Documentation
¶
Overview ¶
Package mirror is a blob store that keeps each blob on several member stores at once (decision 0028): different clouds, regions or accounts, any mix of the fs, s3, gcs and azure backends.
Writes go to Redundancy members in parallel and succeed once WriteQuorum of them hold the blob; members still committing get MemberTimeout to finish in the background, and every member's outcome is recorded in the replica index (ReplicaIndex) as present or pending, so the repair worker can fill missing copies later. Reads use the index to go straight to a member holding the blob, in read order: this instance's zone first, then by observed latency, members whose breaker is open last. A read that fails part-way reopens on the next holder at the same offset, which is safe because blobs are immutable.
This is Artifactory's sharding provider (redundancy, lenientLimit, zone-aware reads) with three differences: members may be any backend in any cloud, an index records which members hold which blob instead of every read probing every shard, and surplus copies are never deleted automatically.
Role ¶
platform layer: a blob store over several member stores. Blob storage belongs to no module, so the mirror sits in the platform beside the backends it spreads blobs over, and is itself a blob.Store and a blob.Signer. The composition root builds one for each blob tier configured with members (blob and cold_blob), runs its repair loop, and gives the storage endpoints its status and optimize trigger. BlobIndex and ReplicaIndex, the parts of the metadata store's blob and replica indexes that the mirror calls, are declared here with the replica rows they carry, by the package that consumes them, so that it imports no store (decision 0044, "Narrowing"); the metadata store's indexes satisfy them, and the repair lease is taken through platform/work's LeaseStore. The package imports platform/blob, platform/blob/session, platform/work, the kernel and the standard library.
Inputs ¶
- Options for New: the Members (each a name, zone, blob store, kind and whether it takes new copies), Redundancy, WriteQuorum, this instance's Zone, MemberTimeout, ChunkSize, the breaker settings and the clock; Sessions, the session.Store that keeps the mirror's own upload sessions; and Replicas, the ReplicaIndex. The repair worker also takes Blobs, the BlobIndex, and Leases, a work.LeaseStore, with RepairLease, the batch, attempt and backoff settings, and OnRepair, which receives each pass.
- Through the blob.Store and blob.Signer methods: uploads, appended over one or more requests, and the SHA-256 of a stored blob for Open, Stat, Exists, Delete and SignURL.
- RunRepair's interval and trigger, which the optimize endpoint signals.
Outputs ¶
- Store, from New: a blob.Store and blob.Signer over the members, with Repair, RunRepair, Status and WaitIdle; Member, Options and the defaults; the sentinels ErrConfig, ErrQuorum and ErrSeek.
- The ports: BlobIndex, the one Get the repair worker calls, and ReplicaIndex, the eight replica methods the mirror calls, without Get.
- The replica rows: BlobReplica, ReplicaState with ReplicaPresent, ReplicaPending, ReplicaDeleting and ReplicaFailed, ReplicaFilter and ReplicaCount.
- RepairReport, what one repair pass did, and Status, with MemberStatus and RemovedMember, for the storage summary.
Invariants ¶
- An upload succeeds once WriteQuorum members hold the blob, and fails with ErrQuorum when fewer do.
- Every member's outcome is recorded in the replica index, as present or pending, so that the repair worker fills each missing copy.
- Reads go to a holder in read order, and a read that fails part-way reopens on the next holder at the same offset.
- Surplus copies are never deleted automatically: repair only adds copies and removes those of deleted blobs, and it keeps a blob that was uploaded again after its delete.
- A repair pass holds the lease that RepairLease names, so two mirrors sharing a lease store, such as the hot and cold tiers, need different names, or each pass of one skips the other.
References ¶
- Decision 0028: docs/research/decisions/0028-blob-mirroring.md (quorum writes, the replica index, zone-aware reads, background repair under a lease, and no automatic deletion of surplus copies).
- Decision 0004: docs/research/decisions/0004-storage-sql-metadata-and-blobs.md (the blob index, whose reference counts decide deferred deletes).
- Decision 0044: docs/research/decisions/0044-modular-monolith-migration.md ("Narrowing").
- Research 18: docs/research/18-cloud-blob-storage.md, section 3 (Artifactory's sharding).
- Target layout: docs/research/architecture-options/5-modular-monolith.md, line 148 (platform/blob/mirror), line 595 (the mirror's files) and line 1049 (the mapping row).
- Plan: docs/implementation/plan.md#p2b-cloud-blob-storage-and-mirroring and #p9d-modular-monolith-migration, epic PLT (https://github.com/weaveplatform/artifactweave/issues/938).
- https://github.com/weaveplatform/artifactweave/issues/22
- https://github.com/weaveplatform/artifactweave/issues/986
Status ¶
Implemented P2b: the replica rows (issue 15), the mirror with quorum writes and failover reads (issue 16, pull request 33), the repair worker with backfill and safe deferred deletes (issue 17, pull request 35), the cross-cloud scenario (issue 19, pull request 38) and chunks that align with every member's part size (issue 39, pull request 41); once P3 served the storage endpoints, Status and the optimize trigger (issue 18, pull request 66) and the replica records of removed members (issue 71, pull request 87). P4b: SignURL and Signs for download and CDN redirects, with signing failures kept out of member health (issue 119, pull requests 139 and 146). P7: SHA-512 among the digests that uploads record and repair checks (issue 296, pull request 298). Moved here in P9d: the index ports, with the replica rows beside them, and leases from platform/work.
Testing ¶
- mirror_test.go: the blobtest contract on three fakes, on file systems with a fake, with a redundancy of two of three and with durable sessions; a member down at append or failing at commit, a missed quorum, stragglers and the deletes and WaitIdle that wait for them, a cancelled commit; read failover, also after an early EOF, the breaker and a delete with a member down; signing; New's validation, chunk sizes and their alignment with part sizes, placement, resumes that drop lost members, and the failures of abort, walk, reads, the replica index and session saves.
- repair_test.go: copies, stragglers found, a missing source, a backoff that doubles and caps, copy failures, deferred deletes that never remove a blob uploaded again, backfill to an added member, draining a member that takes no new copies, skipping deleted and uncopied blobs, the lease and its name, RunRepair, errors, batches, and a pass that stops when its lease is taken over.
- status_test.go: TestUnitStatus and TestUnitStatusErrors.
- crosscloud_test.go: TestAccCrossCloud runs the contract and member outages over S3 on MinIO, GCS on fake-gcs-server and Azure on Azurite. It needs Docker and skips without it; CI runs it in the Linux unit job.
The tests are external (package mirror_test), and export_test.go opens the internals they reach. They build mirrors over testDB (testdb_test.go): the platform's in-memory upload and lease stores, and a blob and replica index that answers as the artifacts module's in-memory indexes do, since platform code, tests included, never imports a module. The artifacts contract runs the real indexes on the in-memory, SQLite and PostgreSQL stores.
Index ¶
- Constants
- Variables
- type BlobIndex
- type BlobReplica
- type Member
- type MemberStatus
- type Options
- type RemovedMember
- type RepairReport
- type ReplicaCount
- type ReplicaFilter
- type ReplicaIndex
- type ReplicaState
- type Status
- type Store
- func (s *Store) BeginUpload(ctx context.Context, opts ...blob.UploadOption) (blob.Upload, error)
- func (s *Store) Delete(ctx context.Context, sha string) error
- func (s *Store) Exists(ctx context.Context, sha string) (bool, error)
- func (s *Store) Open(ctx context.Context, sha string) (io.ReadSeekCloser, blob.Info, error)
- func (s *Store) Repair(ctx context.Context) (RepairReport, error)
- func (s *Store) ResumeUpload(ctx context.Context, id string) (blob.Upload, error)
- func (s *Store) RunRepair(ctx context.Context, every time.Duration, trigger <-chan struct{}) error
- func (s *Store) SignURL(ctx context.Context, sha string, o blob.SignOptions) (string, error)
- func (s *Store) Signs(via blob.Via) bool
- func (s *Store) Stat(ctx context.Context, sha string) (blob.Info, error)
- func (s *Store) Status(ctx context.Context) (Status, error)
- func (s *Store) WaitIdle(ctx context.Context) error
- func (s *Store) Walk(ctx context.Context, fn func(blob.Info) error) error
Constants ¶
const ( // DefaultMemberTimeout is how long members still committing after the // quorum may finish before their copy is left to the repair worker. DefaultMemberTimeout = 30 * time.Second // DefaultChunkSize is the smallest chunk New derives. A chunk is the // buffer one upload hands to every member at once, so a mirrored upload // holds one chunk in memory, not one per member. DefaultChunkSize = 8 << 20 // MaxDerivedChunkSize caps the chunk New derives from the members' part // sizes. Part sizes whose least common multiple is larger (5, 7 and 11 // MiB need 385 MiB) would cost that much memory per upload, and are // almost certainly a mistake. MaxDerivedChunkSize = 256 << 20 // DefaultBreakerThreshold is the consecutive failures that open a // member's breaker. DefaultBreakerThreshold = 5 // DefaultBreakerCooldown is how long an open breaker stays open before a // call is let through again; Artifactory's state-aware providers re-check // a failed store after the same 15 seconds (checkPeriod). DefaultBreakerCooldown = 15 * time.Second // DefaultRepairBatch is how many replicas one repair pass works on per // step, so a pass holds its lease for a bounded time. DefaultRepairBatch = 100 // DefaultRepairMaxAttempts is how many failed copies make a pending // replica failed, for an operator to look at. DefaultRepairMaxAttempts = 10 // DefaultRepairBackoff is the wait after a replica's first failed // attempt; it doubles with every attempt up to maxRepairBackoff, so a // copy that keeps failing is not retried in a tight loop. DefaultRepairBackoff = time.Minute )
Defaults for the zero Options fields.
const DefaultRepairInterval = time.Minute
DefaultRepairInterval is how often RunRepair runs a pass when no interval is given.
Variables ¶
var ( // ErrConfig reports an unusable configuration. ErrConfig = errors.New("blob/mirror: invalid configuration") // ErrQuorum reports a write that fewer than WriteQuorum members accepted. ErrQuorum = errors.New("blob/mirror: write quorum not met") )
Sentinel errors. Test with errors.Is.
var ErrSeek = errors.New("blob/mirror: invalid seek")
ErrSeek reports an invalid Seek.
Functions ¶
This section is empty.
Types ¶
type BlobIndex ¶
type BlobIndex interface {
// Get returns the row for sha256, in whatever state, or an error matching
// kernel.ErrNotFound when there is none: a deferred delete takes that as
// no reference and goes ahead, where any other error fails its step.
Get(ctx context.Context, sha256 string) (blob.Blob, error)
}
BlobIndex is the blob index the repair worker reads a blob's reference count and recorded digests from.
type BlobReplica ¶
type BlobReplica struct {
SHA256 string
Member string
State ReplicaState
Size int64
Attempts int
LastError string
Updated time.Time
}
BlobReplica records one mirror member's copy of one blob. The mirror keeps this index so reads go straight to a holder and repair works from a queue, where Artifactory's sharding has no index and probes every shard.
type Member ¶
type Member struct {
// Name identifies the member in the replica index; it must stay stable.
Name string
// Zone places the member, for example "aws-eu-west-1"; members in the
// instance's zone are read and written first.
Zone string
// Store is the member's blob store.
Store blob.Store
// WriteEnabled lets the member receive new copies. A member with it
// false is drained: it serves reads but gets nothing new.
WriteEnabled bool
// Kind names the member's backend (fs, s3, gcs, azure) for Status; the
// mirror itself does not use it.
Kind string
}
Member is one store of the mirror.
type MemberStatus ¶
type MemberStatus struct {
Name, Zone, Kind string
WriteEnabled bool
// Available is false while the member's breaker is open: reads and
// writes go to the other members first.
Available bool
// Latency is the weighted average of recent successful calls; zero
// before the first one.
Latency time.Duration
// Replicas are the member's replica records per state, ordered by state.
Replicas []ReplicaCount
// SoleCopies counts the blobs whose only present copy is on this
// member. A drained member (WriteEnabled false) is safe to remove from
// the configuration once it is zero.
SoleCopies int64
}
MemberStatus is one member's view in Status.
type Options ¶
type Options struct {
Members []Member
// Redundancy is how many members keep each blob; zero means every
// member (a full mirror).
Redundancy int
// WriteQuorum is how many members must store a blob before an upload
// succeeds. Zero means Redundancy-1 (at least 1): by default an upload
// still succeeds with one member down, which is the outage the mirror
// exists to ride out, and the missing copy is repaired later.
WriteQuorum int
// Zone is this instance's zone.
Zone string
// MemberTimeout bounds how long members may finish after the quorum;
// zero means DefaultMemberTimeout.
MemberTimeout time.Duration
// ChunkSize is the fan-out buffer. Zero derives it: the smallest
// multiple of every member's part size (blob.PartSizer) that is at least
// DefaultChunkSize, so the s3 and azure defaults (8 MiB) with the gcs
// default (16 MiB) give 16 MiB. An explicit size must be a multiple of
// every member's part size.
ChunkSize int64
// Sessions keeps the mirror's own upload sessions (the member upload
// IDs). Members keep their own sessions.
Sessions session.Store
// Replicas records which members hold which blobs.
Replicas ReplicaIndex
// BreakerThreshold and BreakerCooldown tune each member's breaker; zero
// means the defaults.
BreakerThreshold int
BreakerCooldown time.Duration
// Now supplies the time for the breaker, latency and replica records;
// nil means time.Now.
Now func() time.Time
// The repair worker's settings (repair.go). Blobs and Leases are only
// required by Repair: a mirror that never repairs may leave them nil.
//
// Blobs is the blob index whose reference counts tell a deferred delete
// whether the blob was uploaded again since.
Blobs BlobIndex
// Leases holds the lease that keeps two repair passes from overlapping.
Leases work.LeaseStore
// RepairLease names the lease a pass holds; empty means
// "blob-mirror-repair". Two mirrors sharing a lease store (the hot and
// cold tiers) need different names, or each pass of one skips the other.
RepairLease string
// RepairBatch, RepairMaxAttempts and RepairBackoff tune a pass; zero
// means the defaults.
RepairBatch int
RepairMaxAttempts int
RepairBackoff time.Duration
// OnRepair, when set, receives every pass RunRepair makes, so the server
// can log or count them.
OnRepair func(RepairReport, error)
}
Options configures New.
type RemovedMember ¶
type RemovedMember struct {
Name string
// Replicas are its replica records per state, ordered by state.
Replicas []ReplicaCount
// SoleCopies counts the blobs whose only present copy is on it.
SoleCopies int64
}
RemovedMember is a member in Status.Removed.
type RepairReport ¶
type RepairReport struct {
// Skipped is set when another pass held the lease; nothing was done.
Skipped bool
// Copied counts pending replicas filled by copying from another member.
Copied int
// Found counts pending replicas whose member already held the blob, for
// example a commit that finished after its record was written.
Found int
// Failed counts attempts that failed this pass.
Failed int
// Deleted counts tombstones whose copy was removed.
Deleted int
// DeletesSkipped counts tombstones of blobs uploaded again since the
// delete, which were kept rather than removed.
DeletesSkipped int
// Backfilled counts pending records added to bring a blob up to the
// redundancy, for example on a newly added member.
Backfilled int
// Drained counts pending records added because a blob's only copies are
// on members no longer accepting writes.
Drained int
}
RepairReport counts what one repair pass did.
type ReplicaCount ¶
type ReplicaCount struct {
Member string
State ReplicaState
Count int64
Bytes int64
}
ReplicaCount is one member's number of replicas in one state and their combined size, for the storage summary.
type ReplicaFilter ¶
type ReplicaFilter struct {
Member string
States []ReplicaState
}
ReplicaFilter narrows replica listings; empty fields match everything.
type ReplicaIndex ¶
type ReplicaIndex interface {
// Put creates or replaces the record (r.SHA256, r.Member);
// kernel.ErrInvalid without both.
Put(ctx context.Context, r BlobReplica) error
// ForBlob returns a blob's records ordered by member.
ForBlob(ctx context.Context, sha256 string) ([]BlobReplica, error)
// List returns matching records oldest update first, by (Updated, SHA256,
// Member), which is the order the repair worker drains them in.
List(ctx context.Context, f ReplicaFilter, p kernel.Page) ([]BlobReplica, string, error)
// Delete removes one record, or returns an error matching
// kernel.ErrNotFound when there is none, which the mirror ignores.
Delete(ctx context.Context, sha256, member string) error
// DeleteBlob removes every record of a blob and returns how many.
DeleteBlob(ctx context.Context, sha256 string) (int64, error)
// Counts returns the number and size of records per member and state,
// ordered by (member, state).
Counts(ctx context.Context) ([]ReplicaCount, error)
// UnderReplicated counts the blobs with fewer than redundancy present
// records. A blob with a deleting record is being deleted and is not
// counted; neither is a blob with no records at all, which the repair
// worker's backfill brings into the index.
UnderReplicated(ctx context.Context, redundancy int) (int64, error)
// SoleCopies counts, per member, the blobs whose only present record is
// on that member. Blobs being deleted are left out, as UnderReplicated
// leaves them out. A member holding sole copies cannot be removed from
// a mirror without losing them: repair never reads from a member that
// is no longer configured.
SoleCopies(ctx context.Context) (map[string]int64, error)
}
ReplicaIndex records which members hold which blobs. The mirror never calls Get.
type ReplicaState ¶
type ReplicaState string
ReplicaState is where one member of a blob mirror stands with one blob (decision 0028).
const ( // ReplicaPresent: the member holds the blob. ReplicaPresent ReplicaState = "present" // ReplicaPending: the member should hold the blob and the repair worker // will copy it there. ReplicaPending ReplicaState = "pending" // ReplicaDeleting: the blob was deleted and this member's copy still has // to be removed. ReplicaDeleting ReplicaState = "deleting" // ReplicaFailed: repair gave up after repeated attempts; an operator or a // manual repair pass has to act. ReplicaFailed ReplicaState = "failed" )
Replica states.
type Status ¶
type Status struct {
Redundancy int
WriteQuorum int
// Zone is this instance's zone.
Zone string
// UnderReplicated counts blobs with fewer present copies than
// Redundancy (ReplicaIndex.UnderReplicated).
UnderReplicated int64
Members []MemberStatus
// Removed are members with replica records that are no longer
// configured. Repair neither copies to nor reads from them, so a blob
// whose only present copy is on one (SoleCopies) is out of the mirror's
// reach until the member is configured again.
Removed []RemovedMember
}
Status is a mirror's configuration, member health and replica counts, for the storage summary (#18). Artifactory's summary has nothing per shard.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is a blob.Store over several member stores.
func (*Store) BeginUpload ¶
BeginUpload starts a session on the members placement chooses.
func (*Store) Delete ¶
Delete removes the blob from every member. A member that cannot be reached keeps a deleting record, a tombstone the repair worker acts on later; reads honour it, so the blob is gone for every reader as soon as Delete returns.
func (*Store) Open ¶
Open returns a reader that serves the blob from the first member that holds it and moves to the next one, at the same offset, if a read fails.
func (*Store) Repair ¶
func (s *Store) Repair(ctx context.Context) (RepairReport, error)
Repair runs one repair pass under the repair lease:
- pending replicas are copied to their member from a member that holds the blob, or marked present when the member already has it;
- deleting tombstones are carried out, unless the blob was uploaded again since the delete;
- blobs with fewer copies on write-enabled members than the redundancy get pending records, which fills a newly added member and moves the copies of a draining one.
Each step works on at most the repair batch, so a pass is bounded. It never deletes a copy because there are too many: removing a member stays an explicit operator action (decision 0028). When another pass holds the lease it returns a report with Skipped set and no error.
func (*Store) ResumeUpload ¶
ResumeUpload reopens a session and each active member's upload. A member whose upload cannot be resumed drops out of the session.
func (*Store) RunRepair ¶
RunRepair runs a repair pass every interval, and at once whenever trigger fires (the storage optimize endpoint sends on it), until ctx ends, then returns ctx's error. Each pass's report and error go to OnRepair when it is set; a failed pass does not stop the loop.
func (*Store) SignURL ¶
SignURL returns a URL from the first member, in read order, that holds the blob and signs o's route. A member's signing failure moves on to the next member but never counts against its health.
func (*Store) Signs ¶
Signs reports whether any member signs URLs for via. Members are fixed when the mirror is built, so the answer is too.
func (*Store) Status ¶
Status reports the mirror's members, their replica records, and the records of members no longer configured.
func (*Store) WaitIdle ¶
WaitIdle waits until the background commits running when it is called have finished and recorded their outcome, or ctx ends. A server calls it on shutdown so a member finishing after the quorum is recorded rather than left pending for no reason; a test calls it before looking at the members.