#!/usr/bin/env python3 # ------------------------------- UPSCALE TO OBJECT LOCK ------------------------------- # --------- UP-SCALES.COM RECORDS INTO STORAGE WITH A RETENTION LOCK (S3 OBJECT LOCK) ---- # -------------------------------------------------------------------------------------- # A RECEIVER THAT KEEPS THE RECORDS OF YOUR UP↑SCALE SCALES IN A BUCKET WITH A RETENTION # LOCK (THE PROVIDER'S FEATURE: S3 OBJECT LOCK OF AWS S3, BACKBLAZE B2, WASABI, MINIO AND # OTHER S3-COMPATIBLE STORAGE): ONE OBJECT PER RECORD, WITH A RETENTION DATE - UNTIL THEN # THE PROVIDER REFUSES TO DELETE OR OVERWRITE IT. THE RECORD IS ACKNOWLEDGED ONLY AFTER # THE UPLOAD WORKED. AND: THE DAILY FILES OF upscale-receiver.py INTO THE SAME BUCKET. # NOTES FOR AZURE BLOB STORAGE AND GOOGLE CLOUD STORAGE AT THE END OF THIS HEADER. # -------------------------------------------------------------------------------------- # ^^^ AN EXAMPLE - COPY IT AND CHANGE IT AS NEEDED! # It uses boto3 (the AWS SDK for Python), YOUR choice of SDK - it is not part of the # standard library, and this example could not be run against a real bucket by us: # test it with your provider (a test bucket with a short retention) before you use it. # -------------------------------------------------------------------------------------- # WEBHOOK EXPORT OF THE SCALE: https://up-scales.com/manual.html#WiFiWebhook # LIMS / ELN FORWARDING OF THE APP: https://up-scales.com/manual.html#LimsForwarding # ALL EXAMPLES FOR YOUR IT: https://up-scales.com/hardware/integration-lims-webhook-api-examples.html#examples # -------------------------------------------------------------------------------------- # (C) Johann Anderson, 2025-2026 http://farm23.es # -------------------------------------------------------------------------------------- # MIT License - Copyright (c) 2025-2026 Johann Anderson # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to the following # conditions: The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # -------------------------------------------------------------------------------------- # # This script will: # Check every request with the security mode of the scale / the app (1 token, # 2 HMAC-signed, 3 sealed envelope - as upscale-receiver.py). # Upload every new record as one object: # events////.json # with the retention of the bucket's lock (mode + "retain until" = now + the days you # set), and read the retention back from the provider. # Acknowledge the record ({"ack","ref"} - ref = the version id of the object) only # after that - else the scale (or the app) sends it again later. A record that comes # twice (same "id") is found in the bucket and acknowledged again, not stored twice. # Answer "stored" as an archive receiver ({"stored": {"type": "activity" | "legal", # "upto": N, "chain": ""}}, as upscale-receiver.py): N = the newest entry # up to which every entry of the activity log / the LEGAL MODE store is in the # bucket in one chain this script recomputed itself. The scale ("free the entries # the receiver has saved", ENTERPRISE) and the app may then reuse their space. # UPSCALE_STORED=0: only the receipt. # --upload-day: the daily files of upscale-receiver.py (events//.jsonl) # into daily//.jsonl with the same retention (a nightly job). # # -------------------------------------------------------------------------------------- # 1st: What you need: # -------------------------------------------------------------------------------------- # # 1.) A bucket WITH OBJECT LOCK switched on - on most providers only possible when the # bucket is made (it also switches on versioning). The lock modes are the provider's: # GOVERNANCE users with a special right (s3:BypassGovernanceRetention) can still # shorten or remove the retention - good for a test # COMPLIANCE (the provider's name of the strict mode) nobody can shorten it before # the date, also not the account owner - choose it only when you are sure # Read the documentation of your provider: what its lock covers, and what not (e.g. # a deleted account or bucket, the provider's own staff, lost access keys). # An access key that may PutObject, GetObject, GetObjectRetention, PutObjectRetention # (and ListBucket for the doubled-record check). # 2.) Python 3.8 or newer and boto3: pip install boto3 (Debian / Ubuntu: apt install # python3-boto3). Mode 3 (sealed envelope) also: pip install cryptography. # 3.) Your settings (environment variables, or change the defaults below): # UPSCALE_PORT the port of the receiver (default 8082) # UPSCALE_MODES / UPSCALE_TOKENS / UPSCALE_SECRET as in upscale-receiver.py # S3_BUCKET the bucket # S3_PREFIX a folder in it, e.g. "upscale/" (may be empty) # S3_ENDPOINT empty for AWS; else the address of your provider, e.g. # https://s3.eu-central-003.backblazeb2.com (Backblaze B2), # https://s3.eu-central-1.wasabisys.com (Wasabi), # http://minio.local:9000 (your MinIO) # S3_REGION e.g. eu-central-1 # AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY the access key (or a profile / role - # boto3 finds its credentials the usual ways) # RETAIN_DAYS the retention in days (default 3650 = 10 years; a test: 1) # RETAIN_MODE GOVERNANCE (default) or COMPLIANCE # UPSCALE_DATA the folder for the state files (seen records, last n) # # S3_BUCKET=my-records S3_REGION=eu-central-1 RETAIN_DAYS=1 UPSCALE_SECRET=my-secret \ # python3 upscale-to-object-lock.py # python3 upscale-to-object-lock.py --upload-day /srv/upscale-data 2026-11-27 # # A receiver for the copies that stay at hand (the checks of the hash chains, of the # seals and of the chain checkpoints of the scale, requests, poll): upscale-receiver.py # - run both, or give the webhook to this one and let the app's LIMS forwarding post # to the other one. An offline check of its folder: upscale-verify.py. # # -------------------------------------------------------------------------------------- # Azure Blob Storage ("immutability policies" - the provider's name of its retention lock) - # the same idea with the SDK azure-storage-blob: # -------------------------------------------------------------------------------------- # # A container (or storage account) with version-level immutability (the provider's # setting) switched on; then each blob gets its own policy when it is uploaded # ("Unlocked" can still be shortened by an admin, "Locked" not - the provider's modes): # from azure.storage.blob import BlobServiceClient, ImmutabilityPolicy # svc = BlobServiceClient.from_connection_string(os.environ['AZURE_STORAGE_CONNECTION_STRING']) # blob = svc.get_blob_client('upscale-records', object_key(event)) # until = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=RETAIN_DAYS) # blob.upload_blob(body, overwrite=False, # immutability_policy=ImmutabilityPolicy(expiry_time=until, policy_mode='Unlocked')) # Or a time-based retention policy on the whole container (set in the portal, then # "lock" it): every blob in it is kept for that time, the upload needs no policy then. # overwrite=False: a doubled record raises ResourceExistsError = already stored. # # -------------------------------------------------------------------------------------- # Google Cloud Storage (bucket lock) - the same idea with the SDK google-cloud-storage: # -------------------------------------------------------------------------------------- # # A bucket with a RETENTION POLICY (e.g. 10 years); "lock" the policy once you are sure # (after the lock it can not be shortened or removed - the provider's bucket lock). # Every object is then kept for that time after its upload, no setting per object: # from google.cloud import storage # bucket = storage.Client().bucket('upscale-records') # # once: bucket.retention_period = 10 * 365 * 86400; bucket.patch() # # bucket.lock_retention_policy() (can not be undone) # blob = bucket.blob(object_key(event)) # blob.upload_from_string(body, content_type='application/json', if_generation_match=0) # if_generation_match=0: a doubled record raises PreconditionFailed = already stored. # (Buckets made with object retention can also take a retention per object instead.) # # For both: replace put_record() below with these lines and keep the rest - the record # is acknowledged only when the upload did not raise an error. # -------------------------------------------------------------------------------------- import base64, datetime, hashlib, hmac, json, os, re, ssl, sys, threading, time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlparse, parse_qs try: from cryptography.hazmat.primitives.ciphers.aead import AESGCM except ImportError: AESGCM = None try: import boto3 from botocore.config import Config from botocore.exceptions import BotoCoreError, ClientError except ImportError: boto3 = None BotoCoreError = ClientError = Exception # ---------- your settings ---------- env = os.environ.get PORT = int(env('UPSCALE_PORT') or 8082) MODES = [int(m) for m in (env('UPSCALE_MODES') or '1,2,3').split(',') if m.strip()] TOKENS = [t.strip() for t in (env('UPSCALE_TOKENS') or 'CHANGE-ME-TOKEN').split(',') if t.strip()] SECRET = env('UPSCALE_SECRET') or 'CHANGE-ME-SECRET' BUCKET = env('S3_BUCKET') or '' PREFIX = env('S3_PREFIX') or '' ENDPOINT = env('S3_ENDPOINT') or None REGION = env('S3_REGION') or None RETAIN_DAYS = int(env('RETAIN_DAYS') or 3650) RETAIN_MODE = (env('RETAIN_MODE') or 'GOVERNANCE').upper() DATA = (env('UPSCALE_DATA') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'upscale-lock-data')).rstrip('/') ORIGINS = ['https://up-scales.com'] STORED = env('UPSCALE_STORED') != '0' # answer "stored" (the archive receiver) - "0": only the receipt SKIP = ('weight',) # (the live weight: up to one a second - not kept here; remove it from this list to keep it too) S3 = None def s3(): global S3 if S3 is None: if boto3 is None: raise IOError('boto3 is missing (pip install boto3)') try: # (S3-compatible providers: checksums only where the API needs them - boto3 1.36 and newer) cfg = Config(request_checksum_calculation='when_required', response_checksum_validation='when_required') except TypeError: cfg = Config() S3 = boto3.client('s3', endpoint_url=ENDPOINT, region_name=REGION, config=cfg) return S3 def object_key(event): typ = re.sub(r'[^a-z0-9_-]', '', str(event.get('type', '')).lower()) or 'other' dev = re.sub(r'[^A-Za-z0-9]', '', str(event.get('device') or 'unknown')) hid = hashlib.sha256(event['id'].encode()).hexdigest() return '%sevents/%s/%s/%s/%s.json' % (PREFIX, typ, dev, hid[:2], hid) def put_locked(key, body, content_type): """One object with the retention lock -> its version id. Raises IOError when the provider did not confirm it.""" until = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=RETAIN_DAYS) try: r = s3().put_object(Bucket=BUCKET, Key=key, Body=body, ContentType=content_type, ContentMD5=base64.b64encode(hashlib.md5(body).digest()).decode(), ObjectLockMode=RETAIN_MODE, ObjectLockRetainUntilDate=until) version = r.get('VersionId') or '' # read the retention back: the provider says what it keeps (a bucket without Object Lock refuses the upload above) got = s3().get_object_retention(Bucket=BUCKET, Key=key, **({'VersionId': version} if version else {})) ret = got.get('Retention') or {} if ret.get('Mode') != RETAIN_MODE or not ret.get('RetainUntilDate'): raise IOError('no retention on %s' % key) return version except (BotoCoreError, ClientError) as e: raise IOError('upload of %s: %s' % (key, e)) def already_stored(key): try: r = s3().head_object(Bucket=BUCKET, Key=key) return r.get('VersionId') or 'stored' except ClientError as e: if str(e.response.get('Error', {}).get('Code')) in ('404', 'NoSuchKey', 'NotFound'): return '' raise IOError('check of %s: %s' % (key, e)) except BotoCoreError as e: raise IOError('check of %s: %s' % (key, e)) LOCK = threading.Lock() def put_record(event): """A checked record -> (its receipt, max. 36 characters; the "stored" answer or None). Raises IOError when it is not stored (no acknowledgement then).""" hid = hashlib.sha256(event['id'].encode()).hexdigest() marker = os.path.join(DATA, 'state', 'seen', hid[:2], hid) typ = str(event.get('type', '')).lower() if typ in SKIP: return hid[:16], None fresh = False ref = '' with LOCK: if os.path.isfile(marker): with open(marker, encoding='utf-8') as f: ref = f.read().strip() if not ref: key = object_key(event) # (a doubled record after a lost answer or a restart of this receiver: already in the bucket) version = already_stored(key) if not version: version = put_locked(key, json.dumps(dict(event, _rx={'at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}), ensure_ascii=False, separators=(',', ':')).encode('utf-8'), 'application/json') fresh = True print('%s %-10s %s -> %s (until +%d days, %s)' % (time.strftime('%H:%M:%S'), typ, event['id'], key, RETAIN_DAYS, RETAIN_MODE), flush=True) ref = ('S3:' + version)[:36] with LOCK: os.makedirs(os.path.dirname(marker), exist_ok=True) with open(marker, 'w', encoding='utf-8') as f: f.write(ref) stored = None if STORED: # the archive receiver: up to which entry every activity / legal entry is in the bucket in ONE chain recomputed here # (the scale - "free the entries the receiver has saved" - and the app may then reuse their space) with LOCK: path = os.path.join(DATA, 'state', 'stored-marks.json') try: with open(path, encoding='utf-8') as f: marks = json.load(f) except (OSError, ValueError): marks = {} m = stored_step(event, marks, fresh) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path + '.tmp', 'w', encoding='utf-8') as f: json.dump(marks, f) os.replace(path + '.tmp', path) if m and not m.get('base'): stored = {'type': typ, 'upto': m['num'], 'chain': m['h']} return ref, stored # ---------- the archive receiver: the hash chains (as in upscale-receiver.py) ---------- def entry_parts(ev): """The parts of an activity / legal entry: (device, type, size, number, raw bytes, H after it or '', H before it or '' - the app sends "hb" at the start of a piece) | None: not such an event | a text: why not. activity: H = SHA-256(H before | seq as uint32 little-endian | the entry, 16 bytes) legal: H = SHA-256(H before | the entry, 48 bytes) The scale sends "raw" as base64 and "chain" (H after the entry) as hex; the app sends "raw" and "h" as hex.""" typ, d = ev.get('type'), ev.get('data') if typ not in ('activity', 'legal') or not isinstance(d, dict): return None size = 16 if typ == 'activity' else 48 num = d.get('seq', d.get('number', d.get('no'))) if isinstance(num, str): num = re.sub(r'[^0-9]', '', num) if num is None or num == '': return 'no number' r = str(d.get('raw') or '') try: raw = bytes.fromhex(r) if len(r) == 2 * size and re.fullmatch(r'[0-9a-fA-F]+', r) else base64.b64decode(r, validate=True) except ValueError: raw = b'' h = '' for k in ('chain', 'h'): v = d.get(k) if isinstance(v, str) and re.fullmatch(r'[0-9a-fA-F]{64}', v): h = v.lower() break hb = d['hb'].lower() if isinstance(d.get('hb'), str) and re.fullmatch(r'[0-9a-fA-F]{64}', d['hb']) else '' return str(ev.get('device') or d.get('device') or '').lower(), typ, size, int(num), raw, h, hb def chain_link(typ, before, num, raw): return hashlib.sha256(bytes.fromhex(before) + (num.to_bytes(4, 'little') if typ == 'activity' else b'') + raw).hexdigest() def stored_step(ev, marks, fresh): """THE ARCHIVE RECEIVER ("stored"): per scale + kind the newest entry up to which every entry is on the disk in ONE chain this script recomputed itself - marks[key] = {'num', 'h'} ('base': only the first entry of a run is known, its H came with it, nothing is recomputed yet). fresh: the entry was written now (False: it was on the disk already - the scale sends again). The run goes on with the next number (also a resend of one that is on the disk); a new entry further back starts a new run (the scale sends again since its last archive); a gap stops it until the missing entries come (ask for them: {"get":"legal","since":...}). The first entry of a log (activity 0, legal 1) links to the zero start.""" p = entry_parts(ev) if p is None or isinstance(p, str): return None dev, typ, size, num, raw, h, hb = p if not hb and num == (0 if typ == 'activity' else 1): hb = '00' * 32 key = dev + ':' + typ m = marks.get(key) if len(raw) != size: return m if m and num == m['num'] + 1: calc = chain_link(typ, m['h'], num, raw) if not h or hmac.compare_digest(calc, h): marks[key] = {'num': num, 'h': calc} elif fresh and (not m or num <= m['num']): if hb: calc = chain_link(typ, hb, num, raw) if not h or hmac.compare_digest(calc, h): marks[key] = {'num': num, 'h': calc} elif h: marks[key] = {'num': num, 'h': h, 'base': True} return marks.get(key) def upload_day(folder, day): """The daily JSONL files of upscale-receiver.py (/events//.jsonl) into daily//.jsonl.""" base = os.path.join(folder, 'events') n = 0 for typ in sorted(os.listdir(base)): path = os.path.join(base, typ, day + '.jsonl') if not os.path.isfile(path): continue key = '%sdaily/%s/%s.jsonl' % (PREFIX, typ, day) if already_stored(key): print('%s is in the bucket already - not again (a day is uploaded once, after it ended)' % key) continue with open(path, 'rb') as f: body = f.read() version = put_locked(key, body, 'application/x-ndjson') print('%s -> %s (%d bytes, SHA-256 %s, version %s)' % (path, key, len(body), hashlib.sha256(body).hexdigest(), version)) n += 1 print('%d files' % n) # ---------- the receiver (the security modes as in upscale-receiver.py) ---------- def not_set(s): return not s or s.startswith('CHANGE-ME') def seal_nonce(device, n, answer): d = bytes.fromhex(device) return (bytes(b ^ 0xFF for b in d) if answer else d) + n.to_bytes(6, 'little') class Refused(Exception): def __init__(self, code, text): Exception.__init__(self, text) self.code, self.text = code, text class Handler(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def log_message(self, *a): pass def send(self, code, body=b'', headers=None): self.send_response(code) origin = self.headers.get('Origin', '') self.send_header('Access-Control-Allow-Origin', origin if origin in ORIGINS else ORIGINS[0]) self.send_header('Vary', 'Origin') self.send_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization') self.send_header('Access-Control-Allow-Private-Network', 'true') for k, v in (headers or {}).items(): self.send_header(k, v) self.send_header('Content-Type', 'application/json') self.send_header('Content-Length', str(len(body))) self.end_headers() self.wfile.write(body) def do_OPTIONS(self): self.send(204) def do_GET(self): self.any(True) def do_POST(self): self.any(False) def any(self, is_poll): try: code, body, headers = self.process(is_poll) except Refused as e: print('%s refused %d %s (%s)' % (time.strftime('%H:%M:%S'), e.code, e.text, self.client_address[0]), file=sys.stderr, flush=True) code, body, headers = e.code, json.dumps({'error': e.text}).encode(), {} self.send(code, body, headers) def process(self, is_poll): q = parse_qs(urlparse(self.path).query) qget = lambda k: (q.get(k) or [''])[0] hdr = lambda k: self.headers.get(k, '') if is_poll and qget('poll') != '1': raise Refused(405, 'GET only for the poll') raw = b'' if is_poll else self.rfile.read(int(hdr('Content-Length') or 0)) try: body = None if is_poll else json.loads(raw.decode('utf-8')) except ValueError: body = None if hdr('X-Upscale-Signature'): mode = 2 elif ('n' in q) if is_poll else (isinstance(body, dict) and body.get('schema') == 'upscale.sealed/1'): mode = 3 else: mode = 1 if mode not in MODES: raise Refused(401, 'mode %d not accepted here' % mode) device = qget('device') if is_poll else str(body.get('device') or '') if isinstance(body, dict) else '' event, nonce, n = body, '', 0 if mode == 1: auth = hdr('Authorization') given = auth[7:] if auth.startswith('Bearer ') else (hdr('X-API-Key') or qget('token')) if not any(not not_set(t) and hmac.compare_digest(t.encode(), given.encode()) for t in TOKENS): raise Refused(401, 'mode 1: wrong or missing token') elif mode == 2: if not_set(SECRET): raise Refused(503, 'set UPSCALE_SECRET') nonce = hdr('X-Upscale-Nonce') want = 'sha256=' + hmac.new(SECRET.encode(), (hdr('X-Upscale-Time') + '.' + nonce + '.').encode() + raw, hashlib.sha256).hexdigest() if not hmac.compare_digest(want.encode(), hdr('X-Upscale-Signature').encode('utf-8', 'replace')): raise Refused(401, 'mode 2: signature wrong') else: if AESGCM is None or not_set(SECRET): raise Refused(500 if AESGCM is None else 503, 'mode 3 needs the package "cryptography" and UPSCALE_SECRET') n = qget('n') if is_poll else body.get('n') if not re.fullmatch(r'[0-9a-fA-F]{12}', device) or not re.fullmatch(r'[0-9]{1,15}', str(n)): raise Refused(400, 'mode 3: device or n wrong') n = int(n) aes = AESGCM(hashlib.sha256(SECRET.encode()).digest()) try: if is_poll: # (the poll: t = the GCM tag of an empty text) if not hmac.compare_digest(aes.encrypt(seal_nonce(device, n, False), b'', None).hex(), qget('t').lower()): raise ValueError event = None else: event = json.loads(aes.decrypt(seal_nonce(device, n, False), base64.b64decode(str(body.get('ct') or '')), None)) except Exception: raise Refused(401, 'mode 3: the envelope does not open') # n only goes up, per scale with LOCK: os.makedirs(os.path.join(DATA, 'state'), exist_ok=True) path = os.path.join(DATA, 'state', 'last-n-' + device.lower()) last = int(open(path).read() or 0) if os.path.isfile(path) else 0 if n <= last: raise Refused(409, 'mode 3: n %d not higher than %d (replay)' % (n, last)) with open(path, 'w') as f: f.write(str(n)) answer, status = {}, 200 if not is_poll: if not isinstance(event, dict) or not isinstance(event.get('id'), str) or not event['id'] or not event.get('type'): if mode == 1: raise Refused(400, 'not a record') answer, status = {'error': 'not a record'}, 400 else: try: ref, stored = put_record(event) answer = {'ack': event['id'], 'ref': ref} if stored: answer['stored'] = stored except (IOError, OSError) as e: # (no acknowledgement: the scale / the app sends the record again later) print('%s NOT stored: %s' % (time.strftime('%H:%M:%S'), e), file=sys.stderr, flush=True) if mode == 1: raise Refused(503, 'not stored') answer, status = {'error': 'not stored'}, 503 out = json.dumps(answer, ensure_ascii=False, separators=(',', ':')).encode('utf-8') headers = {} if mode == 2: t = str(int(time.time())) headers = {'X-Upscale-Time': t, 'X-Upscale-Nonce': nonce, 'X-Upscale-Signature': 'sha256=' + hmac.new(SECRET.encode(), (t + '.' + nonce + '.').encode() + out, hashlib.sha256).hexdigest()} elif mode == 3: ct = AESGCM(hashlib.sha256(SECRET.encode()).digest()).encrypt(seal_nonce(device, n, True), out, None) out = json.dumps({'schema': 'upscale.sealed/1', 'n': n, 'ct': base64.b64encode(ct).decode()}).encode() return status, out, headers def main(): if not BUCKET: sys.exit('set S3_BUCKET (and S3_REGION / S3_ENDPOINT, the access key)') if boto3 is None: sys.exit('boto3 is missing: pip install boto3') if len(sys.argv) == 4 and sys.argv[1] == '--upload-day': return upload_day(sys.argv[2], sys.argv[3]) srv = ThreadingHTTPServer(('0.0.0.0', PORT), Handler) scheme = 'http' if env('UPSCALE_CERT'): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain(env('UPSCALE_CERT'), env('UPSCALE_KEY')) srv.socket = ctx.wrap_socket(srv.socket, server_side=True) scheme = 'https' print('UP-SCALE to object lock on %s://0.0.0.0:%d - modes %s - bucket %s/%s - %d days %s' % ( scheme, PORT, ','.join(map(str, MODES)), BUCKET, PREFIX, RETAIN_DAYS, RETAIN_MODE), flush=True) try: srv.serve_forever() except KeyboardInterrupt: pass if __name__ == '__main__': main()