蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在三个独立服务中验证模型库恢复和配方重建

PYTHONWindows、CPython 3.12、Ollama 0.40.15;只处理自己新建的临时模型库与微型GGUF,不更改系统安装。portable_models.py
portable_models.py233 行
"""Copy, archive and rebuild an owned local model store; Windows-only service harness."""
import argparse
from contextlib import contextmanager,closing
import hashlib
from http.client import HTTPConnection
from io import BytesIO
import json
import os
from pathlib import Path,PurePosixPath
import re
import shutil
import socket
import subprocess
import sys
import tarfile
from time import monotonic,sleep


def digest(data):
    return hashlib.sha256(data).hexdigest()


def tree(root):
    root=Path(root).resolve()
    result={}
    for path in sorted(root.rglob("*")):
        if path.is_symlink():
            raise ValueError("symlinks are outside this backup contract")
        if path.is_file():
            data=path.read_bytes()
            result[path.relative_to(root).as_posix()]=dict(sha256=digest(data),bytes=len(data))
    return result


def verify_tree(root,expected):
    if tree(root)!=expected:
        raise ValueError("model tree differs from pinned snapshot")


def archive_store(root,archive):
    records=tree(root)
    with tarfile.open(archive,"w:gz") as bundle:
        for name in records:
            bundle.add(Path(root)/name,arcname=name,recursive=False)
    return records


def restore_archive(archive,destination):
    destination=Path(destination).resolve()
    if destination.exists():
        raise ValueError("restore target must not exist")
    destination.mkdir(parents=True)
    with tarfile.open(archive,"r:gz") as bundle:
        entries=bundle.getmembers()
        for entry in entries:
            relative=PurePosixPath(entry.name)
            if relative.is_absolute() or ".." in relative.parts or "\\" in entry.name or any(":" in p for p in relative.parts):
                raise ValueError("unsafe archive member")
            target=destination.joinpath(*relative.parts).resolve()
            if not target.is_relative_to(destination) or not entry.isfile():
                raise ValueError("unsupported archive member")
        for entry in entries:
            target=destination.joinpath(*PurePosixPath(entry.name).parts)
            target.parent.mkdir(parents=True,exist_ok=True)
            source=bundle.extractfile(entry)
            if source is None:raise ValueError("unreadable archive member")
            with source:target.write_bytes(source.read())


def http(port,path,body=None,timeout=30):
    with closing(HTTPConnection("127.0.0.1",port,timeout=timeout)) as connection:
        connection.request("GET" if body is None else "POST",path,
            None if body is None else json.dumps(body).encode(),
            {} if body is None else {"Content-Type":"application/json"})
        response=connection.getresponse();value=json.loads(response.read())
        if response.status!=200:raise RuntimeError((response.status,value))
        return value


@contextmanager
def service(binary,workspace,store):
    if os.name!="nt":raise NotImplementedError("This service lifecycle was verified only on Windows")
    workspace=Path(workspace).resolve();workspace.mkdir(parents=True)
    store=Path(store).resolve();store.mkdir(parents=True,exist_ok=True)
    profile=workspace/"profile";profile.mkdir()
    with socket.socket() as candidate:
        candidate.bind(("127.0.0.1",0));port=candidate.getsockname()[1]
    env={key:os.environ[key] for key in ("SystemRoot","WINDIR","PATH","TEMP","TMP") if key in os.environ}
    env.update(USERPROFILE=str(profile),OLLAMA_HOST=f"127.0.0.1:{port}",OLLAMA_MODELS=str(store),
        OLLAMA_NO_CLOUD="1",OLLAMA_LLM_LIBRARY="cpu",CUDA_VISIBLE_DEVICES="-1",ROCR_VISIBLE_DEVICES="-1",
        OLLAMA_VULKAN="0",HTTPS_PROXY="http://127.0.0.1:9",HTTP_PROXY="http://127.0.0.1:9",NO_PROXY="127.0.0.1,localhost",OLLAMA_NUM_PARALLEL="1",OLLAMA_MAX_LOADED_MODELS="1",OLLAMA_CONTEXT_LENGTH="256")
    log=workspace/"service.log"
    with log.open("wb") as output:
        process=subprocess.Popen([str(binary),"serve"],cwd=workspace,env=env,stdout=output,stderr=output,
            creationflags=subprocess.CREATE_NO_WINDOW)
        try:
            deadline=monotonic()+15
            while True:
                assert process.poll() is None,log.read_text(encoding="utf8",errors="replace")
                try:version=http(port,"/api/version",timeout=1)["version"];break
                except OSError:
                    if monotonic()>deadline:raise
                    sleep(.1)
            yield port,env,version
        finally:
            if process.poll() is None:
                subprocess.run(["taskkill.exe","/PID",str(process.pid),"/T","/F"],capture_output=True,
                    timeout=12,creationflags=subprocess.CREATE_NO_WINDOW)
            process.wait(timeout=12)
    # A still-responding HTTP endpoint would invalidate the stopped-service prerequisite.
    try:http(port,"/api/version",timeout=.3)
    except OSError:pass
    else:raise RuntimeError("owned service endpoint still responds")


