Files
fission-src/storagesvc/stowClient.go
T
smruthi2187andTa-Ching Chen 31ba992726 Archive pruner (#471)
All functions have a pkg reference. This can be a package with either source and a deploy archives, or, a deploy archive. Everytime a function is updated, a new package is created. With archive pruner, the archives that are pointed to by old pkg reference can be deleted from the storage.

* High level spec for package pruning.
* Skeleton for archive pruning
* Adding meat 1 to skeleton.
* Adding meat #2. Separated storage service into a httpHandler component and
Storage Layer component.
* Adding meat #3. getOrphanedArchives in pruner and getItems on
stowClient.
* Restructured archivePruner methods.
* Commiting the day's work. Ready for testing #1.
* Fixing compile errors.
* Test ready. added a few logs for debugging.
* Adding a filter for getItems in stowClient.
* After testing.
* Added a test for archivePruner.
* Adding helm value pruneInterval for testing.
* Modified test.
* Final test.
* Fixing interval from seconds to minutes.
* Small change.
* Changing debugs to info.
* Removing the WIP design
* Ran gofmt on all these files.
* Fixing prune_interval as string in ENV var.

* Addressing all comments, but one.

* changing getFile method in stowClient to stream it into a response.

* All comments incorporated.
* Introducing a new flag for running archivePruner.
1. This flag is disabled for archivePruner to run in unit test.
2. This flag is enabled for archivePruner to run in production.
3. Also disabling test_archive_pruner.sh in this PR. Follow up with
next PR to enable it.

* Addressing review comments.

* Changing the command to generate a file dynamically.

* Enabling arching_pruner_test

* giving execute permissions to test_archive_pruner.sh

* Making changes of positional parameters after recent commit.
Change test case permission and removing kubectlPortForward.

* Adding debug to see why test_utils.sh passed junk pruneInterval.

* shell needs special handling for positional parameters from 10.
2018-02-01 18:13:36 +08:00

202 lines
5.4 KiB
Go

/*
Copyright 2017 The Fission Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package storagesvc
import (
"errors"
"io"
"mime/multipart"
"os"
"time"
"github.com/graymeta/stow"
_ "github.com/graymeta/stow/local"
"github.com/satori/go.uuid"
log "github.com/sirupsen/logrus"
)
type (
StorageType string
storageConfig struct {
storageType StorageType
localPath string
containerName string
// other stuff, such as google or s3 credentials, bucket names etc
}
StowClient struct {
config *storageConfig
location stow.Location
container stow.Container
}
)
const (
StorageTypeLocal StorageType = "local"
PaginationSize int = 10
)
var (
ErrNotFound = errors.New("not found")
ErrRetrievingItem = errors.New("unable to retrieve item")
ErrOpeningItem = errors.New("unable to open item")
ErrWritingFile = errors.New("unable to write file")
ErrWritingFileIntoResponse = errors.New("unable to copy item into http response")
)
func MakeStowClient(storageType StorageType, storagePath string, containerName string) (*StowClient, error) {
if storageType != StorageTypeLocal {
return nil, errors.New("Storage types other than 'local' are not implemented")
}
config := &storageConfig{
storageType: storageType,
localPath: storagePath,
containerName: containerName,
}
stowClient := &StowClient{
config: config,
}
cfg := stow.ConfigMap{"path": config.localPath}
loc, err := stow.Dial("local", cfg)
if err != nil {
log.WithError(err).Error("Error initializing storage")
return nil, err
}
stowClient.location = loc
con, err := loc.CreateContainer(config.containerName)
if os.IsExist(err) {
var cons []stow.Container
var cursor string
// use location.Containers to find containers that match the prefix (container name)
cons, cursor, err = loc.Containers(config.containerName, stow.CursorStart, 1)
if err == nil {
if !stow.IsCursorEnd(cursor) {
// Should only have one storage container
err = errors.New("Found more than one matched storage containers")
} else {
con = cons[0]
}
}
}
if err != nil {
log.WithError(err).Error("Error initializing storage")
return nil, err
}
stowClient.container = con
return stowClient, nil
}
// putFile writes the file on the storage
func (client *StowClient) putFile(file multipart.File, fileSize int64) (string, error) {
// This is not the item ID (that's returned by Put)
// should we just use handler.Filename? what are the constraints here?
uploadName := uuid.NewV4().String()
// save the file to the storage backend
item, err := client.container.Put(uploadName, file, int64(fileSize), nil)
if err != nil {
log.WithError(err).Errorf("Error writing file: %s on storage", uploadName)
return "", ErrWritingFile
}
log.Debugf("Successfully wrote file:%s on storage", uploadName)
return item.ID(), nil
}
// copyFileToStream gets the file contents into a stream
func (client *StowClient) copyFileToStream(fileId string, w io.Writer) error {
item, err := client.container.Item(fileId)
if err != nil {
if err == stow.ErrNotFound {
return ErrNotFound
} else {
return ErrRetrievingItem
}
}
f, err := item.Open()
if err != nil {
return ErrOpeningItem
}
defer f.Close()
_, err = io.Copy(w, f)
if err != nil {
return ErrWritingFileIntoResponse
}
log.Debugf("successfully wrote file: %s into httpresponse", fileId)
return nil
}
// removeFileByID deletes the file from storage
func (client *StowClient) removeFileByID(itemID string) error {
return client.container.RemoveItem(itemID)
}
// filter defines an interface to filter out items from a set of items
type filter func(stow.Item, interface{}) bool
// This method returns all items in a container, filtering out items based on the filter function passed to it
func (client *StowClient) getItemIDsWithFilter(filterFunc filter, filterFuncParam interface{}) ([]string, error) {
cursor := stow.CursorStart
var items []stow.Item
var err error
archiveIDList := make([]string, 0)
for {
items, cursor, err = client.container.Items(stow.NoPrefix, cursor, PaginationSize)
if err != nil {
log.WithError(err).Error("Error getting items from container")
return nil, err
}
for _, item := range items {
isItemFilterable := filterFunc(item, filterFuncParam)
if isItemFilterable {
continue
}
archiveIDList = append(archiveIDList, item.ID())
}
if stow.IsCursorEnd(cursor) {
break
}
}
return archiveIDList, nil
}
// filterItemCreatedAMinuteAgo is one type of filter function that filters out items created less than a minute ago.
// More filter functions can be written if needed, as long as they are of type filter
func filterItemCreatedAMinuteAgo(item stow.Item, currentTime interface{}) bool {
itemLastModTime, _ := item.LastMod()
if currentTime.(time.Time).Sub(itemLastModTime) < 1*time.Minute {
log.Debugf("item: %s created less than a minute ago: %v", item.ID(), itemLastModTime)
return true
}
return false
}