Files
seaweedfs/weed/shell/command_volume_tier_upload.go
T
5a8e774e36 shell: harden volume.tier.upload for unattended batch runs (#13254)
* shell: harden volume.tier.upload for unattended batch runs

- validate -dest against the master's storage backends before any volume
  is marked read-only, instead of failing per volume after the freeze
- mark replicas read-only with canDelete so TTL expiry keeps draining the
  volume during the upload, and restore writable marks when the upload or
  metadata replication fails partway
- keep going after a per-volume failure in batch mode and report all
  errors at the end
- treat an unset -disk as "any disk"; flag.String never returns nil and
  ToDiskType("") is the hdd type, so the batch silently skipped ssd and
  tagged volumes

Refs #13223

* shell: keep deletes refused while volume.tier.upload copies a volume

A delete accepted during the copy appends a tombstone to the source .dat,
so the attach refuses the upload, and one accepted after a replica's .idx
snapshot is dropped when that replica installs the copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: leave replicas that were read-only alone when a tier upload fails

VolumeMarkWritable persists ReadOnly=false, so the rollback cleared an
operator's read-only mark on any replica that was frozen before the run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: roll back the replica whose read-only mark failed in volume.tier.upload

VolumeMarkReadonly freezes the volume locally before its second master
notification, so an error there leaves the replica read-only although it
never joined the marked list. Also name that replica in the error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: let the tiered source accept deletes once every replica has its index

The copies load as tiered volumes that accept deletes, but the source kept
the no-delete mark until its next reload, so a delete applied on a copy
then failed on the source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: bound each rollback mark in volume.tier.upload

A stalled VolumeMarkWritable held up the upload error and, in a batch run,
every later volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: keep replicas frozen when the tier upload attached before failing

A stream that breaks after the volume server attached the remote copy
returns an error, and reopening the other replicas then let them take
writes the remote copy lacks. Ask the source first; a rerun finishes the
upload from its remote copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: bound the final delete mark in volume.tier.upload

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:38:02 -08:00

409 lines
15 KiB
Go

package shell
import (
"context"
"errors"
"flag"
"fmt"
"io"
"math"
"sort"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/pb"
"google.golang.org/grpc"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
)
// maxTierConcurrency caps per-request multipart transfer concurrency.
const maxTierConcurrency = 1024
// validateTierConcurrency rejects values that would wrap when narrowed to the
// int32 proto field or exhaust volume-server resources. 0 means backend default.
func validateTierConcurrency(n int) error {
if n < 0 || n > math.MaxInt32 {
return fmt.Errorf("concurrency must be between 0 and %d, got %d", math.MaxInt32, n)
}
if n > maxTierConcurrency {
return fmt.Errorf("concurrency must be at most %d, got %d", maxTierConcurrency, n)
}
return nil
}
func init() {
Commands = append(Commands, &commandVolumeTierUpload{})
}
type commandVolumeTierUpload struct {
}
func (c *commandVolumeTierUpload) Name() string {
return "volume.tier.upload"
}
func (c *commandVolumeTierUpload) Help() string {
return `upload the dat file of a volume to a remote tier
volume.tier.upload [-collection=""] [-fullPercent=95] [-quietFor=1h]
volume.tier.upload [-collection=""] -volumeId=<volume_id> -dest=<storage_backend> [-keepLocalDatFile] [-concurrency=<n>]
e.g.:
volume.tier.upload -volumeId=7 -dest=s3
volume.tier.upload -volumeId=7 -dest=s3.default
volume.tier.upload -volumeId=7 -dest=s3.telegram -concurrency=1
The <storage_backend> is defined in master.toml.
For example, "s3.default" in [storage.backend.s3.default]
This command will move the dat file of a volume to a remote tier.
SeaweedFS enables scalable and fast local access to lots of files,
and the cloud storage is slower by cost efficient. How to combine them together?
Usually the data follows 80/20 rule: only 20% of data is frequently accessed.
We can offload the old volumes to the cloud.
With this, SeaweedFS can be both fast and scalable, and infinite storage space.
Just add more local SeaweedFS volume servers to increase the throughput.
The index file is still local, and the same O(1) disk read is applied to the remote file.
Each replica keeps its own local index pointing at the same remote object,
so the volume keeps its replica count for reads after tiering.
`
}
func (c *commandVolumeTierUpload) HasTag(CommandTag) bool {
return false
}
func (c *commandVolumeTierUpload) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
tierCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
volumeId := tierCommand.Int("volumeId", 0, "the volume id")
collection := tierCommand.String("collection", "", "comma-separated collection names, wildcards, or regex patterns; empty matches the collection with no name")
fullPercentage := tierCommand.Float64("fullPercent", 95, "the volume reaches the percentage of max volume size")
quietPeriod := tierCommand.Duration("quietFor", 24*time.Hour, "select volumes without no writes for this period")
dest := tierCommand.String("dest", "", "the target tier name")
keepLocalDatFile := tierCommand.Bool("keepLocalDatFile", false, "whether keep local dat file")
disk := tierCommand.String("disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
concurrency := tierCommand.Int("concurrency", 0, "multipart upload concurrency (0 = backend default)")
if err = tierCommand.Parse(args); err != nil {
return err
}
if err = validateTierConcurrency(*concurrency); err != nil {
return err
}
if err = commandEnv.confirmIsLocked(args); err != nil {
return
}
// Fail before any volume is marked read-only when -dest is missing or
// names a backend the master does not know about.
if err = validateTierUploadDestination(commandEnv, *dest); err != nil {
return err
}
vid := needle.VolumeId(*volumeId)
// volumeId is provided
if vid != 0 {
return doVolumeTierUpload(commandEnv, writer, *collection, vid, *dest, *keepLocalDatFile, *concurrency)
}
// apply to all volumes in the collection
// reusing collectVolumeIdsForEcEncode for now
volumeIds, _, err := collectVolumeIdsForEcEncode(commandEnv, *collection, tierUploadDiskType(*disk), *fullPercentage, *quietPeriod, false)
if err != nil {
return err
}
fmt.Printf("tier upload volumes: %v\n", volumeIds)
var errs []error
for _, vid := range volumeIds {
if err = doVolumeTierUpload(commandEnv, writer, *collection, vid, *dest, *keepLocalDatFile, *concurrency); err != nil {
fmt.Fprintf(writer, "volume %d tier upload failed: %v\n", vid, err)
errs = append(errs, fmt.Errorf("volume %d: %w", vid, err))
continue
}
}
return errors.Join(errs...)
}
func doVolumeTierUpload(commandEnv *CommandEnv, writer io.Writer, collectionPattern string, vid needle.VolumeId, dest string, keepLocalDatFile bool, concurrency int) (err error) {
// find volume location
topoInfo, _, err := collectTopologyInfo(commandEnv, 0)
if err != nil {
return fmt.Errorf("collect topology info: %v", err)
}
// The volume server verifies the request's collection against the volume's
// own, so the pattern must resolve to the actual collection here.
collection, found, err := findVolumeCollection(topoInfo, vid, collectionPattern)
if err != nil {
return err
}
if !found {
if collectionPattern == "" {
return fmt.Errorf("volume %d not found", vid)
}
return fmt.Errorf("volume %d not found in collections matching %s", vid, collectionPattern)
}
existingLocations, readOnly := collectVolumeTierUploadLocations(topoInfo, vid, collection, writer)
if len(existingLocations) == 0 {
return fmt.Errorf("volume %d has no replicas in collection %s", vid, collection)
}
// Deletes stay refused until the .idx reaches every replica: a tombstone
// appended to the source .dat during the copy fails the attach, and one
// landing after a replica's .idx copy is lost on that replica.
marked, err := markVolumeReplicasWritable(context.Background(), commandEnv.option.GrpcDialOption, vid, existingLocations, false, false)
if err != nil {
// The failed replica may be half-marked: the volume server freezes
// it locally before its last master notification.
failed := existingLocations[len(marked)]
restoreTierUploadReplicasWritable(commandEnv, vid, existingLocations[:len(marked)+1], readOnly)
return fmt.Errorf("mark volume %d as readonly on %s: %v", vid, failed.Url, err)
}
// copy the .dat file to remote tier
err = uploadDatToRemoteTier(commandEnv.option.GrpcDialOption, writer, vid, collection, existingLocations[0].ServerAddress(), dest, keepLocalDatFile, concurrency)
if err != nil {
// A stream that broke after the attach leaves the source serving the
// remote copy; keep the other replicas frozen so a rerun finishes
// from it instead of letting them take writes the copy lacks.
if !tierUploadSourceAttached(commandEnv, vid, existingLocations[0].ServerAddress()) {
restoreTierUploadReplicasWritable(commandEnv, vid, existingLocations, readOnly)
}
return fmt.Errorf("copy dat file for volume %d on %s to %s: %v", vid, existingLocations[0].Url, dest, err)
}
if keepLocalDatFile {
return nil
}
// Re-copy the uploaded replica's .idx/.vif onto the other replicas instead
// of deleting them: the remote object key lives only in the .vif, so losing
// the single server holding it would orphan the volume.
for i, location := range existingLocations {
if i == 0 {
continue
}
fmt.Fprintf(writer, "replicate remote volume %d metadata from %s to %s\n", vid, existingLocations[0].Url, location.Url)
err = replicateVolumeToServer(context.Background(), commandEnv.option.GrpcDialOption, writer, vid, existingLocations[0].ServerAddress(), location.ServerAddress(), "", 0)
if err != nil {
// The source replica is now backed by the remote object and must
// stay read-only. This replica and the ones after it still hold
// complete local copies, so reopen them for writes.
restoreTierUploadReplicasWritable(commandEnv, vid, existingLocations[i:], readOnly)
return fmt.Errorf("replicate volume %d from %s to %s: %v", vid, existingLocations[0].Url, location.Url, err)
}
}
// Every replica now holds the source's .idx and loaded as a tiered volume
// that accepts deletes; let the source accept them too, or a delete lands
// on the copies and fails on the source until it is reloaded.
if len(existingLocations) > 1 {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err = markVolumeState(ctx, commandEnv.option.GrpcDialOption, vid, existingLocations[0].ServerAddress(), false, true, false); err != nil {
return fmt.Errorf("allow deletes on volume %d at %s: %v", vid, existingLocations[0].Url, err)
}
}
return nil
}
// restoreTierUploadReplicasWritable reopens the replicas a failed upload
// froze, skipping those already read-only before it: VolumeMarkWritable would
// clear their persisted mark. Each attempt is bounded and failures are logged
// so the upload error reaches the caller.
func restoreTierUploadReplicasWritable(commandEnv *CommandEnv, volumeId needle.VolumeId, locations []wdclient.Location, readOnly map[string]bool) {
for _, location := range locations {
if readOnly[location.Url] {
continue
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
if markErr := markVolumeState(ctx, commandEnv.option.GrpcDialOption, volumeId, location.ServerAddress(), true, false, false); markErr != nil {
glog.Errorf("mark volume %d as writable on %s: %v", volumeId, location.Url, markErr)
}
cancel()
}
}
// tierUploadSourceAttached reports whether the source already serves the
// volume from a remote copy. An unanswered check counts as attached.
func tierUploadSourceAttached(commandEnv *CommandEnv, volumeId needle.VolumeId, source pb.ServerAddress) bool {
attached := true
err := operation.WithVolumeServerClient(false, source, commandEnv.option.GrpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
resp, err := client.ReadVolumeFileStatus(ctx, &volume_server_pb.ReadVolumeFileStatusRequest{VolumeId: uint32(volumeId)})
if err != nil {
return err
}
attached = len(resp.GetVolumeInfo().GetFiles()) > 0
return nil
})
if err != nil {
glog.Errorf("check volume %d remote copy on %s: %v", volumeId, source, err)
}
return attached
}
// collectVolumeTierUploadLocations lists the replica locations of a volume,
// putting an already-tiered replica first so a rerun after a partial failure
// reuses its remote object instead of uploading a second copy. readOnly holds
// the replicas already read-only before the upload.
func collectVolumeTierUploadLocations(topoInfo *master_pb.TopologyInfo, vid needle.VolumeId, collection string, writer io.Writer) (locations []wdclient.Location, readOnly map[string]bool) {
var tiered, local []wdclient.Location
readOnly = make(map[string]bool)
eachDataNode(topoInfo, func(dc DataCenterId, rack RackId, dn *master_pb.DataNodeInfo) {
for _, disk := range dn.DiskInfos {
for _, vi := range disk.VolumeInfos {
if needle.VolumeId(vi.Id) == vid && vi.Collection == collection {
fmt.Fprintf(writer, "find volume %d from Url:%s, GrpcPort:%d, DC:%s\n", vid, dn.Id, dn.GrpcPort, string(dc))
loc := wdclient.Location{
Url: dn.Id,
PublicUrl: dn.Id,
GrpcPort: int(dn.GrpcPort),
DataCenter: string(dc),
}
if vi.ReadOnly {
readOnly[loc.Url] = true
}
if vi.RemoteStorageName != "" {
tiered = append(tiered, loc)
} else {
local = append(local, loc)
}
}
}
}
})
return append(tiered, local...), readOnly
}
// tierUploadDiskType maps the -disk flag to the batch selector's disk filter.
// An empty flag must return nil ("any disk"): flag.String always yields a
// non-nil pointer, and ToDiskType("") is the hdd type, so treating "" as a
// filter would silently restrict the batch to hard drives.
func tierUploadDiskType(disk string) *types.DiskType {
if disk == "" {
return nil
}
diskType := types.ToDiskType(disk)
return &diskType
}
// validateTierUploadDestination rejects an empty -dest or one the master does
// not have a storage backend for, before any volume is marked read-only. The
// volume server resolves the name against its own backend table, which the
// master distributes from the same configuration, so the master's list is the
// authoritative check available to the shell.
func validateTierUploadDestination(commandEnv *CommandEnv, dest string) error {
if dest == "" {
return fmt.Errorf("-dest is required, e.g. -dest=s3.default")
}
var backends []*master_pb.StorageBackend
err := commandEnv.MasterClient.WithClient(context.Background(), false, func(client master_pb.SeaweedClient) error {
resp, err := client.GetMasterConfiguration(context.Background(), &master_pb.GetMasterConfigurationRequest{})
if err != nil {
return err
}
backends = resp.GetStorageBackends()
return nil
})
if err != nil {
return fmt.Errorf("list storage backends from master: %v", err)
}
names := tierUploadBackendNames(backends)
if !names[dest] {
configured := make([]string, 0, len(names))
for name := range names {
configured = append(configured, name)
}
sort.Strings(configured)
return fmt.Errorf("unknown tier destination %q; configured storage backends: %v", dest, configured)
}
return nil
}
// tierUploadBackendNames expands the master's storage backend list into the
// destination names the volume server accepts, mirroring how
// backend.LoadFromPbStorageBackends registers "type.id" plus a bare "type"
// alias for the "default" id.
func tierUploadBackendNames(backends []*master_pb.StorageBackend) map[string]bool {
names := make(map[string]bool)
for _, b := range backends {
if b == nil || b.Type == "" {
continue
}
names[b.Type+"."+b.Id] = true
if b.Id == "default" {
names[b.Type] = true
}
}
return names
}
func uploadDatToRemoteTier(grpcDialOption grpc.DialOption, writer io.Writer, volumeId needle.VolumeId, collection string, sourceVolumeServer pb.ServerAddress, dest string, keepLocalDatFile bool, concurrency int) error {
err := operation.WithVolumeServerClient(true, sourceVolumeServer, grpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {
stream, copyErr := volumeServerClient.VolumeTierMoveDatToRemote(context.Background(), &volume_server_pb.VolumeTierMoveDatToRemoteRequest{
VolumeId: uint32(volumeId),
Collection: collection,
DestinationBackendName: dest,
KeepLocalDatFile: keepLocalDatFile,
Concurrency: int32(concurrency),
})
if stream == nil {
if copyErr == nil {
// when the volume is already uploaded, VolumeTierMoveDatToRemote will return nil stream and nil error
// so we should directly return in this caseAdd commentMore actions
fmt.Fprintf(writer, "volume %v already uploaded", volumeId)
return nil
} else {
return copyErr
}
}
var lastProcessed int64
for {
resp, recvErr := stream.Recv()
if recvErr != nil {
if recvErr == io.EOF {
break
} else {
return recvErr
}
}
processingSpeed := float64(resp.Processed-lastProcessed) / 1024.0 / 1024.0
fmt.Fprintf(writer, "copied %.2f%%, %d bytes, %.2fMB/s\n", resp.ProcessedPercentage, resp.Processed, processingSpeed)
lastProcessed = resp.Processed
}
return copyErr
})
return err
}