def cli(binary,env,*args,check=True):
    run=subprocess.run([str(binary),*map(str,args)],env=env,capture_output=True,encoding="utf8",
        errors="replace",timeout=35,creationflags=getattr(subprocess,"CREATE_NO_WINDOW",0))
    if check and run.returncode!=0:raise RuntimeError((run.stdout,run.stderr))
    return run


def inventory(port):
    return {row["name"]:row["digest"] for row in http(port,"/api/tags")["models"]}


def inspect_custom(port,name):
    value=http(port,"/api/show",dict(model=name))
    parameters={}
    for line in value["parameters"].splitlines():
        key,item=line.split(maxsplit=1)
        if key in ("num_ctx","temperature"):parameters[key]=float(item)
    generated=http(port,"/api/generate",dict(model=name,prompt="owned backup input",raw=True,stream=False,
        options=dict(num_predict=4,num_ctx=128,temperature=0)))
    return dict(system=value["system"],parameters=parameters,response=generated["response"].strip(),
        eval_count=generated["eval_count"])


def run(binary,root):
    root=Path(root).resolve()
    root.mkdir(parents=True,exist_ok=True)
    source=root/"source-store"
    fixture=root/"owned.gguf"
    subprocess.run([sys.executable,"-I","-B",str(Path(__file__).with_name("make_fixture.py")),
        str(fixture),"--token","pong","--context","256"],check=True,timeout=15)
    base=root/"base.Modelfile"
    base.write_text(f"FROM {fixture}\nPARAMETER num_ctx 256\nPARAMETER temperature 0\n",encoding="utf8")
    custom=root/"custom.Modelfile"
    custom.write_text('FROM mbsky-migrate:base\nSYSTEM "Blue Sky owned backup check."\nPARAMETER temperature 0.2\nPARAMETER num_ctx 128\n',encoding="utf8")
    with service(binary,root/"source-runtime",source) as (port,env,source_version):
        cli(binary,env,"create","mbsky-migrate:base","-f",base)
        cli(binary,env,"create","mbsky-migrate:custom","-f",custom)
        cli(binary,env,"cp","mbsky-migrate:custom","mbsky-migrate:alias")
        original_inventory=inventory(port)
        original=inspect_custom(port,"mbsky-migrate:custom")
        exported=cli(binary,env,"show","--modelfile","mbsky-migrate:custom").stdout
    pinned=tree(source)
    assert pinned and any(name.startswith("blobs/") for name in pinned)
    copied=root/"copied-store"
    assert source.is_relative_to(root) and copied.is_relative_to(root)
    shutil.copytree(source,copied)
    verify_tree(copied,pinned)
    archive=root/"models-backup.tar.gz"
    assert archive_store(source,archive)==pinned
    restored=root/"restored-store"
    restore_archive(archive,restored)
    verify_tree(restored,pinned)
    # Corruption is detected before any native service is started on that copy.
    damaged=root/"damaged-store";shutil.copytree(source,damaged)
    one=damaged/next(iter(pinned));one.write_bytes(one.read_bytes()+b"X")
    try:verify_tree(damaged,pinned)
    except ValueError:corrupt_rejected=True
    else:raise AssertionError("corruption was not detected")
    bad=root/"unsafe.tar.gz"
    with tarfile.open(bad,"w:gz") as bundle:
        member=tarfile.TarInfo("../escape.txt");member.size=1
        bundle.addfile(member,BytesIO(b"x"))
    try:restore_archive(bad,root/"unsafe-target")
    except ValueError:unsafe_rejected=True
    else:raise AssertionError("unsafe archive accepted")
    # Both original and target paths are explicit descendants of this disposable root.
    # This rename makes the exported old absolute FROM unavailable without deleting it.
    preserved=root/"source-store-preserved"
    assert source.resolve().is_relative_to(root) and preserved.resolve().is_relative_to(root)
    assert source.parent==root and preserved.parent==root and not preserved.exists()
    source.rename(preserved)
    from_line=next(line for line in exported.splitlines() if line.startswith("FROM "))
    missing_path=Path(from_line.split(maxsplit=1)[1].strip('"'))
    old_blob_available=missing_path.exists()
    assert not old_blob_available
    try:
        with service(binary,root/"restored-runtime",restored) as (port,env,restored_version):
            restored_inventory=inventory(port)
            restored_observation=inspect_custom(port,"mbsky-migrate:custom")
        rebuilt_store=root/"rebuilt-store"
        old_recipe=root/"old-path.Modelfile";old_recipe.write_text(exported,encoding="utf8")
        portable=root/"portable.Modelfile"
        portable.write_text(re.sub(r"(?m)^FROM .*$","FROM "+str(fixture).replace("\\","/"),exported),encoding="utf8")
        with service(binary,root/"rebuilt-runtime",rebuilt_store) as (port,env,rebuilt_version):
            failed=cli(binary,env,"create","mbsky-migrate:missing","-f",old_recipe,check=False)
            assert failed.returncode!=0
            cli(binary,env,"create","mbsky-migrate:recreated","-f",portable)
            recreated=inspect_custom(port,"mbsky-migrate:recreated")
    finally:
        assert preserved.resolve().is_relative_to(root) and source.resolve().is_relative_to(root)
        assert not source.exists()
        preserved.rename(source)
    verify_tree(source,pinned)
    return dict(source_version=source_version,restored_version=restored_version,rebuilt_version=rebuilt_version,
        source_inventory=original_inventory,restored_inventory=restored_inventory,
        source=original,restored=restored_observation,recreated=recreated,
        model_files=pinned,copied_hashes_equal=tree(copied)==pinned,
        restored_hashes_equal=tree(restored)==pinned,source_preserved=True,
        archive_sha256=digest(archive.read_bytes()),archive_bytes=archive.stat().st_size,
        exported_from_absolute=missing_path.is_absolute(),old_blob_unavailable_during_rebuild=not old_blob_available,
        missing_recipe_exit=failed.returncode,missing_recipe_error=(failed.stdout+failed.stderr)[-1000:],
        corrupt_rejected=corrupt_rejected,unsafe_archive_rejected=unsafe_rejected,
        escape_written=(root/"escape.txt").exists(),fixture_sha256=digest(fixture.read_bytes()),
        portable_recipe_sha256=digest(portable.read_bytes()),
        registry_pull_requests=sum('/api/pull' in line and 'POST' in line for log in root.glob("*-runtime/service.log")
            for line in log.read_text(encoding="utf8",errors="replace").splitlines()),
        all_owned_services_stopped=True)


if __name__=="__main__":
    import tempfile
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--binary",type=Path,required=True)
    args=parser.parse_args()
    with tempfile.TemporaryDirectory(prefix="mbsky-owned-model-migration-") as temporary:
        result=run(args.binary.resolve(strict=True),Path(temporary))
    print(json.dumps(result,ensure_ascii=False))
本例需在 Windows、CPython 3.12、Ollama 0.40.15;只处理自己新建的临时模型库与微型GGUF,不更改系统安装。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、CPython 3.12、Ollama 0.40.15;只处理自己新建的临时模型库与微型GGUF,不更改系统安装。

入口文件:projects/ollama-migration/portable_models.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 portable_models.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、CPython 3.12、Ollama 0.40.15;只处理自己新建的临时模型库与微型GGUF,不更改系统安装。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Ollama

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a217.zip

下载课程关联工程包:Ollama

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a229.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习