Skip to content

Commit 16b6bc3

Browse files
committed
fix: 修复了 alist 每 10 秒发送 /api/me 的问题,修改了 web 响应时间问题;增加了存储测速
1 parent 46ccb0d commit 16b6bc3

File tree

6 files changed

+78
-21
lines changed

6 files changed

+78
-21
lines changed

VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.0.14
1+
3.0.15

core/cluster.py

Lines changed: 63 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -960,7 +960,7 @@ def __init__(self, hash: str, size: int, mtime: float, data: bytes) -> None:
960960

961961
ROOT = Path(__file__).parent.parent
962962

963-
API_VERSION = "1.12.1"
963+
API_VERSION = "1.13.0"
964964
USER_AGENT = f"openbmclapi/{API_VERSION} python-openbmclapi/{config.VERSION}"
965965
CHECK_FILE_CONTENT = "Python OpenBMCLAPI"
966966
CHECK_FILE_MD5 = hashlib.md5(CHECK_FILE_CONTENT.encode("utf-8")).hexdigest()
@@ -971,6 +971,9 @@ def __init__(self, hash: str, size: int, mtime: float, data: bytes) -> None:
971971
946684800000
972972

973973
)
974+
MEASURES_HASH: dict[int, str] = {
975+
}
976+
MEASURE_BUFFER: bytes = b'\x00'
974977

975978
routes = web.routes
976979
aweb = web.web
@@ -984,6 +987,34 @@ def convert_file_to_storage_file(file: File) -> SFile:
984987
file.hash
985988
)
986989

990+
def init_measure_block(size: int):
991+
MEASURES_HASH[size] = hashlib.md5(MEASURE_BUFFER * 1024 * 1024 * size).hexdigest()
992+
993+
async def init_measure(maxsize: int = 50):
994+
for i in range(1, maxsize, 10):
995+
init_measure_block(i)
996+
997+
async def init_measure_files():
998+
for storage in clusters.storage_manager.storages:
999+
for size, hash in MEASURES_HASH.items():
1000+
file = File(
1001+
hash,
1002+
hash,
1003+
size * 1024 * 1024,
1004+
946684800000
1005+
)
1006+
try:
1007+
if await storage.exists(hash) and await storage.get_size(hash) == size * 1024 * 1024:
1008+
continue
1009+
await storage.write_file(
1010+
convert_file_to_storage_file(file),
1011+
MEASURE_BUFFER * 1024 * 1024 * size,
1012+
file.mtime
1013+
)
1014+
except:
1015+
logger.terror("cluster.error.init_measure_file", storage=storage.path, type=storage.type, size=units.format_bytes(size * 1024 * 1024), hash=hash)
1016+
...
1017+
9871018
async def init():
9881019
logger.tinfo("cluster.info.init", openbmclapi_version=API_VERSION, version=config.VERSION)
9891020
# read clusters from config
@@ -1012,7 +1043,8 @@ async def init():
10121043
logger.terror("cluster.error.unspported_storage", type=type, path=cstorage['path'])
10131044
continue
10141045
clusters.storage_manager.add_storage(storage)
1015-
1046+
if config.const.measure_storage:
1047+
logger.tinfo("cluster.info.enable.measure_storage")
10161048
scheduler.run_later(
10171049
clusters.start, 0
10181050
)
@@ -1043,19 +1075,35 @@ async def _(request: aweb.Request):
10431075
if not check_sign(f"/measure/{size}", s, e):
10441076
return aweb.Response(status=403)
10451077
cluster_id = get_cluster_id_from_sign(f"/measure/{size}", s, e)
1046-
response = aweb.StreamResponse(
1047-
status=200,
1048-
reason="OK",
1049-
headers={
1050-
"Content-Length": str(size * 1024 * 1024),
1051-
"Content-Type": "application/octet-stream",
1052-
},
1053-
)
1054-
await response.prepare(request)
1055-
for _ in range(size):
1056-
await response.write(b'\x00' * 1024 * 1024)
1057-
await response.write_eof()
1058-
return response
1078+
if not config.const.measure_storage:
1079+
response = aweb.StreamResponse(
1080+
status=200,
1081+
reason="OK",
1082+
headers={
1083+
"Content-Length": str(size * 1024 * 1024),
1084+
"Content-Type": "application/octet-stream",
1085+
},
1086+
)
1087+
await response.prepare(request)
1088+
for _ in range(size):
1089+
await response.write(MEASURE_BUFFER * 1024 * 1024)
1090+
await response.write_eof()
1091+
return response
1092+
else:
1093+
init_measure_block(size)
1094+
await init_measure_files()
1095+
storage = clusters.storage_manager.storages[0]
1096+
if isinstance(storage, storages.AlistStorage):
1097+
url = await storage.get_url(MEASURES_HASH[size])
1098+
logger.debug("Requested measure url:", url)
1099+
return aweb.HTTPFound(url)
1100+
elif isinstance(storage, storages.LocalStorage):
1101+
return aweb.FileResponse(
1102+
Path(storage.get_path(MEASURES_HASH[size]))
1103+
)
1104+
return aweb.Response(status=400)
1105+
1106+
10591107
"""return aweb.HTTPFound(
10601108
f"https://speedtest1.online.sh.cn:8080/download?size={size * 1024 * 1024}&r=0.7129844570865569"
10611109
)"""

