π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[server] Remove clear orphan object cleanup flow
Manav Rathi27b66aa7dcdc
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 054e84c3b9..e7648c7612 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -277,8 +277,6 @@ func main() {objectCleanupController := controller.NewObjectCleanupController(objectCleanupRepo,objectRepo,- lockController,- objectController,s3Config,)@@ -923,25 +921,24 @@ func main() {privateAPI.POST("/storage-bonus/referral-claim", storageBonusHandler.ClaimReferral)adminHandler := &api.AdminHandler{- QueueRepo: queueRepo,- UserRepo: userRepo,- CollectionRepo: collectionRepo,- AuthenticatorRepo: authRepo,- UserAuthRepo: userAuthRepo,- UserController: userController,- FamilyController: familyController,- EmergencyController: emergencyCtrl,- RemoteStoreController: remoteStoreController,- FileRepo: fileRepo,- StorageBonusRepo: storagBonusRepo,- BillingRepo: billingRepo,- BillingController: billingController,- ObjectCleanupController: objectCleanupController,- MailingListsController: mailingListsController,- DiscordController: discordController,- HashingKey: hashingKeyBytes,- PasskeyController: passkeyCtrl,- StorageBonusCtl: storageBonusCtrl,+ QueueRepo: queueRepo,+ UserRepo: userRepo,+ CollectionRepo: collectionRepo,+ AuthenticatorRepo: authRepo,+ UserAuthRepo: userAuthRepo,+ UserController: userController,+ FamilyController: familyController,+ EmergencyController: emergencyCtrl,+ RemoteStoreController: remoteStoreController,+ FileRepo: fileRepo,+ StorageBonusRepo: storagBonusRepo,+ BillingRepo: billingRepo,+ BillingController: billingController,+ MailingListsController: mailingListsController,+ DiscordController: discordController,+ HashingKey: hashingKeyBytes,+ PasskeyController: passkeyCtrl,+ StorageBonusCtl: storageBonusCtrl,}adminAPI.POST("/mail", adminHandler.SendMail)adminAPI.POST("/mail/subscribe", adminHandler.SubscribeMail)@@ -966,7 +963,6 @@ func main() {adminAPI.PUT("/user/subscription", adminHandler.UpdateSubscription)adminAPI.POST("/queue/re-queue", adminHandler.ReQueueItem)adminAPI.POST("/user/bonus", adminHandler.UpdateBonus)- adminAPI.POST("/job/clear-orphan-objects", adminHandler.ClearOrphanObjects)userEntityController := &userEntityCtrl.Controller{Repo: userEntityRepo}userEntityHandler := &api.UserEntityHandler{Controller: userEntityController}@@ -1214,7 +1210,6 @@ func setupAndStartBackgroundJobs(fileDataCtrl.StartDataDeletion() // Start data deletion for file data;contactController.StartDataDeletion()objectCleanupController.StartRemovingUnreportedObjects()- objectCleanupController.StartClearingOrphanObjects()}func setupAndStartCrons(userAuthRepo *repo.UserAuthRepository, collectionLinkRepo *public.CollectionLinkRepo,diff --git a/server/configurations/local.yaml b/server/configurations/local.yamlindex 1d2dc0f525..319c585042 100644--- a/server/configurations/local.yaml+++ b/server/configurations/local.yaml@@ -436,8 +436,3 @@ jobs:# Number of go routines to spawn for object cleanup# Optional, default value is indicated here.worker-count: 1- clear-orphan-objects:- # By default, this job is disabled.- enabled: false- # If provided, only objects that begin with this prefix are pruned.- prefix: ""diff --git a/server/ente/admin.go b/server/ente/admin.goindex d70002dd70..3876f1d37b 100644--- a/server/ente/admin.go+++ b/server/ente/admin.go@@ -148,17 +148,3 @@ func (u SupportUpdateBonus) Validate() error {}return nil}--// ClearOrphanObjectsRequest is the API request to trigger the process for-// clearing orphan objects in DC.-//-// The optional prefix can be specified to limit the cleanup to objects that-// begin with that prefix.-//-// ForceTaskLock can be used to force the cleanup to start even if there is an-// existing task lock for the clear orphan objects task.-type ClearOrphanObjectsRequest struct {- DC string `json:"dc" binding:"required"`- Prefix string `json:"prefix"`- ForceTaskLock bool `json:"forceTaskLock"`-}diff --git a/server/pkg/api/admin.go b/server/pkg/api/admin.goindex 412a455c52..0ca379fbe3 100644--- a/server/pkg/api/admin.go+++ b/server/pkg/api/admin.go@@ -39,25 +39,24 @@ import (// AdminHandler exposes request handlers for all admin related requeststype AdminHandler struct {- QueueRepo *repo.QueueRepository- UserRepo *repo.UserRepository- CollectionRepo *repo.CollectionRepository- AuthenticatorRepo *authenticator.Repository- UserAuthRepo *repo.UserAuthRepository- FileRepo *repo.FileRepository- BillingRepo *repo.BillingRepository- StorageBonusRepo *storagebonus.Repository- BillingController *controller.BillingController- UserController *user.UserController- EmergencyController *emergency.Controller- FamilyController *family.Controller- RemoteStoreController *remotestore.Controller- ObjectCleanupController *controller.ObjectCleanupController- MailingListsController *controller.MailingListsController- DiscordController *discord.DiscordController- HashingKey []byte- PasskeyController *controller.PasskeyController- StorageBonusCtl *storagebonusCtrl.Controller+ QueueRepo *repo.QueueRepository+ UserRepo *repo.UserRepository+ CollectionRepo *repo.CollectionRepository+ AuthenticatorRepo *authenticator.Repository+ UserAuthRepo *repo.UserAuthRepository+ FileRepo *repo.FileRepository+ BillingRepo *repo.BillingRepository+ StorageBonusRepo *storagebonus.Repository+ BillingController *controller.BillingController+ UserController *user.UserController+ EmergencyController *emergency.Controller+ FamilyController *family.Controller+ RemoteStoreController *remotestore.Controller+ MailingListsController *controller.MailingListsController+ DiscordController *discord.DiscordController+ HashingKey []byte+ PasskeyController *controller.PasskeyController+ StorageBonusCtl *storagebonusCtrl.Controller}// Duration for which an admin's token is considered valid@@ -679,18 +678,3 @@ func (h *AdminHandler) attachSubscription(ctx *gin.Context, userID int64, responresponse["authCodes"] = authEntryCount}}--func (h *AdminHandler) ClearOrphanObjects(c *gin.Context) {- var req ente.ClearOrphanObjectsRequest- err := c.ShouldBindJSON(&req)- if err != nil {- handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, ""))- return- }- if !h.ObjectCleanupController.IsValidClearOrphanObjectsDC(req.DC) {- handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "unsupported dc %s", req.DC))- return- }- go h.ObjectCleanupController.ClearOrphanObjects(req.DC, req.Prefix, req.ForceTaskLock)- c.JSON(http.StatusOK, gin.H{})-}diff --git a/server/pkg/controller/object_cleanup.go b/server/pkg/controller/object_cleanup.goindex de13d3a1b4..edfb2886eb 100644--- a/server/pkg/controller/object_cleanup.go+++ b/server/pkg/controller/object_cleanup.go@@ -3,50 +3,32 @@ package controllerimport ("database/sql""errors"- "fmt""strings"- "sync"stime "time"- "github.com/ente-io/museum/pkg/controller/lock""github.com/ente-io/stacktrace"- "github.com/prometheus/client_golang/prometheus"- "github.com/prometheus/client_golang/prometheus/promauto""github.com/spf13/viper""github.com/aws/aws-sdk-go/service/s3""github.com/ente-io/museum/ente""github.com/ente-io/museum/pkg/repo""github.com/ente-io/museum/pkg/utils/s3config"- enteString "github.com/ente-io/museum/pkg/utils/string""github.com/ente-io/museum/pkg/utils/time"log "github.com/sirupsen/logrus")-// ObjectCleanupController exposes functions to remove orphan and stale entries-// from object storage.-//-// There are 3 main types of orphans that can end up in our object storage:+// ObjectCleanupController exposes functions to remove temporary object storage+// entries that were never committed to the database.//// 1. We create presigned URLs for clients to upload their objects to. It might// happen that the client is able to successfully upload to these URLs, but// not tell museum about the successful upload.//// 2. During replication, we might have half-done multipart uploads.-//-// 3. When an existing object is updated (e.g. the user edits the file on iOS),-// then the file entry in our DB is updated to point to the new object, and-// the old object is now meant to be discarded.-//-// ObjectCleanupController is meant to manage all these scenarios over time.type ObjectCleanupController struct {- Repo *repo.ObjectCleanupRepository- ObjectRepo *repo.ObjectRepository- LockController *lock.LockController- ObjectController *ObjectController- S3Config *s3config.S3Config- // Prometheus Metrics- mOrphanObjectsDeleted *prometheus.CounterVec+ Repo *repo.ObjectCleanupRepository+ ObjectRepo *repo.ObjectRepository+ S3Config *s3config.S3Config}// PreSignedRequestValidityDuration is the lifetime of a pre-signed URL@@ -55,38 +37,16 @@ const PreSignedRequestValidityDuration = 7 * 24 * stime.Hour// PreSignedPartUploadRequestDuration is the lifetime of a pre-signed multipart URLconst PreSignedPartUploadRequestDuration = 7 * 24 * stime.Hour-// clearOrphanObjectsCheckInterval is the interval after which we check if the-// ClearOrphanObjects job needs to be re-run.-//-// See also, clearOrphanObjectsMinimumJobInterval.-const clearOrphanObjectsCheckInterval = 1 * 24 * stime.Hour--// ClearOrphanObjectsMinimumJobInterval is the minimum interval that must pass-// before we run another instance of the ClearOrphanObjects job.-//-// This interval is enforced across museum instances.-const clearOrphanObjectsMinimumJobInterval = 2 * 24 * stime.Hour-// Return a new instance of ObjectCleanupControllerfunc NewObjectCleanupController(objectCleanupRepo *repo.ObjectCleanupRepository,objectRepo *repo.ObjectRepository,- lockController *lock.LockController,- objectController *ObjectController,s3Config *s3config.S3Config,) *ObjectCleanupController {- mOrphanObjectsDeleted := promauto.NewCounterVec(prometheus.CounterOpts{- Name: "museum_orphan_objects_deleted_total",- Help: "Number of objects successfully deleted when clearing orphan objects",- }, []string{"dc"})-return &ObjectCleanupController{- Repo: objectCleanupRepo,- ObjectRepo: objectRepo,- LockController: lockController,- ObjectController: objectController,- S3Config: s3Config,- mOrphanObjectsDeleted: mOrphanObjectsDeleted,+ Repo: objectCleanupRepo,+ ObjectRepo: objectRepo,+ S3Config: s3Config,}}@@ -369,320 +329,3 @@ func isUnknownUploadError(err error) bool {}return false}--// StartClearingOrphanObjects is the entry point for the job that goes through-// all the objects in the given datacenter, and deletes orphan objects for which-// we do not have DB entries.-//-// Such orphan objects are expected to have been created because the code for-// updating the DB entries when a file gets updated did not cleanup the-// corresponding objects from object storage. Once we start keeping track of-// such objects in a separate queue, this cron job won't be needed.-func (c *ObjectCleanupController) StartClearingOrphanObjects() {- // TODO: object_cleanup: This code is only currently tested for B2- if c.S3Config.GetHotDataCenter() != c.S3Config.GetHotBackblazeDC() {- log.Info("Skipping ClearingOrphanObjects since the Hot DC is not B2")- return- }-- isJobEnabled := viper.GetBool("jobs.clear-orphan-objects.enabled")- if !isJobEnabled {- return- }-- prefix := viper.GetString("jobs.clear-orphan-objects.prefix")-- log.Infof("Starting workers to clear-orphan-objects (prefix %s)", prefix)-- // TODO: object_cleanup: start workers for other DCs once the temp_objects- // table supports specifying a DC- go c.clearOrphanObjectsWorker(c.S3Config.GetHotBackblazeDC(), prefix)-}--// clearOrphanObjectsWorker is the entry point for the worker goroutine to-// cleanup objects in a particular DC.-func (c *ObjectCleanupController) clearOrphanObjectsWorker(dc string, prefix string) {- for {- c.ClearOrphanObjects(dc, prefix, false)- stime.Sleep(clearOrphanObjectsCheckInterval)- }-}--// IsValidClearOrphanObjectsDC verifies that the given DC is valid for use as-// the target of an orphan object cleanup.-func (c *ObjectCleanupController) IsValidClearOrphanObjectsDC(dc string) bool {- if dc != c.S3Config.GetHotBackblazeDC() {- return false- }-- // TODO: object_cleanup: This code is only currently tested for B2- if c.S3Config.GetHotDataCenter() != c.S3Config.GetHotBackblazeDC() {- return false- }-- return true-}--func (c *ObjectCleanupController) ClearOrphanObjects(dc string, prefix string, forceTaskLock bool) {- logger := log.WithFields(log.Fields{- "task": "clear-orphan-objects",- "data_center": dc,- })-- if !c.IsValidClearOrphanObjectsDC(dc) {- logger.Errorf("Unsupported DC %s", dc)- return- }-- lockName := clearOrphanObjectsLockName(dc)-- if forceTaskLock {- logger.Infof("Forcefully removing task lock %s", lockName)- err := c.LockController.TaskLockingRepo.ReleaseLock(lockName)- if err != nil {- logger.Error(stacktrace.Propagate(err, ""))- return- }- }-- if !c.LockController.TryLock(lockName, clearOrphanObjectsNextLockUntil()) {- logger.Infof("Skipping since a lock could not be obtained")- return- }- // The lock is not released intentionally- //- // By keeping the stale entry for the unheld lock in the DB, we will be able- // to retain the timestamp when this job last ran. This is a kludgy way to- // guarantee that clearOrphanObjectsMinimumJobInterval is enforced across- // all museum instances (without introducing a new DB table).- //- // defer c.LockController.ReleaseLock(lockName)-- s3Config := c.S3Config- dest := &CleanupOrphanObjectsDestination{- DC: dc,- Client: s3Config.GetS3Client(dc),- Bucket: s3Config.GetBucket(dc),- HasComplianceHold: s3Config.WasabiComplianceDC() == dc,- }-- logger.Infof("Clearing orphan objects from bucket %s (hasComplianceHold %v)",- *dest.Bucket, dest.HasComplianceHold)-- // Each directory listing of an S3 bucket returns a maximum of 1000 objects,- // and an optional continuation token. Until there are more objects- // (indicated by the presence of the continuation token), keep fetching- // directory listings.- //- // For each directory listing, spawn 10 goroutines to go through chunks of- // 100 each to clear orphan objects.- //- // Refresh the lock's acquisition time during each iteration since this job- // can span hours, and we don't want a different instance to start another- // run just because it was only considering the start time of the job.-- err := dest.Client.ListObjectVersionsPages(&s3.ListObjectVersionsInput{- Bucket: dest.Bucket,- Prefix: &prefix,- },- func(page *s3.ListObjectVersionsOutput, lastPage bool) bool {- c.clearOrphanObjectsPage(page, dest, logger)-- lerr := c.LockController.ExtendLock(lockName, clearOrphanObjectsNextLockUntil())- if lerr != nil {- logger.Error(lerr)- return false- }-- return true- })- if err != nil {- logger.Error(stacktrace.Propagate(err, ""))- return- }-- logger.Info("Cleared orphan objects")-}--func clearOrphanObjectsLockName(dc string) string {- return fmt.Sprintf("clear-orphan-objects:%s", dc)-}--func clearOrphanObjectsNextLockUntil() int64 {- return time.Microseconds() + clearOrphanObjectsMinimumJobInterval.Microseconds()-}--type CleanupOrphanObjectsDestination struct {- DC string- Client s3.S3- Bucket *string- // If true, this bucket has a compliance hold on objects that needs to be- // removed first before they can be deleted.- HasComplianceHold bool-}--// ObjectVersionOrDeleteMarker is an abstraction to allow us to reuse the same-// code to delete both object versions and delete markers-type ObjectVersionOrDeleteMarker struct {- ObjectVersion *s3.ObjectVersion- DeleteMarker *s3.DeleteMarkerEntry-}--func (od ObjectVersionOrDeleteMarker) GetKey() *string {- if od.ObjectVersion != nil {- return od.ObjectVersion.Key- }- return od.DeleteMarker.Key-}--func (od ObjectVersionOrDeleteMarker) GetLastModified() *stime.Time {- if od.ObjectVersion != nil {- return od.ObjectVersion.LastModified- }- return od.DeleteMarker.LastModified-}--func (od ObjectVersionOrDeleteMarker) GetVersionId() *string {- if od.ObjectVersion != nil {- return od.ObjectVersion.VersionId- }- return od.DeleteMarker.VersionId-}--func (c *ObjectCleanupController) clearOrphanObjectsPage(page *s3.ListObjectVersionsOutput, dest *CleanupOrphanObjectsDestination, logger *log.Entry) error {- // MaxKeys is 1000. Until we can, break it into batches and create a- // separate goroutine to process each batch.- batchSize := 10-- versions := page.Versions- nv := len(versions)- deleteMarkers := page.DeleteMarkers- nd := len(deleteMarkers)- n := nv + nd-- logger.Infof("Processing page containing %d values (%d object versions, %d delete markers)", n, nv, nd)-- ods := make([]ObjectVersionOrDeleteMarker, n)- for i := 0; i < nv; i++ {- ods[i] = ObjectVersionOrDeleteMarker{ObjectVersion: versions[i]}- }- for i := 0; i < nd; i++ {- ods[nv+i] = ObjectVersionOrDeleteMarker{DeleteMarker: deleteMarkers[i]}- }-- var wg sync.WaitGroup-- for i := 0; i < n; i++ {- end := min(i+batchSize, n)-- if i >= end {- // Nothing left- break- }-- start, stop := i, end- wg.Go(func() {- batch := ods[start:stop]- c.clearOrphanObjectsVersionOrDeleteMarkers(batch, dest, logger)- })-- i = end- }-- wg.Wait()-- return nil-}--func (c *ObjectCleanupController) clearOrphanObjectsVersionOrDeleteMarkers(ods []ObjectVersionOrDeleteMarker, dest *CleanupOrphanObjectsDestination, logger *log.Entry) {- for _, od := range ods {- c.clearOrphanObjectsVersionOrDeleteMarker(od, dest, logger)- }-}--func (c *ObjectCleanupController) clearOrphanObjectsVersionOrDeleteMarker(od ObjectVersionOrDeleteMarker, dest *CleanupOrphanObjectsDestination, logger *log.Entry) {- if od.GetKey() == nil || od.GetLastModified() == nil {- logger.Errorf("Ignoring object with missing fields: %v %v", od.GetKey(), od.GetLastModified())- return- }-- objectKey := *od.GetKey()- lastModified := *od.GetLastModified()-- logger = logger.WithFields(log.Fields{- "object_key": objectKey,- "last_modified": lastModified,- })-- exists, err := c.ObjectRepo.DoesObjectOrTempObjectExist(objectKey)- if err != nil {- logger.Error(stacktrace.Propagate(err, "Failed to determine if object already exists in DB"))- return- }-- if exists {- return- }-- // 2 days ago- cutoff := stime.Now().AddDate(0, 0, -2)-- // As a safety check, ignore very recent objects from cleanup- if lastModified.After(cutoff) {- logger.Warnf("Ignoring too-recent orphan object since it was modified after %v", cutoff)- return- }-- logger.Infof("Found orphan object %v", od)-- if dest.HasComplianceHold {- // Remove compliance hold.- err := c.ObjectController.DisableObjectConditionalHold(&dest.Client, *dest.Bucket, objectKey)- if err != nil {- logger.Error(stacktrace.Propagate(err, "Failed to disable conditional hold on object"))- return- }-- // Add the object to the cleanup queue with an expiry time that is after- // the compliance hold would've passed. Add 2 days of buffer too.- expiryDays := s3config.WasabiObjectConditionalHoldDays + 2- expiryTime := time.MicrosecondsAfterDays(expiryDays)- c.addCleanupEntryForObjectKey(objectKey, dest.DC, expiryTime)-- logger.Infof("Disabled compliance hold and added an entry to cleanup orphan object after %v", expiryTime)- } else {- // Delete it right away.- versionID := od.GetVersionId()- logger.Infof("Deleting version '%s'", enteString.EmptyIfNil(versionID))- err := c.DeleteObjectVersion(objectKey, versionID, dest)- if err != nil {- logger.Error(stacktrace.Propagate(err, "Failed to delete object"))- }-- c.mOrphanObjectsDeleted.WithLabelValues(dest.DC).Inc()- }-}--// DeleteObjectVersion can be used to delete objects from versioned buckets.-//-// If we delete an object in a versioning enabled bucket, deletion does not-// actually remove the object and instead creates a delete marker:-//-// - When we delete a file, it creates a delete marker-// - The delete marker becomes the latest version-// - The old version of the file still remains-//-// If we explicitly pass a version ID in the delete call, then the delete marker-// won't get created.-//-// > To delete versioned objects permanently, use `DELETE Object versionId`-//-// https://docs.aws.amazon.com/AmazonS3/latest/userguide/DeletingObjectVersions.html-func (c *ObjectCleanupController) DeleteObjectVersion(objectKey string, versionID *string, dest *CleanupOrphanObjectsDestination) error {- _, err := dest.Client.DeleteObject(&s3.DeleteObjectInput{- Bucket: dest.Bucket,- Key: &objectKey,- VersionId: versionID,- })- return stacktrace.Propagate(err, "")-}