Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/dao/downloader_dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ func (d *DownloaderDao) reconcileCachedFile(p *downloader.TaskParam) {
InstanceId: config.SysConfig.Registration().NodeID,
StartPos: p.FileSize, EndPos: p.FileSize, Status: consts.StatusDownloaded,
}
if err := d.schedulerDao.SyncFileProcess(&manager.SyncFileProcessReq{FileProcessEntries: []*manager.FileProcessEntry{entry}}); err != nil {
if err := d.schedulerDao.ReportCachedFile(&manager.SyncFileProcessReq{FileProcessEntries: []*manager.FileProcessEntry{entry}}); err != nil {
zap.S().Errorf("reconcile cached file %s/%s: %v", p.OrgRepo, p.FileName, err)
data.WriteLocalOperationChan(consts.OperationProcess, &data.FileProcessParam{
Datatype: p.DataType, Org: p.RepoKey.Namespace, Repo: p.RepoKey.Repo,
Expand Down
51 changes: 51 additions & 0 deletions internal/dao/file_dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,57 @@ requestRemoteFileInfo:
return pathInfo, nil
}

// GetSnapshotSizesContext 用一次 revision?blobs=true 请求取得快照内全部文件大小。
// 上游缺少任一路径的大小时返回错误,由调用方退回分批 paths-info。
func (f *FileDao) GetSnapshotSizesContext(ctx context.Context, repoType, orgRepo, commit, authorization string, paths []string) (map[string]int64, error) {
upstream, err := UpstreamRepo(repoType, orgRepo)
if err != nil {
return nil, err
}
uri := fmt.Sprintf("/api/%s/%s/revision/%s?blobs=true", repoType, repository.EscapeURLPath(upstream), repository.EscapeURLPath(commit))
headers := map[string]string{}
if authorization != "" {
headers["authorization"] = authorization
}
response, err := util.RetryRequestContext(ctx, func() (*common.Response, error) {
return util.GetContext(ctx, uri, headers)
})
if err != nil {
return nil, fmt.Errorf("remote metadata request: %w", err)
}
if response.StatusCode != http.StatusOK {
return nil, myerr.NewAppendCode(response.StatusCode, "snapshot sizes request failed")
}
var meta struct {
Sha string `json:"sha"`
Siblings []struct {
Rfilename string `json:"rfilename"`
Size *int64 `json:"size"`
} `json:"siblings"`
}
if err = sonic.Unmarshal(response.Body, &meta); err != nil {
return nil, err
}
if meta.Sha != commit {
return nil, fmt.Errorf("upstream returned commit %q, want %q", meta.Sha, commit)
}
listed := make(map[string]int64, len(meta.Siblings))
for _, sibling := range meta.Siblings {
if sibling.Size != nil {
listed[sibling.Rfilename] = *sibling.Size
}
}
sizes := make(map[string]int64, len(paths))
for _, path := range paths {
size, ok := listed[path]
if !ok {
return nil, fmt.Errorf("upstream omitted size for %q", path)
}
sizes[path] = size
}
return sizes, nil
}

// GetPathsSizesContext 批量查询快照内文件大小,每 128 个路径一次 paths-info 请求。
// 上游必须逐一返回请求的路径,缺失或多出的条目都视为错误。
func (f *FileDao) GetPathsSizesContext(ctx context.Context, repoType, orgRepo, commit, authorization string, paths []string) (map[string]int64, error) {
Expand Down
84 changes: 74 additions & 10 deletions internal/dao/scheduler_dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package dao
import (
"context"
"dingospeed/pkg/repository"
"errors"
"google.golang.org/protobuf/proto"
"sync/atomic"
"time"

"dingospeed/internal/data"
Expand All @@ -15,8 +17,32 @@ import (
"go.uber.org/zap"
)

// 下载路径上的调度调用(选取对等节点、上报文件已缓存)失败时都有退路:
// 回源下载,或写入本地队列稍后重放。短超时加冷却期,避免调度器或其数据库
// 卡住时,每个文件都要等满 RpcRequestTimeout,并在调度器的写锁上排队。
var (
SchedulerFastTimeout = 5 * time.Second
SchedulerFastCooldown = 30 * time.Second
)

var errSchedulerCooling = errors.New("scheduler calls paused after a recent failure")

type SchedulerDao struct {
Client manager.ManagerClient
Client manager.ManagerClient
fastSkipUntil atomic.Int64
}

func (s *SchedulerDao) fastCall(call func(context.Context) error) error {
if time.Now().UnixNano() < s.fastSkipUntil.Load() {
return errSchedulerCooling
}
ctx, cancel := context.WithTimeout(context.Background(), SchedulerFastTimeout)
defer cancel()
if err := call(ctx); err != nil {
s.fastSkipUntil.Store(time.Now().Add(SchedulerFastCooldown).UnixNano())
return err
}
return nil
}

func NewSchedulerDao() *SchedulerDao {
Expand Down Expand Up @@ -66,26 +92,47 @@ func (s *SchedulerDao) SchedulerFile(req *manager.SchedulerFileRequest) (*manage
req.Org, req.Repo = org, repo
}

ctx, cancel := context.WithTimeout(context.Background(), consts.RpcRequestTimeout)
defer cancel()
resp, err := s.Client.SchedulerFile(ctx, req)
var resp *manager.SchedulerFileResponse
err := s.fastCall(func(ctx context.Context) (err error) {
resp, err = s.Client.SchedulerFile(ctx, req)
return err
})
return resp, err
}

func (s *SchedulerDao) SyncFileProcess(req *manager.SyncFileProcessReq) error {
req, err := storageFileProcess(req)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), consts.RpcRequestTimeout)
defer cancel()
_, err = s.Client.SyncFileProcess(ctx, req)
return err
}

// ReportCachedFile 在下载路径上同步执行,失败由调用方写入本地队列重放。
func (s *SchedulerDao) ReportCachedFile(req *manager.SyncFileProcessReq) error {
req, err := storageFileProcess(req)
if err != nil {
return err
}
return s.fastCall(func(ctx context.Context) error {
_, err := s.Client.SyncFileProcess(ctx, req)
return err
})
}

func storageFileProcess(req *manager.SyncFileProcessReq) (*manager.SyncFileProcessReq, error) {
req = proto.Clone(req).(*manager.SyncFileProcessReq)
for _, e := range req.FileProcessEntries {
org, repo, err := (repository.RepoKey{Namespace: e.Org, RepoType: e.DataType, Repo: e.Repo}).Storage()
if err != nil {
return err
return nil, err
}
e.Org, e.Repo = org, repo
}

ctx, cancel := context.WithTimeout(context.Background(), consts.RpcRequestTimeout)
defer cancel()
_, err := s.Client.SyncFileProcess(ctx, req)
return err
return req, nil
}

func (s *SchedulerDao) ReportFileProcess(request *manager.FileProcessRequest) error {
Expand Down Expand Up @@ -169,6 +216,23 @@ func (s *SchedulerDao) ExecUpdateCacheJobStatus(jobId int, status int32, instanc
}
}

// ReportCacheJobRunning tells the scheduler a job is running and how large its
// snapshot is. It is best effort and deliberately not queued for replay: a
// replayed "running" could land after the job's terminal status.
func (s *SchedulerDao) ReportCacheJobRunning(jobId int, instanceId, org, repo string, usedStorage int64) {
request := &manager.UpdateCacheJobStatusReq{
Id: int64(jobId),
InstanceId: instanceId,
Status: consts.RunningStatusJobIng,
Org: org,
Repo: repo,
UsedStorage: usedStorage,
}
if err := s.UpdateCacheJobStatus(request); err != nil {
zap.S().Warnf("report cache job %d running: %v", jobId, err)
}
}

func (s *SchedulerDao) UpdateRepositoryMountStatus(request *manager.UpdateRepositoryMountStatusReq) error {
zap.S().Infof("updateRepositoryMountStatus id:%d, status:%d, %s", request.Id, request.Status, request.ErrorMsg)
ctx, cancel := context.WithTimeout(context.Background(), consts.RpcRequestTimeout)
Expand Down
81 changes: 81 additions & 0 deletions internal/dao/scheduler_fast_call_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package dao

import (
"context"
"errors"
"sync/atomic"
"testing"
"time"

pb "dingospeed/pkg/proto/manager"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
)

type stalledSchedulerClient struct {
storageClient
stall atomic.Bool
calls atomic.Int32
}

func (c *stalledSchedulerClient) wait(ctx context.Context) error {
c.calls.Add(1)
if c.stall.Load() {
<-ctx.Done()
return ctx.Err()
}
return nil
}

func (c *stalledSchedulerClient) SchedulerFile(ctx context.Context, _ *pb.SchedulerFileRequest, _ ...grpc.CallOption) (*pb.SchedulerFileResponse, error) {
if err := c.wait(ctx); err != nil {
return nil, err
}
return &pb.SchedulerFileResponse{ProcessId: 1}, nil
}

func (c *stalledSchedulerClient) SyncFileProcess(ctx context.Context, _ *pb.SyncFileProcessReq, _ ...grpc.CallOption) (*emptypb.Empty, error) {
if err := c.wait(ctx); err != nil {
return nil, err
}
return &emptypb.Empty{}, nil
}

func TestSchedulerFastCallsTimeOutAndCoolDown(t *testing.T) {
oldTimeout, oldCooldown := SchedulerFastTimeout, SchedulerFastCooldown
defer func() { SchedulerFastTimeout, SchedulerFastCooldown = oldTimeout, oldCooldown }()
SchedulerFastTimeout, SchedulerFastCooldown = 50*time.Millisecond, 200*time.Millisecond

c := &stalledSchedulerClient{}
c.stall.Store(true)
d := &SchedulerDao{Client: c}
req := &pb.SchedulerFileRequest{DataType: "models", Org: "huggingface", Repo: "Qwen/demo", Name: "weights.bin", Etag: "hash"}
report := &pb.SyncFileProcessReq{FileProcessEntries: []*pb.FileProcessEntry{{DataType: "models", Org: "huggingface", Repo: "Qwen/demo"}}}

start := time.Now()
if _, err := d.SchedulerFile(req); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("stalled scheduler: %v", err)
}
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("waited %s for a stalled scheduler", elapsed)
}
// During the cooldown neither lookups nor cache reports reach the scheduler.
if _, err := d.SchedulerFile(req); !errors.Is(err, errSchedulerCooling) {
t.Fatalf("lookup during cooldown: %v", err)
}
if err := d.ReportCachedFile(report); !errors.Is(err, errSchedulerCooling) {
t.Fatalf("report during cooldown: %v", err)
}
if got := c.calls.Load(); got != 1 {
t.Fatalf("scheduler called %d times", got)
}

c.stall.Store(false)
time.Sleep(SchedulerFastCooldown)
if _, err := d.SchedulerFile(req); err != nil {
t.Fatalf("after cooldown: %v", err)
}
if err := d.ReportCachedFile(report); err != nil {
t.Fatalf("report after cooldown: %v", err)
}
}
10 changes: 8 additions & 2 deletions internal/service/cache_job_dedup.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,14 @@ func (p *CacheJobService) reusableCacheJob(key repository.RepoKey, snapshot *dao
}
}
}
if completed != nil && dao.PreheatCacheComplete(key, snapshot) {
return completed, nil
if completed != nil {
// A create request only carries the upstream size estimate; the
// completed job recorded the measured size of this commit.
measured := *snapshot
measured.UsedStorage = int64(completed.TotalBytes)
if dao.PreheatCacheComplete(key, &measured) {
return completed, nil
}
}
return nil, nil
}
Loading
Loading