-
Notifications
You must be signed in to change notification settings - Fork 138
Takeout #5707
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Tristan-C789
wants to merge
11
commits into
cs3org:feat/takeout
Choose a base branch
from
Tristan-C789:feat/takeout
base: feat/takeout
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,013
−0
Draft
Takeout #5707
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
df42a97
takeout: add takeout http service to loader
Tristan-C789 2bba970
takeout: Add HTTP service (POST & GET endpoints)
Tristan-C789 bc29ad6
takeout: Add Takeout job
Tristan-C789 a07e8cb
takeout: Refactor archive size handling for better precision
Tristan-C789 37b5989
takeout: Add support for .tgz archive format
Tristan-C789 c6e83e9
takeout: Delete destination directory before new takeout
Tristan-C789 2fc363c
takeout: Make endpoints depend on HTTP method rather than suffix
Tristan-C789 90c4cc6
takeout: Refactor takeout container creation
Tristan-C789 092c32b
takeout: Add cleanup periodic job skeleton
Tristan-C789 0340dc5
takeout: Add cleanup logic
Tristan-C789 57d5b53
takeout: Refactor http svc & pkg configs, misc
Tristan-C789 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,266 @@ | ||
| package takeout | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "io" | ||
| "net/http" | ||
| "strings" | ||
| "time" | ||
|
|
||
| rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" | ||
| provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" | ||
| "github.com/cs3org/reva/v3/pkg/appctx" | ||
| "github.com/cs3org/reva/v3/pkg/rgrpc/todo/pool" | ||
| "github.com/cs3org/reva/v3/pkg/rhttp/global" | ||
| "github.com/cs3org/reva/v3/pkg/rjobs" | ||
| "github.com/cs3org/reva/v3/pkg/takeout" | ||
| "github.com/cs3org/reva/v3/pkg/takeout/cleanup" | ||
| "github.com/cs3org/reva/v3/pkg/utils/cfg" | ||
| "github.com/rs/zerolog" | ||
| ) | ||
|
|
||
| /* Service registration */ | ||
|
|
||
| // Init registers the takeout http service | ||
| func init() { | ||
| global.Register("takeout", New) | ||
| } | ||
|
|
||
| /* Service's configuration setup */ | ||
|
|
||
| // The takeout service Config | ||
| type Config struct { | ||
| Prefix string `mapstructure:"prefix"` | ||
| MachineSecret string `mapstructure:"machine_secret" validate:"required"` | ||
| GatewaySvc string `mapstructure:"gatewaysvc" validate:"required"` | ||
| TakeoutAdminUsername string `mapstructure:"takeout_admin_username" validate:"required"` | ||
| TakeoutPath string `mapstructure:"takeout_path" validate:"required"` | ||
| CleanupSchedule string `mapstructure:"cleanup_schedule"` | ||
| CleanupDelay int64 `mapstructure:"cleanup_delay"` // In hours | ||
| } | ||
|
|
||
| // New sets the potential custom service config | ||
| func New(ctx context.Context, m map[string]any) (global.Service, error) { | ||
| // Decode config | ||
| var c Config | ||
| if err := cfg.Decode(m, &c); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Declare logger | ||
| l := appctx.GetLogger(ctx) | ||
|
|
||
| // Register periodic cleanup job | ||
| cleanupConfig := &cleanup.Config{ | ||
| MachineSecret: c.MachineSecret, | ||
| GatewaySvc: c.GatewaySvc, | ||
| TakeoutAdminUsername: c.TakeoutAdminUsername, | ||
| TakeoutPath: c.TakeoutPath, | ||
| CleanupSchedule: c.CleanupSchedule, | ||
| CleanupDelay: c.CleanupDelay, | ||
| } | ||
| cleanup.RegisterCleanup(ctx, cleanupConfig, l) | ||
|
|
||
| return &svc{conf: &c, log: l}, nil | ||
| } | ||
|
|
||
| // ApplyDefaults sets the default service config | ||
| func (c *Config) ApplyDefaults() { | ||
| if c.Prefix == "" { | ||
| c.Prefix = "takeout" | ||
| } | ||
| if c.CleanupSchedule == "" { | ||
| c.CleanupSchedule = "@daily" | ||
| } | ||
| if c.CleanupDelay == 0 { | ||
| c.CleanupDelay = 168 // One week | ||
| } | ||
| } | ||
|
|
||
| // The GET JSON reply structure | ||
| type statusReply struct { | ||
| RunID string `json:"run_id"` | ||
| State string `json:"state"` | ||
| EnqueuedAt time.Time `json:"enqueued_at"` | ||
| StartedAt *time.Time `json:"started_at,omitempty"` | ||
| FinishedAt *time.Time `json:"finished_at,omitempty"` | ||
| Error string `json:"error,omitempty"` | ||
| ArchivesURL string `json:"archives_url,omitempty"` | ||
| ArchivesPath string `json:"archives_path,omitempty"` | ||
| } | ||
|
|
||
| /* Service setup */ | ||
|
|
||
| // The takeout service structure | ||
| type svc struct { | ||
| conf *Config | ||
| log *zerolog.Logger | ||
| } | ||
|
|
||
| // Close performs a clean up | ||
| func (s *svc) Close() error { | ||
| return nil | ||
| } | ||
|
|
||
| // Prefix sets the prefix | ||
| func (s *svc) Prefix() string { | ||
| return s.conf.Prefix | ||
| } | ||
|
|
||
| // Unprotected sets the unprotected paths | ||
| func (s *svc) Unprotected() []string { | ||
| return nil | ||
| } | ||
|
|
||
| // Handler propagates the request depending on the suffix | ||
| func (s *svc) Handler() http.Handler { | ||
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| // The only accepted suffix should be the conf one | ||
| url := strings.TrimSuffix(r.URL.Path, "/") | ||
| if url != "" { | ||
| s.log.Warn().Msgf("takeout: %s is not a supported suffix", url) | ||
| w.WriteHeader(http.StatusNotFound) | ||
| return | ||
| } | ||
|
|
||
| // Dispatch depending on request method | ||
| s.log.Info().Msgf("takeout: handling method %s", r.Method) | ||
| switch r.Method { | ||
| case http.MethodPost: | ||
| s.handlePost(w, r) | ||
| case http.MethodGet: | ||
| s.handleGet(w, r) | ||
|
|
||
| default: | ||
| s.log.Warn().Msgf("takeout: %s is not a supported method", r.Method) | ||
| w.WriteHeader(http.StatusBadRequest) | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| func (s *svc) handlePost(w http.ResponseWriter, r *http.Request) { | ||
| // Parse parameters from the request body | ||
| req := struct { | ||
| ArchiveFormat string `json:"archive_format"` | ||
| MaxArchiveSize int64 `json:"max_archive_size"` | ||
| }{ | ||
| // Default values | ||
| ArchiveFormat: "zip", | ||
| MaxArchiveSize: 2 << 30, // 2 GiB | ||
| } | ||
| if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF { | ||
| s.log.Err(err).Msg("takeout: could not decode job parameters") | ||
| w.WriteHeader(http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| // Get job runner | ||
| runner := rjobs.Default() | ||
| if runner == nil { | ||
| s.log.Error().Msg("takeout: could not find runner") | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| // Get current authenticated user | ||
| user := appctx.ContextMustGetUser(r.Context()) | ||
|
|
||
| // Get root path | ||
| gtw, err := pool.GetGatewayServiceClient(pool.Endpoint(s.conf.GatewaySvc)) | ||
| if err != nil { | ||
| s.log.Error().Msg("takeout: could not get gateway") | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| return | ||
| } | ||
| homeRes, err := gtw.GetHome(r.Context(), &provider.GetHomeRequest{}) | ||
| if err != nil { | ||
| s.log.Err(err).Msg("takeout: could not find home directory") | ||
| } | ||
| if homeRes.Status.Code != rpc.Code_CODE_OK { | ||
| s.log.Error().Msgf("takeout: could not find home directory: %s", homeRes.Status.Message) | ||
| } | ||
| rootPath := homeRes.Path | ||
|
|
||
| // Enqueue job | ||
| runId, err := runner.Enqueue(r.Context(), takeout.JobName, rjobs.Params{ | ||
| "archive_format": req.ArchiveFormat, | ||
| "max_archive_size": req.MaxArchiveSize, | ||
| "username": user.Username, | ||
| "root_path": rootPath, | ||
| }, rjobs.WithOwner(user.Username), rjobs.Unique("takeout:"+user.Username)) | ||
| if err != nil { | ||
| s.log.Err(err).Msg("takeout: could not enqueue job") | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| // Reply with job ID | ||
| s.log.Info().Msgf("takeout: takeout job %s enqueued", runId) | ||
| w.WriteHeader(http.StatusOK) | ||
| } | ||
|
|
||
| func (s *svc) handleGet(w http.ResponseWriter, r *http.Request) { | ||
| // Get job runner | ||
| runner := rjobs.Default() | ||
| if runner == nil { | ||
| s.log.Error().Msg("takeout: could not find runner") | ||
| w.WriteHeader(http.StatusFailedDependency) | ||
| return | ||
| } | ||
|
|
||
| // Get takeout job from username, if any | ||
| user := appctx.ContextMustGetUser(r.Context()) | ||
| jobs, err := runner.ListByOwner(r.Context(), user.Username, rjobs.ListFilter{Job: "takeout"}) | ||
| if err != nil { | ||
| s.log.Err(err).Msg("takeout: could not list user's jobs") | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| return | ||
| } | ||
| if len(jobs) == 0 { | ||
| s.log.Debug().Msgf("takeout: user %s has no takeout job attached", user.Username) | ||
| w.WriteHeader(http.StatusNotFound) | ||
| return | ||
| } | ||
|
|
||
| // Handle latest job | ||
| st := jobs[0] | ||
|
Tristan-C789 marked this conversation as resolved.
|
||
| rep := statusReply{ | ||
| RunID: string(st.RunID), | ||
| State: string(st.State), | ||
| EnqueuedAt: st.EnqueuedAt, | ||
| StartedAt: st.StartedAt, | ||
| FinishedAt: st.FinishedAt, | ||
| } | ||
| switch st.State { | ||
| case rjobs.StateFailed: | ||
| rep.Error = st.LastError | ||
| case rjobs.StateSucceeded: | ||
| // Reply with the public link to the archives | ||
| url, okT := st.Result["archives_url"].(string) | ||
| path, okP := st.Result["archives_path"].(string) | ||
| if !okT || !okP { | ||
| // Unreachable | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| return | ||
| } | ||
| rep.ArchivesURL = url | ||
| rep.ArchivesPath = path | ||
| case rjobs.StateQueued, rjobs.StateRunning: | ||
| // Nothing to add | ||
| default: | ||
| // Unreachable | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| // Encode and send the JSON reply | ||
| body, err := json.Marshal(rep) | ||
| if err != nil { | ||
| // Unreachable | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| return | ||
| } | ||
| w.Header().Set("Content-Type", "application/json") | ||
| w.Write(body) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.