Files
rust-discovery/tools/dev_customer_starters.py
T

102 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Publish selected signed agent packages for first enrollment in empty customer catalogs."""
import argparse
import hashlib
import inspect
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import tempfile
import uuid
from dev_stage import ssh_prefix
def publish(tenant, platform, release, official_windows=False, *, root=Path('/opt/rust-discovery/devstate/mvp-releases'),
database_container='rust-discovery-server-postgres-1', service_uid=10001):
labels = {'x86_64-pc-windows-gnu': 'windows-gnu', 'x86_64-unknown-linux-gnu': 'linux'}
label = labels[platform]
if official_windows:
if platform != 'x86_64-pc-windows-gnu':
raise ValueError('Official Windows starter requires GNU x64')
label = 'windows-gnu-official'
source = root / 'objects' / tenant
config = root / 'config'
dest = config / 'customer-starters'
sql = """SELECT json_build_object('envelope',convert_from(envelope,'UTF8')::json,
'agent',agent_sha256,'agent_size',agent_bytes,'helper',helper_sha256,'helper_size',helper_bytes,
'starter_worker',(SELECT json_build_object('sha256',sha256,'bytes',size_bytes)
FROM customer_starter_workers WHERE tenant_id=:'customer' AND platform=:'platform' AND official_windows=:'official'::boolean))
FROM agent_update_releases WHERE tenant_id=:'customer' AND platform=:'platform' AND release_id=:'release';"""
raw = subprocess.check_output(['docker','exec','-i',database_container,
'psql','-XqtA','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm','-v','customer='+tenant,
'-v','platform='+platform,'-v','official='+str(official_windows),'-v','release='+release],input=sql.encode())
if not raw.strip():
raise ValueError('Selected release is missing from the source customer catalog')
row = json.loads(raw)
local_pin = config / (label+'-bootstrap.'+tenant+'.json')
if local_pin.exists():
worker = json.loads(local_pin.read_bytes())['current']
elif row['starter_worker']:
worker = row['starter_worker']
else:
default = json.loads((config / (label+'-bootstrap.json')).read_bytes())
worker = {'sha256': default['updater_sha256'], 'bytes': default['updater_bytes']}
desc = {'envelope': row['envelope'], 'worker': worker}
dest.mkdir(mode=0o700,exist_ok=True)
if not dest.is_dir() or dest.is_symlink():
raise ValueError('Protected starter directory required')
os.chown(dest,service_uid,service_uid)
os.chmod(dest,0o700)
def write(name, blocks):
with tempfile.NamedTemporaryFile(dir=dest,delete=False) as out:
temp = Path(out.name)
try:
digest = hashlib.sha256()
for data in blocks:
out.write(data)
digest.update(data)
if len(name)==64 and digest.hexdigest()!=name:
raise ValueError('Package object digest mismatch')
out.flush()
os.fchown(out.fileno(),service_uid,service_uid)
os.fsync(out.fileno())
os.replace(temp,dest/name)
finally:
temp.unlink(missing_ok=True)
for digest,size in [(row['agent'],row['agent_size']),(row['helper'],row['helper_size']),(worker['sha256'],worker['bytes'])]:
if not re.fullmatch('[a-f0-9]{64}',digest) or not 0<size<=268435456:
raise ValueError('Invalid package descriptor')
with os.fdopen(os.open(source/digest,os.O_RDONLY|os.O_NOFOLLOW),'rb') as f:
info=os.fstat(f.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_size!=size:
raise ValueError('Missing regular package file')
write(digest,iter(lambda:f.read(1024*1024),b''))
descriptor = platform + ('-official.json' if official_windows else '.json')
write(descriptor,[json.dumps(desc,separators=(',',':')).encode()])
directory_fd = os.open(dest, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
print(json.dumps({'starter_platform':platform,'release_id':release}))
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--tenant',required=True,type=uuid.UUID)
parser.add_argument('--platform',required=True,choices=['x86_64-unknown-linux-gnu','x86_64-pc-windows-gnu'])
parser.add_argument('--official-windows',action='store_true')
parser.add_argument('--release',required=True,type=uuid.UUID)
args=parser.parse_args()
imports='import hashlib,json,os,re,stat,subprocess,tempfile\nfrom pathlib import Path\n'
script=imports+inspect.getsource(publish)+'\npublish'+repr((str(args.tenant),args.platform,str(args.release),args.official_windows))
subprocess.run([*ssh_prefix('server'),'python3 -I -'],input=script,text=True,check=True)
if __name__=='__main__':
main()