core/config.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"advanced.check_type": "size",
1818
"advanced.auto_sync_assets": True,
1919
"advanced.github_token": "",
20+
"advanced.measure_storage": False,
2021
"web": {
2122
"port": -1,
2223
"public_port": 6543,
@@ -153,6 +154,10 @@ def auto_sync_assets(self):
153154
def github_token(self):
154155
return Config.get("advanced.github_token", None) or None
155156

157+
@property
158+
def measure_storage(self) -> bool:
159+
return Config.get("advanced.measure_storage", False)
160+
156161
const = Const()
157162

158163
def read_version():

core/storages/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def __init__(self, path: str, width: int, url: str, username: Optional[str], pas
202202
self.tcp_connector = aiohttp.TCPConnector(limit=256)
203203
self.download_connector = aiohttp.TCPConnector(limit=256)
204204
self.cache = cache.MemoryStorage()
205-
scheduler.run_repeat_later(self._check_token, 0, 10)
205+
scheduler.run_repeat_later(self._check_token, 0, 3600)
206206

207207
async def _get_token(self):
208208
await self.wait_token.wait()
@@ -274,7 +274,8 @@ async def _action_data(self, action: str, url: str, data: Any, headers: dict[str
274274
**await resp.json()
275275
)
276276
if result.code != 200:
277-
logger.terror("storage.error.alist", status=result.code, message=result.message)
277+
logger.terror("storage.error.action_alist", method=action, url=url, status=result.code, message=result.message)
278+
logger.debug(data)
278279
logger.debug(result)
279280
else:
280281
self.cache.set(hash, result, 30)

core/web.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ async def middleware(request: web.Request, handler: Any) -> web.Response:
7373
except:
7474
pass
7575
setattr(request, "custom_address", address)
76-
start = time.monotonic_ns()
76+
start = time.perf_counter_ns()
7777
resp = None
7878
try:
7979
resp = await handler(request)
@@ -87,7 +87,7 @@ async def middleware(request: web.Request, handler: Any) -> web.Response:
8787
status = resp.status
8888
if request.http_range.start is not None and status == 200:
8989
status = 206
90-
end = time.monotonic_ns()
90+
end = time.perf_counter_ns()
9191
logger.tdebug("web.debug.request_info", time=units.format_count_time(end - start, 4).rjust(16), host=request.host, address=(address).rjust(16), user_agent=request.headers.get("User-Agent"), real_path=request.raw_path, method=request.method.ljust(9), status=status)
9292
finally:
9393
request.match_info.current_app = old_app

i18n/zh_cn.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
"cluster.debug.public_host": "已在 [${host}:${port}] 上开放",
2424
"cluster.error.socketio": "节点 [${cluster}] 发送 [${type}] 时出错,原因 [${err}]",
2525
"cluster.info.socketio.message": "节点 [${cluster}] 主控消息:${message}",
26+
"storage.error.action_alist": "Alist 返回出错,请求方式 [${method}] url [${url}] 错误代码 [${status}],原因 [${message}]",
2627
"storage.error.alist": "Alist 返回出错,错误代码 [${status}],原因 [${message}]",
2728
"storage.debug.error_alist": "Alist 返回出错,错误代码 [${status}],原因 [${message}]",
2829
"storage.error.alist.fetch_token": "Alist 获取 Token 出错,错误代码 [${status}],原因 [${message}]",
@@ -44,5 +45,7 @@
4445
"cluster.info.init": "当前 OpenBMCLAPI 版本为 [${openbmclapi_version}] Python OpenBMCLAPI 版本为 [${version}]",
4546
"cluster.success.no_missing_files": "当前暂无更新的文件",
4647
"cluster.debug.retry_download": "文件 [${file_path} ${file_hash}(${file_size})] 在 [${start_date}] 第 [${count}] 次下载失败,将在 [${time}] 重试",
47-
"database.error.write": "数据库写入出错,原因:"
48+
"database.error.write": "数据库写入出错,原因:",
49+
"cluster.info.enable.measure_storage": "已开启 存储 测速",
50+
"cluster.error.init_measure_file": "无法初始化 测速文件,存储 [${path} (${type})] 大小 [${size}] 哈希 [${hash}]"
4851
}

0 commit comments

Comments
 (0)