2022-12-21 09:41:20 +00:00
|
|
|
import logging
|
2022-12-20 13:55:07 +00:00
|
|
|
from base64 import b64encode as b64enc
|
2022-12-16 12:51:14 +00:00
|
|
|
from hashlib import sha256
|
|
|
|
from uuid import uuid4
|
2022-12-19 13:27:10 +00:00
|
|
|
from os.path import join, dirname
|
2022-12-19 13:44:26 +00:00
|
|
|
from os import getenv
|
2022-12-21 09:41:20 +00:00
|
|
|
|
2022-12-21 09:53:51 +00:00
|
|
|
from dotenv import load_dotenv
|
2022-12-16 12:51:14 +00:00
|
|
|
from fastapi import FastAPI, HTTPException
|
|
|
|
from fastapi.requests import Request
|
2022-12-20 17:24:59 +00:00
|
|
|
from fastapi.encoders import jsonable_encoder
|
2022-12-16 12:51:14 +00:00
|
|
|
import json
|
2022-12-19 12:11:28 +00:00
|
|
|
from datetime import datetime
|
|
|
|
from dateutil.relativedelta import relativedelta
|
2022-12-16 12:51:14 +00:00
|
|
|
from calendar import timegm
|
|
|
|
from jose import jws, jwk, jwt
|
|
|
|
from jose.constants import ALGORITHMS
|
2022-12-21 09:41:20 +00:00
|
|
|
from starlette.middleware.cors import CORSMiddleware
|
2022-12-21 06:33:20 +00:00
|
|
|
from starlette.responses import StreamingResponse, JSONResponse, HTMLResponse
|
2022-12-20 13:55:07 +00:00
|
|
|
import dataset
|
2022-12-20 13:45:44 +00:00
|
|
|
from Crypto.PublicKey import RSA
|
|
|
|
from Crypto.PublicKey.RSA import RsaKey
|
|
|
|
|
2022-12-21 09:40:05 +00:00
|
|
|
logger = logging.getLogger()
|
2022-12-21 10:06:09 +00:00
|
|
|
load_dotenv('../version.env')
|
2022-12-21 09:40:05 +00:00
|
|
|
|
|
|
|
VERSION, COMMIT, DEBUG = getenv('VERSION', 'unknown'), getenv('COMMIT', 'unknown'), bool(getenv('DEBUG', False))
|
|
|
|
|
2022-12-20 13:45:44 +00:00
|
|
|
|
|
|
|
def load_file(filename) -> bytes:
|
|
|
|
with open(filename, 'rb') as file:
|
|
|
|
content = file.read()
|
|
|
|
return content
|
|
|
|
|
|
|
|
|
|
|
|
def load_key(filename) -> RsaKey:
|
|
|
|
return RSA.import_key(extern_key=load_file(filename), passphrase=None)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
|
2022-12-16 12:54:55 +00:00
|
|
|
# todo: initialize certificate (or should be done by user, and passed through "volumes"?)
|
|
|
|
|
2022-12-21 09:41:20 +00:00
|
|
|
__details = dict(
|
|
|
|
title='FastAPI-DLS',
|
|
|
|
description='Minimal Delegated License Service (DLS).',
|
|
|
|
version=VERSION,
|
|
|
|
)
|
|
|
|
|
|
|
|
app, db = FastAPI(**__details), dataset.connect(str(getenv('DATABASE', 'sqlite:///db.sqlite')))
|
2022-12-16 12:51:14 +00:00
|
|
|
|
2022-12-20 17:06:32 +00:00
|
|
|
TOKEN_EXPIRE_DELTA = relativedelta(hours=1) # days=1
|
2022-12-20 14:05:50 +00:00
|
|
|
LEASE_EXPIRE_DELTA = relativedelta(days=int(getenv('LEASE_EXPIRE_DAYS', 90)))
|
2022-12-19 12:15:19 +00:00
|
|
|
|
2022-12-19 13:48:13 +00:00
|
|
|
DLS_URL = str(getenv('DLS_URL', 'localhost'))
|
|
|
|
DLS_PORT = int(getenv('DLS_PORT', '443'))
|
2022-12-19 13:44:26 +00:00
|
|
|
SITE_KEY_XID = getenv('SITE_KEY_XID', '00000000-0000-0000-0000-000000000000')
|
2022-12-19 13:27:10 +00:00
|
|
|
INSTANCE_KEY_RSA = load_key(join(dirname(__file__), 'cert/instance.private.pem'))
|
|
|
|
INSTANCE_KEY_PUB = load_key(join(dirname(__file__), 'cert/instance.public.pem'))
|
2022-12-16 12:51:14 +00:00
|
|
|
|
2022-12-21 09:41:20 +00:00
|
|
|
CORS_ORIGINS = getenv('CORS_ORIGINS').split(',') if (getenv('CORS_ORIGINS')) else f'https://{DLS_URL}' # todo: prevent static https
|
|
|
|
|
2022-12-20 13:55:07 +00:00
|
|
|
jwt_encode_key = jwk.construct(INSTANCE_KEY_RSA.export_key().decode('utf-8'), algorithm=ALGORITHMS.RS256)
|
|
|
|
jwt_decode_key = jwk.construct(INSTANCE_KEY_PUB.export_key().decode('utf-8'), algorithm=ALGORITHMS.RS512)
|
|
|
|
|
2022-12-21 09:41:20 +00:00
|
|
|
app.debug = DEBUG
|
|
|
|
app.add_middleware(
|
|
|
|
CORSMiddleware,
|
|
|
|
allow_origins=CORS_ORIGINS,
|
|
|
|
allow_credentials=True,
|
|
|
|
allow_methods=["*"],
|
|
|
|
allow_headers=["*"],
|
|
|
|
)
|
|
|
|
|
|
|
|
logger.setLevel(logging.DEBUG if DEBUG else logging.INFO)
|
|
|
|
|
2022-12-16 12:51:14 +00:00
|
|
|
|
2022-12-20 17:06:32 +00:00
|
|
|
def get_token(request: Request) -> dict:
|
|
|
|
authorization_header = request.headers['authorization']
|
|
|
|
token = authorization_header.split(' ')[1]
|
2022-12-21 07:00:52 +00:00
|
|
|
return jwt.decode(token=token, key=jwt_decode_key, algorithms=ALGORITHMS.RS256, options={'verify_aud': False})
|
2022-12-20 17:06:32 +00:00
|
|
|
|
|
|
|
|
2022-12-16 12:51:14 +00:00
|
|
|
@app.get('/')
|
|
|
|
async def index():
|
2022-12-21 06:33:20 +00:00
|
|
|
from markdown import markdown
|
|
|
|
content = load_file('../README.md').decode('utf-8')
|
|
|
|
return HTMLResponse(markdown(text=content, extensions=['tables', 'fenced_code', 'md_in_html', 'nl2br', 'toc']))
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
|
2022-12-16 12:53:32 +00:00
|
|
|
@app.get('/status')
|
|
|
|
async def status(request: Request):
|
2022-12-21 09:40:05 +00:00
|
|
|
return JSONResponse({'status': 'up', 'version': VERSION, 'commit': COMMIT, 'debug': DEBUG})
|
2022-12-16 12:53:32 +00:00
|
|
|
|
|
|
|
|
2022-12-20 17:24:59 +00:00
|
|
|
@app.get('/-/origins')
|
|
|
|
async def _origins(request: Request):
|
|
|
|
response = list(map(lambda x: jsonable_encoder(x), db['origin'].all()))
|
|
|
|
return JSONResponse(response)
|
|
|
|
|
|
|
|
|
|
|
|
@app.get('/-/leases')
|
|
|
|
async def _leases(request: Request):
|
|
|
|
response = list(map(lambda x: jsonable_encoder(x), db['lease'].all()))
|
|
|
|
return JSONResponse(response)
|
|
|
|
|
|
|
|
|
2022-12-16 12:51:14 +00:00
|
|
|
# venv/lib/python3.9/site-packages/nls_core_service_instance/service_instance_token_manager.py
|
|
|
|
@app.get('/client-token')
|
|
|
|
async def client_token():
|
|
|
|
cur_time = datetime.utcnow()
|
2022-12-19 12:11:28 +00:00
|
|
|
exp_time = cur_time + relativedelta(years=12)
|
2022-12-19 14:51:49 +00:00
|
|
|
|
|
|
|
service_instance_public_key_configuration = {
|
|
|
|
"service_instance_public_key_me": {
|
|
|
|
"mod": hex(INSTANCE_KEY_PUB.public_key().n)[2:],
|
|
|
|
"exp": INSTANCE_KEY_PUB.public_key().e,
|
|
|
|
},
|
|
|
|
"service_instance_public_key_pem": INSTANCE_KEY_PUB.export_key().decode('utf-8'),
|
|
|
|
"key_retention_mode": "LATEST_ONLY"
|
|
|
|
}
|
|
|
|
|
2022-12-16 12:51:14 +00:00
|
|
|
payload = {
|
|
|
|
"jti": str(uuid4()),
|
|
|
|
"iss": "NLS Service Instance",
|
|
|
|
"aud": "NLS Licensed Client",
|
2022-12-19 12:52:16 +00:00
|
|
|
"iat": timegm(cur_time.timetuple()),
|
|
|
|
"nbf": timegm(cur_time.timetuple()),
|
|
|
|
"exp": timegm(exp_time.timetuple()),
|
2022-12-16 12:51:14 +00:00
|
|
|
"update_mode": "ABSOLUTE",
|
2022-12-19 14:51:49 +00:00
|
|
|
"scope_ref_list": [str(uuid4())],
|
2022-12-16 12:51:14 +00:00
|
|
|
"fulfillment_class_ref_list": [],
|
|
|
|
"service_instance_configuration": {
|
2022-12-19 14:51:49 +00:00
|
|
|
"nls_service_instance_ref": "00000000-0000-0000-0000-000000000000",
|
2022-12-16 12:51:14 +00:00
|
|
|
"svc_port_set_list": [
|
|
|
|
{
|
|
|
|
"idx": 0,
|
|
|
|
"d_name": "DLS",
|
2022-12-20 17:06:32 +00:00
|
|
|
"svc_port_map": [{"service": "auth", "port": DLS_PORT}, {"service": "lease", "port": DLS_PORT}]
|
2022-12-16 12:51:14 +00:00
|
|
|
}
|
|
|
|
],
|
2022-12-19 13:44:26 +00:00
|
|
|
"node_url_list": [{"idx": 0, "url": DLS_URL, "url_qr": DLS_URL, "svc_port_set_idx": 0}]
|
2022-12-16 12:51:14 +00:00
|
|
|
},
|
2022-12-19 14:51:49 +00:00
|
|
|
"service_instance_public_key_configuration": service_instance_public_key_configuration,
|
2022-12-16 12:51:14 +00:00
|
|
|
}
|
|
|
|
|
2022-12-21 07:00:52 +00:00
|
|
|
content = jws.sign(payload, key=jwt_encode_key, headers=None, algorithm=ALGORITHMS.RS256)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
2022-12-20 17:06:32 +00:00
|
|
|
response = StreamingResponse(iter([content]), media_type="text/plain")
|
2022-12-19 21:20:50 +00:00
|
|
|
filename = f'client_configuration_token_{datetime.now().strftime("%d-%m-%y-%H-%M-%S")}'
|
|
|
|
response.headers["Content-Disposition"] = f'attachment; filename={filename}'
|
2022-12-20 17:06:32 +00:00
|
|
|
|
2022-12-16 12:51:14 +00:00
|
|
|
return response
|
|
|
|
|
|
|
|
|
|
|
|
# venv/lib/python3.9/site-packages/nls_services_auth/test/test_origins_controller.py
|
2022-12-20 13:55:07 +00:00
|
|
|
# {"candidate_origin_ref":"00112233-4455-6677-8899-aabbccddeeff","environment":{"fingerprint":{"mac_address_list":["ff:ff:ff:ff:ff:ff"]},"hostname":"my-hostname","ip_address_list":["192.168.178.123","fe80::","fe80::1%enp6s18"],"guest_driver_version":"510.85.02","os_platform":"Debian GNU/Linux 11 (bullseye) 11","os_version":"11 (bullseye)"},"registration_pending":false,"update_pending":false}
|
2022-12-16 12:51:14 +00:00
|
|
|
@app.post('/auth/v1/origin')
|
2022-12-21 07:00:52 +00:00
|
|
|
async def auth_v1_origin(request: Request):
|
2022-12-20 13:55:07 +00:00
|
|
|
j = json.loads((await request.body()).decode('utf-8'))
|
|
|
|
|
2022-12-20 17:06:32 +00:00
|
|
|
origin_ref = j['candidate_origin_ref']
|
2022-12-21 09:45:45 +00:00
|
|
|
logging.info(f'> [ origin ]: {origin_ref}: {j}')
|
2022-12-20 13:55:07 +00:00
|
|
|
|
|
|
|
data = dict(
|
2022-12-20 17:06:32 +00:00
|
|
|
origin_ref=origin_ref,
|
2022-12-20 13:55:07 +00:00
|
|
|
hostname=j['environment']['hostname'],
|
|
|
|
guest_driver_version=j['environment']['guest_driver_version'],
|
2022-12-20 17:06:32 +00:00
|
|
|
os_platform=j['environment']['os_platform'], os_version=j['environment']['os_version'],
|
2022-12-20 13:55:07 +00:00
|
|
|
)
|
2022-12-20 17:06:32 +00:00
|
|
|
|
|
|
|
db['origin'].upsert(data, ['origin_ref'])
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
cur_time = datetime.utcnow()
|
|
|
|
response = {
|
2022-12-20 17:06:32 +00:00
|
|
|
"origin_ref": origin_ref,
|
2022-12-19 14:51:49 +00:00
|
|
|
"environment": j['environment'],
|
2022-12-16 12:51:14 +00:00
|
|
|
"svc_port_set_list": None,
|
|
|
|
"node_url_list": None,
|
|
|
|
"node_query_order": None,
|
|
|
|
"prompts": None,
|
2022-12-20 05:47:40 +00:00
|
|
|
"sync_timestamp": cur_time.isoformat()
|
2022-12-16 12:51:14 +00:00
|
|
|
}
|
2022-12-20 17:06:32 +00:00
|
|
|
|
2022-12-20 05:47:40 +00:00
|
|
|
return JSONResponse(response)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
# venv/lib/python3.9/site-packages/nls_services_auth/test/test_auth_controller.py
|
|
|
|
# venv/lib/python3.9/site-packages/nls_core_auth/auth.py - CodeResponse
|
2022-12-20 13:55:07 +00:00
|
|
|
# {"code_challenge":"...","origin_ref":"00112233-4455-6677-8899-aabbccddeeff"}
|
2022-12-16 12:51:14 +00:00
|
|
|
@app.post('/auth/v1/code')
|
2022-12-21 07:00:52 +00:00
|
|
|
async def auth_v1_code(request: Request):
|
2022-12-20 13:55:07 +00:00
|
|
|
j = json.loads((await request.body()).decode('utf-8'))
|
|
|
|
|
|
|
|
origin_ref = j['origin_ref']
|
2022-12-21 09:45:45 +00:00
|
|
|
logging.info(f'> [ code ]: {origin_ref}: {j}')
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
cur_time = datetime.utcnow()
|
2022-12-20 17:06:32 +00:00
|
|
|
delta = relativedelta(minutes=15)
|
|
|
|
expires = cur_time + delta
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
payload = {
|
|
|
|
'iat': timegm(cur_time.timetuple()),
|
|
|
|
'exp': timegm(expires.timetuple()),
|
|
|
|
'challenge': j['code_challenge'],
|
2022-12-23 05:56:29 +00:00
|
|
|
'origin_ref': j['origin_ref'],
|
2022-12-16 12:51:14 +00:00
|
|
|
'key_ref': SITE_KEY_XID,
|
|
|
|
'kid': SITE_KEY_XID
|
|
|
|
}
|
|
|
|
|
2022-12-21 07:00:52 +00:00
|
|
|
auth_code = jws.sign(payload, key=jwt_encode_key, headers={'kid': payload.get('kid')}, algorithm=ALGORITHMS.RS256)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
response = {
|
|
|
|
"auth_code": auth_code,
|
2022-12-20 05:47:40 +00:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 12:51:14 +00:00
|
|
|
"prompts": None
|
|
|
|
}
|
2022-12-20 17:06:32 +00:00
|
|
|
|
2022-12-20 05:47:40 +00:00
|
|
|
return JSONResponse(response)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
# venv/lib/python3.9/site-packages/nls_services_auth/test/test_auth_controller.py
|
|
|
|
# venv/lib/python3.9/site-packages/nls_core_auth/auth.py - TokenResponse
|
2022-12-20 13:55:07 +00:00
|
|
|
# {"auth_code":"...","code_verifier":"..."}
|
2022-12-16 12:51:14 +00:00
|
|
|
@app.post('/auth/v1/token')
|
2022-12-21 07:00:52 +00:00
|
|
|
async def auth_v1_token(request: Request):
|
2022-12-20 13:55:07 +00:00
|
|
|
j = json.loads((await request.body()).decode('utf-8'))
|
|
|
|
payload = jwt.decode(token=j['auth_code'], key=jwt_decode_key)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
2022-12-23 05:56:29 +00:00
|
|
|
origin_ref = payload['origin_ref']
|
|
|
|
logging.info(f'> [ auth ]: {origin_ref}: {j}')
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
# validate the code challenge
|
2022-12-20 13:55:07 +00:00
|
|
|
if payload['challenge'] != b64enc(sha256(j['code_verifier'].encode('utf-8')).digest()).rstrip(b'=').decode('utf-8'):
|
2022-12-20 17:06:32 +00:00
|
|
|
raise HTTPException(status_code=401, detail='expected challenge did not match verifier')
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
cur_time = datetime.utcnow()
|
2022-12-20 17:06:32 +00:00
|
|
|
access_expires_on = cur_time + TOKEN_EXPIRE_DELTA
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
new_payload = {
|
|
|
|
'iat': timegm(cur_time.timetuple()),
|
|
|
|
'nbf': timegm(cur_time.timetuple()),
|
|
|
|
'iss': 'https://cls.nvidia.org',
|
|
|
|
'aud': 'https://cls.nvidia.org',
|
|
|
|
'exp': timegm(access_expires_on.timetuple()),
|
2022-12-23 05:56:29 +00:00
|
|
|
'origin_ref': origin_ref,
|
2022-12-16 12:51:14 +00:00
|
|
|
'key_ref': SITE_KEY_XID,
|
|
|
|
'kid': SITE_KEY_XID,
|
|
|
|
}
|
|
|
|
|
2022-12-21 07:00:52 +00:00
|
|
|
auth_token = jwt.encode(new_payload, key=jwt_encode_key, headers={'kid': payload.get('kid')}, algorithm=ALGORITHMS.RS256)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
response = {
|
2022-12-20 05:47:40 +00:00
|
|
|
"expires": access_expires_on.isoformat(),
|
2022-12-16 12:51:14 +00:00
|
|
|
"auth_token": auth_token,
|
2022-12-20 05:47:40 +00:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 12:51:14 +00:00
|
|
|
}
|
|
|
|
|
2022-12-20 05:47:40 +00:00
|
|
|
return JSONResponse(response)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
|
2022-12-20 13:55:07 +00:00
|
|
|
# {'fulfillment_context': {'fulfillment_class_ref_list': []}, 'lease_proposal_list': [{'license_type_qualifiers': {'count': 1}, 'product': {'name': 'NVIDIA RTX Virtual Workstation'}}], 'proposal_evaluation_mode': 'ALL_OF', 'scope_ref_list': ['00112233-4455-6677-8899-aabbccddeeff']}
|
2022-12-16 12:51:14 +00:00
|
|
|
@app.post('/leasing/v1/lessor')
|
2022-12-21 07:00:52 +00:00
|
|
|
async def leasing_v1_lessor(request: Request):
|
2022-12-20 17:06:32 +00:00
|
|
|
j, token = json.loads((await request.body()).decode('utf-8')), get_token(request)
|
2022-12-20 13:55:07 +00:00
|
|
|
|
2022-12-23 05:56:29 +00:00
|
|
|
origin_ref = token['origin_ref']
|
2022-12-20 13:55:07 +00:00
|
|
|
scope_ref_list = j['scope_ref_list']
|
2022-12-23 05:56:29 +00:00
|
|
|
logging.info(f'> [ create ]: {origin_ref}: create leases for scope_ref_list {scope_ref_list}')
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
cur_time = datetime.utcnow()
|
|
|
|
lease_result_list = []
|
2022-12-20 13:55:07 +00:00
|
|
|
for scope_ref in scope_ref_list:
|
2022-12-20 17:06:32 +00:00
|
|
|
expires = cur_time + LEASE_EXPIRE_DELTA
|
2022-12-16 12:51:14 +00:00
|
|
|
lease_result_list.append({
|
|
|
|
"ordinal": 0,
|
2022-12-20 17:06:32 +00:00
|
|
|
# https://docs.nvidia.com/license-system/latest/nvidia-license-system-user-guide/index.html
|
2022-12-16 12:51:14 +00:00
|
|
|
"lease": {
|
|
|
|
"ref": scope_ref,
|
2022-12-20 05:47:40 +00:00
|
|
|
"created": cur_time.isoformat(),
|
2022-12-20 17:06:32 +00:00
|
|
|
"expires": expires.isoformat(),
|
|
|
|
# The percentage of the lease period that must elapse before a licensed client can renew a license
|
2022-12-16 12:51:14 +00:00
|
|
|
"recommended_lease_renewal": 0.15,
|
|
|
|
"offline_lease": "true",
|
|
|
|
"license_type": "CONCURRENT_COUNTED_SINGLE"
|
|
|
|
}
|
|
|
|
})
|
2022-12-20 17:06:32 +00:00
|
|
|
|
|
|
|
data = dict(origin_ref=origin_ref, lease_ref=scope_ref, lease_created=cur_time, lease_expires=expires)
|
|
|
|
db['lease'].insert_ignore(data, ['origin_ref', 'lease_ref']) # todo: handle update
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
response = {
|
|
|
|
"lease_result_list": lease_result_list,
|
|
|
|
"result_code": "SUCCESS",
|
2022-12-20 05:47:40 +00:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 12:51:14 +00:00
|
|
|
"prompts": None
|
|
|
|
}
|
|
|
|
|
2022-12-20 05:47:40 +00:00
|
|
|
return JSONResponse(response)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
# venv/lib/python3.9/site-packages/nls_services_lease/test/test_lease_multi_controller.py
|
2022-12-20 17:06:32 +00:00
|
|
|
# venv/lib/python3.9/site-packages/nls_dal_service_instance_dls/schema/service_instance/V1_0_21__product_mapping.sql
|
2022-12-16 12:51:14 +00:00
|
|
|
@app.get('/leasing/v1/lessor/leases')
|
2022-12-21 07:00:52 +00:00
|
|
|
async def leasing_v1_lessor_lease(request: Request):
|
2022-12-20 17:06:32 +00:00
|
|
|
token = get_token(request)
|
2022-12-20 13:55:07 +00:00
|
|
|
|
2022-12-23 05:56:29 +00:00
|
|
|
origin_ref = token['origin_ref']
|
2022-12-20 13:55:07 +00:00
|
|
|
|
2022-12-20 17:06:32 +00:00
|
|
|
active_lease_list = list(map(lambda x: x['lease_ref'], db['lease'].find(origin_ref=origin_ref)))
|
2022-12-23 05:56:29 +00:00
|
|
|
logging.info(f'> [ leases ]: {origin_ref}: found {len(active_lease_list)} active leases')
|
2022-12-20 13:55:07 +00:00
|
|
|
|
2022-12-16 12:51:14 +00:00
|
|
|
cur_time = datetime.utcnow()
|
|
|
|
response = {
|
2022-12-20 13:55:07 +00:00
|
|
|
"active_lease_list": active_lease_list,
|
2022-12-20 05:47:40 +00:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 12:51:14 +00:00
|
|
|
"prompts": None
|
|
|
|
}
|
|
|
|
|
2022-12-20 05:47:40 +00:00
|
|
|
return JSONResponse(response)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
|
2022-12-19 12:15:19 +00:00
|
|
|
# venv/lib/python3.9/site-packages/nls_core_lease/lease_single.py
|
|
|
|
@app.put('/leasing/v1/lease/{lease_ref}')
|
2022-12-21 07:00:52 +00:00
|
|
|
async def leasing_v1_lease_renew(request: Request, lease_ref: str):
|
2022-12-20 17:06:32 +00:00
|
|
|
token = get_token(request)
|
2022-12-20 13:55:07 +00:00
|
|
|
|
2022-12-23 05:56:29 +00:00
|
|
|
origin_ref = token['origin_ref']
|
|
|
|
logging.info(f'> [ renew ]: {origin_ref}: renew {lease_ref}')
|
2022-12-20 17:06:32 +00:00
|
|
|
|
|
|
|
if db['lease'].count(origin_ref=origin_ref, lease_ref=lease_ref) == 0:
|
|
|
|
raise HTTPException(status_code=404, detail='requested lease not available')
|
2022-12-19 12:15:19 +00:00
|
|
|
|
2022-12-19 15:16:44 +00:00
|
|
|
cur_time = datetime.utcnow()
|
2022-12-20 13:55:07 +00:00
|
|
|
expires = cur_time + LEASE_EXPIRE_DELTA
|
2022-12-19 12:15:19 +00:00
|
|
|
response = {
|
|
|
|
"lease_ref": lease_ref,
|
2022-12-20 13:55:07 +00:00
|
|
|
"expires": expires.isoformat(),
|
2022-12-19 12:15:19 +00:00
|
|
|
"recommended_lease_renewal": 0.16,
|
|
|
|
"offline_lease": True,
|
|
|
|
"prompts": None,
|
2022-12-20 05:47:40 +00:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-19 12:15:19 +00:00
|
|
|
}
|
|
|
|
|
2022-12-20 17:06:32 +00:00
|
|
|
data = dict(origin_ref=origin_ref, lease_ref=lease_ref, lease_expires=expires, lease_last_update=cur_time)
|
|
|
|
db['lease'].update(data, ['origin_ref', 'lease_ref'])
|
2022-12-20 13:55:07 +00:00
|
|
|
|
2022-12-20 05:47:40 +00:00
|
|
|
return JSONResponse(response)
|
2022-12-19 12:15:19 +00:00
|
|
|
|
|
|
|
|
2022-12-16 12:51:14 +00:00
|
|
|
@app.delete('/leasing/v1/lessor/leases')
|
2022-12-21 07:00:52 +00:00
|
|
|
async def leasing_v1_lessor_lease_remove(request: Request):
|
2022-12-20 17:06:32 +00:00
|
|
|
token = get_token(request)
|
2022-12-20 13:55:07 +00:00
|
|
|
|
2022-12-23 05:56:29 +00:00
|
|
|
origin_ref = token['origin_ref']
|
2022-12-20 17:06:32 +00:00
|
|
|
|
|
|
|
released_lease_list = list(map(lambda x: x['lease_ref'], db['lease'].find(origin_ref=origin_ref)))
|
|
|
|
deletions = db['lease'].delete(origin_ref=origin_ref)
|
2022-12-23 05:56:29 +00:00
|
|
|
logging.info(f'> [ remove ]: {origin_ref}: removed {deletions} leases')
|
2022-12-20 13:55:07 +00:00
|
|
|
|
2022-12-16 12:51:14 +00:00
|
|
|
cur_time = datetime.utcnow()
|
|
|
|
response = {
|
2022-12-20 13:55:07 +00:00
|
|
|
"released_lease_list": released_lease_list,
|
2022-12-16 12:51:14 +00:00
|
|
|
"release_failure_list": None,
|
2022-12-20 05:47:40 +00:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 12:51:14 +00:00
|
|
|
"prompts": None
|
|
|
|
}
|
2022-12-20 05:47:40 +00:00
|
|
|
return JSONResponse(response)
|
2022-12-16 12:51:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
import uvicorn
|
|
|
|
|
2022-12-19 12:35:03 +00:00
|
|
|
###
|
|
|
|
#
|
|
|
|
# Running `python app/main.py` assumes that the user created a keypair, e.g. with openssl.
|
|
|
|
#
|
|
|
|
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout app/cert/webserver.key -out app/cert/webserver.crt
|
|
|
|
#
|
|
|
|
###
|
2022-12-16 12:51:14 +00:00
|
|
|
|
2022-12-21 09:45:45 +00:00
|
|
|
logging.info(f'> Starting dev-server ...')
|
2022-12-19 12:35:03 +00:00
|
|
|
|
2022-12-19 13:27:10 +00:00
|
|
|
ssl_keyfile = join(dirname(__file__), 'cert/webserver.key')
|
|
|
|
ssl_certfile = join(dirname(__file__), 'cert/webserver.crt')
|
2022-12-19 12:35:03 +00:00
|
|
|
|
|
|
|
uvicorn.run('main:app', host='0.0.0.0', port=443, ssl_keyfile=ssl_keyfile, ssl_certfile=ssl_certfile, reload=True)
|