Files
dpl/scripts/fuc-xb-launch/runtime.py
T

66 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""Enable only this staging instance's native workers and minute scheduler."""
import hashlib,json,os,pathlib,re,shutil,subprocess
BASE=pathlib.Path('/var/www/wwwroot/fuc-xb-test')
DIR=BASE/'private/launch-ready-20261105/runtime'
UNIT=pathlib.Path('/etc/systemd/system/fuc-xb-test-horizon.service')
CRON=pathlib.Path('/etc/cron.d/fuc-xb-test')
def run(args):
p=subprocess.run(args,capture_output=True,text=True,timeout=60)
assert p.returncode==0,'FUC runtime operation failed; inspect private diagnostic'
return p.stdout.strip()
def main():
os.umask(0o077)
assert not DIR.exists()and not os.path.lexists(UNIT)and not os.path.lexists(CRON),'Existing runtime; inspect instead of overwriting'
for name in [str(UNIT)+'.d']:assert not os.path.lexists(name),'Existing worker override'
ready=json.loads((BASE/'private/launch-ready-20261105/configured.json').read_text())
assert ready['bulk_automatic_mail_disabled']and ready['payment_channels_disabled_until_cutover']
php=r'''putenv('XB_INSTANCE=fuc-xb-test');require $argv[1].'/vendor/autoload.php';$a=require $argv[1].'/bootstrap/app.php';$a->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();if(Illuminate\Support\Facades\DB::connection()->getDatabaseName()!=='fuc_xb_test'||App\Services\MailFlow\AutomaticMailPolicy::state()['level']!==3||admin_setting('remind_mail_enable')||!admin_setting('stop_register')||App\Models\Payment::where('enable',true)->exists())throw new RuntimeException('Isolation guard failed');foreach(['send_email','send_email_mass','send_telegram','default','order_handle']as$q)if(Illuminate\Support\Facades\Queue::size($q))throw new RuntimeException('Unexpected notification/business backlog');echo json_encode(['guarded'=>true]);'''
assert json.loads(run(['runuser','-u','fucxbtest','--','php','-r',php,str(BASE/'current')]))['guarded']
DIR.mkdir(mode=0o700)
envfile=BASE/'shared/.env';before=envfile.read_bytes();shutil.copy2(envfile,DIR/'environment-before');(DIR/'environment-before').chmod(0o600)
text=before.decode();changes={'APP_ENV':'production','MAIL_DRIVER':'smtp','MAIL_MAILER':'smtp','HORIZON_PREFIX':'fuc_xb_test_horizon_','HORIZON_DATA_PIPELINE_MAX':'2','HORIZON_BUSINESS_MAX':'1','HORIZON_NOTIFICATION_MAX':'1','HORIZON_WORKER_MEMORY_MB':'128'}
for k,v in changes.items():
pattern=r'^'+re.escape(k)+r'=.*$'
text=re.sub(pattern,k+'='+v,text,flags=re.M)if re.search(pattern,text,re.M)else text.rstrip()+'\n'+k+'='+v+'\n'
journal={'owner':'fuc-xb-launch-20261105','changed_env_keys':list(changes),'before_env_sha256':hashlib.sha256(before).hexdigest(),'phase':'preparing'}
(DIR/'intent.json').write_text(json.dumps(journal,indent=2));envfile.write_text(text)
unit='''[Unit]
Description=FUC-XB isolated Horizon
After=network-online.target fuc-xb-test-redis.service
Requires=fuc-xb-test-redis.service
[Service]
Type=simple
User=fucxbtest
Group=fucxbtest
Environment=XB_INSTANCE=fuc-xb-test
WorkingDirectory=/var/www/wwwroot/fuc-xb-test/current
ExecStart=/usr/bin/php artisan horizon
Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=90
MemoryMax=768M
CPUQuota=100%
UMask=0027
[Install]
WantedBy=multi-user.target
'''
cron='''SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
* * * * * fucxbtest cd /var/www/wwwroot/fuc-xb-test/current && XB_INSTANCE=fuc-xb-test /usr/bin/php artisan schedule:run >> /var/www/wwwroot/fuc-xb-test/shared/storage/logs/schedule.log 2>&1
'''
try:
run(['runuser','-u','fucxbtest','--','env','XB_INSTANCE=fuc-xb-test','php',str(BASE/'current/artisan'),'config:clear'])
UNIT.write_text(unit);UNIT.chmod(0o644);CRON.write_text(cron);CRON.chmod(0o644)
run(['systemctl','daemon-reload']);run(['systemctl','enable','--now','fuc-xb-test-horizon'])
assert run(['systemctl','is-active','fuc-xb-test-horizon'])=='active'
run(['runuser','-u','fucxbtest','--','env','XB_INSTANCE=fuc-xb-test','php',str(BASE/'current/artisan'),'schedule:run'])
except BaseException:
CRON.unlink(missing_ok=True)
stopped=subprocess.run(['systemctl','disable','--now','fuc-xb-test-horizon'],capture_output=True,timeout=100)
journal['phase']='failed';journal['cleanup_returncode']=stopped.returncode;(DIR/'intent.json').write_text(json.dumps(journal,indent=2));raise
journal.update(phase='active',mail_driver='smtp',queue='redis',automatic_mail_policy=3,payment_channels_enabled=0,worker_unit_sha256=hashlib.sha256(UNIT.read_bytes()).hexdigest(),cron_sha256=hashlib.sha256(CRON.read_bytes()).hexdigest(),after_env_sha256=hashlib.sha256(envfile.read_bytes()).hexdigest())
(DIR/'receipt.json').write_text(json.dumps(journal,indent=2));print(json.dumps(journal))
if __name__=='__main__':main()