Deprecated Lifecycle and Tiering UI (#3470)

Signed-off-by: Benjamin Perez <benjamin@bexsoft.net>
This commit is contained in:
Alex
2024-11-11 17:36:14 -06:00
committed by GitHub
parent 4e5dcf0fc3
commit 2ca484c691
107 changed files with 18 additions and 16906 deletions

View File

@@ -1,488 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"context"
"encoding/base64"
"strconv"
"github.com/dustin/go-humanize"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/api/operations"
"github.com/minio/console/api/operations/tiering"
tieringApi "github.com/minio/console/api/operations/tiering"
"github.com/minio/console/models"
"github.com/minio/madmin-go/v3"
)
func registerAdminTiersHandlers(api *operations.ConsoleAPI) {
// return a list of notification endpoints
api.TieringTiersListHandler = tieringApi.TiersListHandlerFunc(func(params tieringApi.TiersListParams, session *models.Principal) middleware.Responder {
tierList, err := getTiersResponse(session, params)
if err != nil {
return tieringApi.NewTiersListDefault(err.Code).WithPayload(err.APIError)
}
return tieringApi.NewTiersListOK().WithPayload(tierList)
})
api.TieringTiersListNamesHandler = tiering.TiersListNamesHandlerFunc(func(params tiering.TiersListNamesParams, session *models.Principal) middleware.Responder {
tierList, err := getTiersNameResponse(session, params)
if err != nil {
return tieringApi.NewTiersListDefault(err.Code).WithPayload(err.APIError)
}
return tieringApi.NewTiersListNamesOK().WithPayload(tierList)
})
// add a new tiers
api.TieringAddTierHandler = tieringApi.AddTierHandlerFunc(func(params tieringApi.AddTierParams, session *models.Principal) middleware.Responder {
err := getAddTierResponse(session, params)
if err != nil {
return tieringApi.NewAddTierDefault(err.Code).WithPayload(err.APIError)
}
return tieringApi.NewAddTierCreated()
})
// get a tier
api.TieringGetTierHandler = tieringApi.GetTierHandlerFunc(func(params tieringApi.GetTierParams, session *models.Principal) middleware.Responder {
notifEndpoints, err := getGetTierResponse(session, params)
if err != nil {
return tieringApi.NewGetTierDefault(err.Code).WithPayload(err.APIError)
}
return tieringApi.NewGetTierOK().WithPayload(notifEndpoints)
})
// edit credentials for a tier
api.TieringEditTierCredentialsHandler = tieringApi.EditTierCredentialsHandlerFunc(func(params tieringApi.EditTierCredentialsParams, session *models.Principal) middleware.Responder {
err := getEditTierCredentialsResponse(session, params)
if err != nil {
return tieringApi.NewEditTierCredentialsDefault(err.Code).WithPayload(err.APIError)
}
return tieringApi.NewEditTierCredentialsOK()
})
// remove an empty tier
api.TieringRemoveTierHandler = tieringApi.RemoveTierHandlerFunc(func(params tieringApi.RemoveTierParams, session *models.Principal) middleware.Responder {
err := getRemoveTierResponse(session, params)
if err != nil {
return tieringApi.NewRemoveTierDefault(err.Code).WithPayload(err.APIError)
}
return tieringApi.NewRemoveTierNoContent()
})
}
// getTiers returns a list of tiers with their stats
func getTiers(ctx context.Context, client MinioAdmin) (*models.TierListResponse, error) {
tiers, err := client.listTiers(ctx)
if err != nil {
return nil, err
}
tierStatsInfo, err := client.tierStats(ctx)
if err != nil {
return nil, err
}
tiersStatsMap := make(map[string]madmin.TierStats, len(tierStatsInfo))
for _, stat := range tierStatsInfo {
tiersStatsMap[stat.Name] = stat.Stats
}
var tiersList []*models.Tier
for _, tierData := range tiers {
// Default Tier Stats
tierStats := madmin.TierStats{
NumObjects: 0,
NumVersions: 0,
TotalSize: 0,
}
if stats, ok := tiersStatsMap[tierData.Name]; ok {
tierStats = stats
}
status := client.verifyTierStatus(ctx, tierData.Name) == nil
switch tierData.Type {
case madmin.S3:
tiersList = append(tiersList, &models.Tier{
Type: models.TierTypeS3,
S3: &models.TierS3{
Accesskey: tierData.S3.AccessKey,
Bucket: tierData.S3.Bucket,
Endpoint: tierData.S3.Endpoint,
Name: tierData.Name,
Prefix: tierData.S3.Prefix,
Region: tierData.S3.Region,
Secretkey: tierData.S3.SecretKey,
Storageclass: tierData.S3.StorageClass,
Usage: humanize.IBytes(tierStats.TotalSize),
Objects: strconv.Itoa(tierStats.NumObjects),
Versions: strconv.Itoa(tierStats.NumVersions),
},
Status: status,
})
case madmin.MinIO:
tiersList = append(tiersList, &models.Tier{
Type: models.TierTypeMinio,
Minio: &models.TierMinio{
Accesskey: tierData.MinIO.AccessKey,
Bucket: tierData.MinIO.Bucket,
Endpoint: tierData.MinIO.Endpoint,
Name: tierData.Name,
Prefix: tierData.MinIO.Prefix,
Region: tierData.MinIO.Region,
Secretkey: tierData.MinIO.SecretKey,
Usage: humanize.IBytes(tierStats.TotalSize),
Objects: strconv.Itoa(tierStats.NumObjects),
Versions: strconv.Itoa(tierStats.NumVersions),
},
Status: status,
})
case madmin.GCS:
tiersList = append(tiersList, &models.Tier{
Type: models.TierTypeGcs,
Gcs: &models.TierGcs{
Bucket: tierData.GCS.Bucket,
Creds: tierData.GCS.Creds,
Endpoint: tierData.GCS.Endpoint,
Name: tierData.Name,
Prefix: tierData.GCS.Prefix,
Region: tierData.GCS.Region,
Usage: humanize.IBytes(tierStats.TotalSize),
Objects: strconv.Itoa(tierStats.NumObjects),
Versions: strconv.Itoa(tierStats.NumVersions),
},
Status: status,
})
case madmin.Azure:
tiersList = append(tiersList, &models.Tier{
Type: models.TierTypeAzure,
Azure: &models.TierAzure{
Accountkey: tierData.Azure.AccountKey,
Accountname: tierData.Azure.AccountName,
Bucket: tierData.Azure.Bucket,
Endpoint: tierData.Azure.Endpoint,
Name: tierData.Name,
Prefix: tierData.Azure.Prefix,
Region: tierData.Azure.Region,
Usage: humanize.IBytes(tierStats.TotalSize),
Objects: strconv.Itoa(tierStats.NumObjects),
Versions: strconv.Itoa(tierStats.NumVersions),
},
Status: status,
})
case madmin.Unsupported:
tiersList = append(tiersList, &models.Tier{
Type: models.TierTypeUnsupported,
Status: status,
})
}
}
// build response
return &models.TierListResponse{
Items: tiersList,
}, nil
}
// getTiersResponse returns a response with a list of tiers
func getTiersResponse(session *models.Principal, params tieringApi.TiersListParams) (*models.TierListResponse, *CodedAPIError) {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mAdmin, err := NewMinioAdminClient(params.HTTPRequest.Context(), session)
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
adminClient := AdminClient{Client: mAdmin}
// serialize output
tiersResp, err := getTiers(ctx, adminClient)
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
return tiersResp, nil
}
// getTiersNameResponse returns a response with a list of tiers' names
func getTiersNameResponse(session *models.Principal, params tieringApi.TiersListNamesParams) (*models.TiersNameListResponse, *CodedAPIError) {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mAdmin, err := NewMinioAdminClient(params.HTTPRequest.Context(), session)
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
adminClient := AdminClient{Client: mAdmin}
// serialize output
tiersResp, err := getTiersName(ctx, adminClient)
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
return tiersResp, nil
}
// getTiersName fetches listTiers and returns a list of the tiers' names
func getTiersName(ctx context.Context, client MinioAdmin) (*models.TiersNameListResponse, error) {
tiers, err := client.listTiers(ctx)
if err != nil {
return nil, err
}
tiersNameList := make([]string, len(tiers))
for i, tierData := range tiers {
tiersNameList[i] = tierData.Name
}
return &models.TiersNameListResponse{
Items: tiersNameList,
}, nil
}
func addTier(ctx context.Context, client MinioAdmin, params *tieringApi.AddTierParams) error {
var cfg *madmin.TierConfig
var err error
switch params.Body.Type {
case models.TierTypeS3:
cfg, err = madmin.NewTierS3(
params.Body.S3.Name,
params.Body.S3.Accesskey,
params.Body.S3.Secretkey,
params.Body.S3.Bucket,
madmin.S3Region(params.Body.S3.Region),
madmin.S3Prefix(params.Body.S3.Prefix),
madmin.S3Endpoint(params.Body.S3.Endpoint),
madmin.S3StorageClass(params.Body.S3.Storageclass),
)
if err != nil {
return err
}
case models.TierTypeMinio:
cfg, err = madmin.NewTierMinIO(
params.Body.Minio.Name,
params.Body.Minio.Endpoint,
params.Body.Minio.Accesskey,
params.Body.Minio.Secretkey,
params.Body.Minio.Bucket,
madmin.MinIORegion(params.Body.Minio.Region),
madmin.MinIOPrefix(params.Body.Minio.Prefix),
)
if err != nil {
return err
}
case models.TierTypeGcs:
gcsOpts := []madmin.GCSOptions{}
prefix := params.Body.Gcs.Prefix
if prefix != "" {
gcsOpts = append(gcsOpts, madmin.GCSPrefix(prefix))
}
region := params.Body.Gcs.Region
if region != "" {
gcsOpts = append(gcsOpts, madmin.GCSRegion(region))
}
base64Text := make([]byte, base64.StdEncoding.EncodedLen(len(params.Body.Gcs.Creds)))
l, _ := base64.StdEncoding.Decode(base64Text, []byte(params.Body.Gcs.Creds))
cfg, err = madmin.NewTierGCS(
params.Body.Gcs.Name,
base64Text[:l],
params.Body.Gcs.Bucket,
gcsOpts...,
)
if err != nil {
return err
}
case models.TierTypeAzure:
cfg, err = madmin.NewTierAzure(
params.Body.Azure.Name,
params.Body.Azure.Accountname,
params.Body.Azure.Accountkey,
params.Body.Azure.Bucket,
madmin.AzurePrefix(params.Body.Azure.Prefix),
madmin.AzureEndpoint(params.Body.Azure.Endpoint),
madmin.AzureRegion(params.Body.Azure.Region),
)
if err != nil {
return err
}
case models.TierTypeUnsupported:
cfg = &madmin.TierConfig{
Type: madmin.Unsupported,
}
}
err = client.addTier(ctx, cfg)
if err != nil {
return err
}
return nil
}
// getAddTierResponse returns the response of admin tier
func getAddTierResponse(session *models.Principal, params tieringApi.AddTierParams) *CodedAPIError {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mAdmin, err := NewMinioAdminClient(params.HTTPRequest.Context(), session)
if err != nil {
return ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
adminClient := AdminClient{Client: mAdmin}
// serialize output
errTier := addTier(ctx, adminClient, &params)
if errTier != nil {
return ErrorWithContext(ctx, errTier)
}
return nil
}
func getTier(ctx context.Context, client MinioAdmin, params *tieringApi.GetTierParams) (*models.Tier, error) {
tiers, err := client.listTiers(ctx)
if err != nil {
return nil, err
}
for i := range tiers {
switch tiers[i].Type {
case madmin.S3:
if params.Type != models.TierTypeS3 || tiers[i].Name != params.Name {
continue
}
return &models.Tier{
Type: models.TierTypeS3,
S3: &models.TierS3{
Accesskey: tiers[i].S3.AccessKey,
Bucket: tiers[i].S3.Bucket,
Endpoint: tiers[i].S3.Endpoint,
Name: tiers[i].Name,
Prefix: tiers[i].S3.Prefix,
Region: tiers[i].S3.Region,
Secretkey: tiers[i].S3.SecretKey,
Storageclass: tiers[i].S3.StorageClass,
},
}, err
case madmin.GCS:
if params.Type != models.TierTypeGcs || tiers[i].Name != params.Name {
continue
}
return &models.Tier{
Type: models.TierTypeGcs,
Gcs: &models.TierGcs{
Bucket: tiers[i].GCS.Bucket,
Creds: tiers[i].GCS.Creds,
Endpoint: tiers[i].GCS.Endpoint,
Name: tiers[i].Name,
Prefix: tiers[i].GCS.Prefix,
Region: tiers[i].GCS.Region,
},
}, nil
case madmin.Azure:
if params.Type != models.TierTypeAzure || tiers[i].Name != params.Name {
continue
}
return &models.Tier{
Type: models.TierTypeAzure,
Azure: &models.TierAzure{
Accountkey: tiers[i].Azure.AccountKey,
Accountname: tiers[i].Azure.AccountName,
Bucket: tiers[i].Azure.Bucket,
Endpoint: tiers[i].Azure.Endpoint,
Name: tiers[i].Name,
Prefix: tiers[i].Azure.Prefix,
Region: tiers[i].Azure.Region,
},
}, nil
}
}
// build response
return nil, ErrNotFound
}
// getGetTierResponse returns a tier
func getGetTierResponse(session *models.Principal, params tieringApi.GetTierParams) (*models.Tier, *CodedAPIError) {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mAdmin, err := NewMinioAdminClient(params.HTTPRequest.Context(), session)
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
adminClient := AdminClient{Client: mAdmin}
// serialize output
addTierResp, err := getTier(ctx, adminClient, &params)
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
return addTierResp, nil
}
func editTierCredentials(ctx context.Context, client MinioAdmin, params *tieringApi.EditTierCredentialsParams) error {
base64Text := make([]byte, base64.StdEncoding.EncodedLen(len(params.Body.Creds)))
l, err := base64.StdEncoding.Decode(base64Text, []byte(params.Body.Creds))
if err != nil {
return err
}
creds := madmin.TierCreds{
AccessKey: params.Body.AccessKey,
SecretKey: params.Body.SecretKey,
CredsJSON: base64Text[:l],
}
return client.editTierCreds(ctx, params.Name, creds)
}
// getEditTierCredentialsResponse returns the result of editing credentials for a tier
func getEditTierCredentialsResponse(session *models.Principal, params tieringApi.EditTierCredentialsParams) *CodedAPIError {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mAdmin, err := NewMinioAdminClient(params.HTTPRequest.Context(), session)
if err != nil {
return ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
adminClient := AdminClient{Client: mAdmin}
// serialize output
err = editTierCredentials(ctx, adminClient, &params)
if err != nil {
return ErrorWithContext(ctx, err)
}
return nil
}
func removeTier(ctx context.Context, client MinioAdmin, params *tieringApi.RemoveTierParams) error {
return client.removeTier(ctx, params.Name)
}
func getRemoveTierResponse(session *models.Principal, params tieringApi.RemoveTierParams) *CodedAPIError {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mAdmin, err := NewMinioAdminClient(params.HTTPRequest.Context(), session)
if err != nil {
return ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
adminClient := AdminClient{Client: mAdmin}
// serialize output
err = removeTier(ctx, adminClient, &params)
if err != nil {
return ErrorWithContext(ctx, err)
}
return nil
}

View File

@@ -1,310 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"context"
"errors"
"fmt"
"testing"
tieringApi "github.com/minio/console/api/operations/tiering"
"github.com/minio/console/models"
"github.com/minio/madmin-go/v3"
"github.com/stretchr/testify/assert"
)
func TestGetTiers(t *testing.T) {
assert := assert.New(t)
// mock minIO client
adminClient := AdminClientMock{}
function := "getTiers()"
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Test-1 : getTiers() get list of tiers
// mock lifecycle response from MinIO
returnListMock := []*madmin.TierConfig{
{
Version: "V1",
Type: madmin.S3,
Name: "S3 Tier",
S3: &madmin.TierS3{
Endpoint: "https://s3tier.test.com/",
AccessKey: "Access Key",
SecretKey: "Secret Key",
Bucket: "buckets3",
Prefix: "pref1",
Region: "us-west-1",
StorageClass: "TT1",
},
},
{
Version: "V1",
Type: madmin.MinIO,
Name: "MinIO Tier",
MinIO: &madmin.TierMinIO{
Endpoint: "https://minio-endpoint.test.com/",
AccessKey: "access",
SecretKey: "secret",
Bucket: "somebucket",
Prefix: "p1",
Region: "us-east-2",
},
},
}
returnStatsMock := []madmin.TierInfo{
{
Name: "STANDARD",
Type: "internal",
Stats: madmin.TierStats{NumObjects: 2, NumVersions: 2, TotalSize: 228915},
},
{
Name: "MinIO Tier",
Type: "internal",
Stats: madmin.TierStats{NumObjects: 10, NumVersions: 3, TotalSize: 132788},
},
{
Name: "S3 Tier",
Type: "s3",
Stats: madmin.TierStats{NumObjects: 0, NumVersions: 0, TotalSize: 0},
},
}
expectedOutput := &models.TierListResponse{
Items: []*models.Tier{
{
Type: models.TierTypeS3,
S3: &models.TierS3{
Accesskey: "Access Key",
Secretkey: "Secret Key",
Bucket: "buckets3",
Endpoint: "https://s3tier.test.com/",
Name: "S3 Tier",
Prefix: "pref1",
Region: "us-west-1",
Storageclass: "TT1",
Usage: "0 B",
Objects: "0",
Versions: "0",
},
Status: false,
},
{
Type: models.TierTypeMinio,
Minio: &models.TierMinio{
Accesskey: "access",
Secretkey: "secret",
Bucket: "somebucket",
Endpoint: "https://minio-endpoint.test.com/",
Name: "MinIO Tier",
Prefix: "p1",
Region: "us-east-2",
Usage: "130 KiB",
Objects: "10",
Versions: "3",
},
Status: false,
},
},
}
minioListTiersMock = func(_ context.Context) ([]*madmin.TierConfig, error) {
return returnListMock, nil
}
minioTierStatsMock = func(_ context.Context) ([]madmin.TierInfo, error) {
return returnStatsMock, nil
}
minioVerifyTierStatusMock = func(_ context.Context, _ string) error {
return fmt.Errorf("someerror")
}
tiersList, err := getTiers(ctx, adminClient)
if err != nil {
t.Errorf("Failed on %s:, error occurred: %s", function, err.Error())
}
// verify length of tiers list is correct
assert.Equal(len(tiersList.Items), len(returnListMock), fmt.Sprintf("Failed on %s: length of lists is not the same", function))
assert.Equal(expectedOutput, tiersList)
// Test-2 : getTiers() list is empty
returnListMockT2 := []*madmin.TierConfig{}
minioListTiersMock = func(_ context.Context) ([]*madmin.TierConfig, error) {
return returnListMockT2, nil
}
tiersListT2, err := getTiers(ctx, adminClient)
if err != nil {
t.Errorf("Failed on %s:, error occurred: %s", function, err.Error())
}
if len(tiersListT2.Items) != 0 {
t.Errorf("Failed on %s:, returned list was not empty", function)
}
}
func TestGetTiersName(t *testing.T) {
assert := assert.New(t)
// mock minIO client
adminClient := AdminClientMock{}
function := "getTiersName()"
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Test-1 : getTiersName() get list tiers' names
// mock lifecycle response from MinIO
returnListMock := []*madmin.TierConfig{
{
Version: "V1",
Type: madmin.S3,
Name: "S3 Tier",
S3: &madmin.TierS3{
Endpoint: "https://s3tier.test.com/",
AccessKey: "Access Key",
SecretKey: "Secret Key",
Bucket: "buckets3",
Prefix: "pref1",
Region: "us-west-1",
StorageClass: "TT1",
},
},
{
Version: "V1",
Type: madmin.MinIO,
Name: "MinIO Tier",
MinIO: &madmin.TierMinIO{
Endpoint: "https://minio-endpoint.test.com/",
AccessKey: "access",
SecretKey: "secret",
Bucket: "somebucket",
Prefix: "p1",
Region: "us-east-2",
},
},
}
expectedOutput := &models.TiersNameListResponse{
Items: []string{"S3 Tier", "MinIO Tier"},
}
minioListTiersMock = func(_ context.Context) ([]*madmin.TierConfig, error) {
return returnListMock, nil
}
tiersList, err := getTiersName(ctx, adminClient)
if err != nil {
t.Errorf("Failed on %s:, error occurred: %s", function, err.Error())
}
// verify length of tiers list is correct
assert.Equal(len(tiersList.Items), len(returnListMock), fmt.Sprintf("Failed on %s: length of lists is not the same", function))
assert.Equal(expectedOutput, tiersList)
// Test-2 : getTiersName() list is empty
returnListMockT2 := []*madmin.TierConfig{}
minioListTiersMock = func(_ context.Context) ([]*madmin.TierConfig, error) {
return returnListMockT2, nil
}
emptyTierList, err := getTiersName(ctx, adminClient)
if err != nil {
t.Errorf("Failed on %s:, error occurred: %s", function, err.Error())
}
if len(emptyTierList.Items) != 0 {
t.Errorf("Failed on %s:, returned list was not empty", function)
}
}
func TestAddTier(t *testing.T) {
assert := assert.New(t)
// mock minIO client
adminClient := AdminClientMock{}
function := "addTier()"
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Test-1: addTier() add new Tier
minioAddTiersMock = func(_ context.Context, _ *madmin.TierConfig) error {
return nil
}
paramsToAdd := tieringApi.AddTierParams{
Body: &models.Tier{
Type: "S3",
S3: &models.TierS3{
Accesskey: "TestAK",
Bucket: "bucket1",
Endpoint: "https://test.com/",
Name: "TIERS3",
Prefix: "Pr1",
Region: "us-west-1",
Secretkey: "SecretK",
Storageclass: "STCLASS",
},
},
}
err := addTier(ctx, adminClient, &paramsToAdd)
assert.Equal(nil, err, fmt.Sprintf("Failed on %s: Error returned", function))
// Test-2: addTier() error adding Tier
minioAddTiersMock = func(_ context.Context, _ *madmin.TierConfig) error {
return errors.New("error setting new tier")
}
err2 := addTier(ctx, adminClient, &paramsToAdd)
assert.Equal(errors.New("error setting new tier"), err2, fmt.Sprintf("Failed on %s: Error returned", function))
}
func TestUpdateTierCreds(t *testing.T) {
assert := assert.New(t)
// mock minIO client
adminClient := AdminClientMock{}
function := "editTierCredentials()"
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Test-1: editTierCredentials() update Tier configuration
minioEditTiersMock = func(_ context.Context, _ string, _ madmin.TierCreds) error {
return nil
}
params := &tieringApi.EditTierCredentialsParams{
Name: "TESTTIER",
Body: &models.TierCredentialsRequest{
AccessKey: "New Key",
SecretKey: "Secret Key",
},
}
err := editTierCredentials(ctx, adminClient, params)
assert.Equal(nil, err, fmt.Sprintf("Failed on %s: Error returned", function))
// Test-2: editTierCredentials() update Tier configuration failure
minioEditTiersMock = func(_ context.Context, _ string, _ madmin.TierCreds) error {
return errors.New("error message")
}
errT2 := editTierCredentials(ctx, adminClient, params)
assert.Equal(errors.New("error message"), errT2, fmt.Sprintf("Failed on %s: Error returned", function))
}

View File

@@ -38,7 +38,6 @@ import (
"github.com/minio/mc/pkg/probe" "github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials" "github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio-go/v7/pkg/notification" "github.com/minio/minio-go/v7/pkg/notification"
"github.com/minio/minio-go/v7/pkg/tags" "github.com/minio/minio-go/v7/pkg/tags"
) )
@@ -74,8 +73,6 @@ type MinioClient interface {
setObjectLockConfig(ctx context.Context, bucketName string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) error setObjectLockConfig(ctx context.Context, bucketName string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) error
getBucketObjectLockConfig(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error) getBucketObjectLockConfig(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error)
getObjectLockConfig(ctx context.Context, bucketName string) (lock string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error) getObjectLockConfig(ctx context.Context, bucketName string) (lock string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error)
getLifecycleRules(ctx context.Context, bucketName string) (lifecycle *lifecycle.Configuration, err error)
setBucketLifecycle(ctx context.Context, bucketName string, config *lifecycle.Configuration) error
copyObject(ctx context.Context, dst minio.CopyDestOptions, src minio.CopySrcOptions) (minio.UploadInfo, error) copyObject(ctx context.Context, dst minio.CopyDestOptions, src minio.CopySrcOptions) (minio.UploadInfo, error)
GetBucketTagging(ctx context.Context, bucketName string) (*tags.Tags, error) GetBucketTagging(ctx context.Context, bucketName string) (*tags.Tags, error)
SetBucketTagging(ctx context.Context, bucketName string, tags *tags.Tags) error SetBucketTagging(ctx context.Context, bucketName string, tags *tags.Tags) error
@@ -209,14 +206,6 @@ func (c minioClient) getObjectLockConfig(ctx context.Context, bucketName string)
return c.client.GetObjectLockConfig(ctx, bucketName) return c.client.GetObjectLockConfig(ctx, bucketName)
} }
func (c minioClient) getLifecycleRules(ctx context.Context, bucketName string) (lifecycle *lifecycle.Configuration, err error) {
return c.client.GetBucketLifecycle(ctx, bucketName)
}
func (c minioClient) setBucketLifecycle(ctx context.Context, bucketName string, config *lifecycle.Configuration) error {
return c.client.SetBucketLifecycle(ctx, bucketName, config)
}
func (c minioClient) copyObject(ctx context.Context, dst minio.CopyDestOptions, src minio.CopySrcOptions) (minio.UploadInfo, error) { func (c minioClient) copyObject(ctx context.Context, dst minio.CopyDestOptions, src minio.CopySrcOptions) (minio.UploadInfo, error) {
return c.client.CopyObject(ctx, dst, src) return c.client.CopyObject(ctx, dst, src)
} }

View File

@@ -125,8 +125,6 @@ func configureAPI(api *operations.ConsoleAPI) http.Handler {
registerConfigHandlers(api) registerConfigHandlers(api)
// Register bucket events handlers // Register bucket events handlers
registerBucketEventsHandlers(api) registerBucketEventsHandlers(api)
// Register bucket lifecycle handlers
registerBucketsLifecycleHandlers(api)
// Register service handlers // Register service handlers
registerServiceHandlers(api) registerServiceHandlers(api)
// Register session handlers // Register session handlers
@@ -147,8 +145,6 @@ func configureAPI(api *operations.ConsoleAPI) http.Handler {
registerKMSHandlers(api) registerKMSHandlers(api)
// Register admin IDP handlers // Register admin IDP handlers
registerIDPHandlers(api) registerIDPHandlers(api)
// Register Account handlers
registerAdminTiersHandlers(api)
// Register Inspect Handler // Register Inspect Handler
registerInspectHandler(api) registerInspectHandler(api)
// Register nodes handlers // Register nodes handlers

File diff suppressed because it is too large Load Diff

View File

@@ -60,7 +60,6 @@ func TestError(t *testing.T) {
"ErrPolicyBodyNotInRequest": {code: 400, err: ErrPolicyBodyNotInRequest}, "ErrPolicyBodyNotInRequest": {code: 400, err: ErrPolicyBodyNotInRequest},
"ErrInvalidEncryptionAlgorithm": {code: 500, err: ErrInvalidEncryptionAlgorithm}, "ErrInvalidEncryptionAlgorithm": {code: 500, err: ErrInvalidEncryptionAlgorithm},
"ErrSSENotConfigured": {code: 404, err: ErrSSENotConfigured}, "ErrSSENotConfigured": {code: 404, err: ErrSSENotConfigured},
"ErrBucketLifeCycleNotConfigured": {code: 404, err: ErrBucketLifeCycleNotConfigured},
"ErrChangePassword": {code: 403, err: ErrChangePassword}, "ErrChangePassword": {code: 403, err: ErrChangePassword},
"ErrInvalidLicense": {code: 404, err: ErrInvalidLicense}, "ErrInvalidLicense": {code: 404, err: ErrInvalidLicense},
"ErrLicenseNotFound": {code: 404, err: ErrLicenseNotFound}, "ErrLicenseNotFound": {code: 404, err: ErrLicenseNotFound},

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// AddBucketLifecycleHandlerFunc turns a function with the right signature into a add bucket lifecycle handler
type AddBucketLifecycleHandlerFunc func(AddBucketLifecycleParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn AddBucketLifecycleHandlerFunc) Handle(params AddBucketLifecycleParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// AddBucketLifecycleHandler interface for that can handle valid add bucket lifecycle params
type AddBucketLifecycleHandler interface {
Handle(AddBucketLifecycleParams, *models.Principal) middleware.Responder
}
// NewAddBucketLifecycle creates a new http.Handler for the add bucket lifecycle operation
func NewAddBucketLifecycle(ctx *middleware.Context, handler AddBucketLifecycleHandler) *AddBucketLifecycle {
return &AddBucketLifecycle{Context: ctx, Handler: handler}
}
/*
AddBucketLifecycle swagger:route POST /buckets/{bucket_name}/lifecycle Bucket addBucketLifecycle
Add Bucket Lifecycle
*/
type AddBucketLifecycle struct {
Context *middleware.Context
Handler AddBucketLifecycleHandler
}
func (o *AddBucketLifecycle) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewAddBucketLifecycleParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,126 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"io"
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
"github.com/minio/console/models"
)
// NewAddBucketLifecycleParams creates a new AddBucketLifecycleParams object
//
// There are no default values defined in the spec.
func NewAddBucketLifecycleParams() AddBucketLifecycleParams {
return AddBucketLifecycleParams{}
}
// AddBucketLifecycleParams contains all the bound params for the add bucket lifecycle operation
// typically these are obtained from a http.Request
//
// swagger:parameters AddBucketLifecycle
type AddBucketLifecycleParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: body
*/
Body *models.AddBucketLifecycle
/*
Required: true
In: path
*/
BucketName string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewAddBucketLifecycleParams() beforehand.
func (o *AddBucketLifecycleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if runtime.HasBody(r) {
defer r.Body.Close()
var body models.AddBucketLifecycle
if err := route.Consumer.Consume(r.Body, &body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("body", "body", ""))
} else {
res = append(res, errors.NewParseError("body", "body", "", err))
}
} else {
// validate body object
if err := body.Validate(route.Formats); err != nil {
res = append(res, err)
}
ctx := validate.WithOperationRequest(r.Context())
if err := body.ContextValidate(ctx, route.Formats); err != nil {
res = append(res, err)
}
if len(res) == 0 {
o.Body = &body
}
}
} else {
res = append(res, errors.Required("body", "body", ""))
}
rBucketName, rhkBucketName, _ := route.Params.GetOK("bucket_name")
if err := o.bindBucketName(rBucketName, rhkBucketName, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindBucketName binds and validates parameter BucketName from path.
func (o *AddBucketLifecycleParams) bindBucketName(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.BucketName = raw
return nil
}

View File

@@ -1,115 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// AddBucketLifecycleCreatedCode is the HTTP code returned for type AddBucketLifecycleCreated
const AddBucketLifecycleCreatedCode int = 201
/*
AddBucketLifecycleCreated A successful response.
swagger:response addBucketLifecycleCreated
*/
type AddBucketLifecycleCreated struct {
}
// NewAddBucketLifecycleCreated creates AddBucketLifecycleCreated with default headers values
func NewAddBucketLifecycleCreated() *AddBucketLifecycleCreated {
return &AddBucketLifecycleCreated{}
}
// WriteResponse to the client
func (o *AddBucketLifecycleCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(201)
}
/*
AddBucketLifecycleDefault Generic error response.
swagger:response addBucketLifecycleDefault
*/
type AddBucketLifecycleDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewAddBucketLifecycleDefault creates AddBucketLifecycleDefault with default headers values
func NewAddBucketLifecycleDefault(code int) *AddBucketLifecycleDefault {
if code <= 0 {
code = 500
}
return &AddBucketLifecycleDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the add bucket lifecycle default response
func (o *AddBucketLifecycleDefault) WithStatusCode(code int) *AddBucketLifecycleDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the add bucket lifecycle default response
func (o *AddBucketLifecycleDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the add bucket lifecycle default response
func (o *AddBucketLifecycleDefault) WithPayload(payload *models.APIError) *AddBucketLifecycleDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the add bucket lifecycle default response
func (o *AddBucketLifecycleDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *AddBucketLifecycleDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,116 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
"strings"
)
// AddBucketLifecycleURL generates an URL for the add bucket lifecycle operation
type AddBucketLifecycleURL struct {
BucketName string
_basePath string
// avoid unkeyed usage
_ struct{}
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *AddBucketLifecycleURL) WithBasePath(bp string) *AddBucketLifecycleURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *AddBucketLifecycleURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *AddBucketLifecycleURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/buckets/{bucket_name}/lifecycle"
bucketName := o.BucketName
if bucketName != "" {
_path = strings.Replace(_path, "{bucket_name}", bucketName, -1)
} else {
return nil, errors.New("bucketName is required on AddBucketLifecycleURL")
}
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *AddBucketLifecycleURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *AddBucketLifecycleURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *AddBucketLifecycleURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on AddBucketLifecycleURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on AddBucketLifecycleURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *AddBucketLifecycleURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// AddMultiBucketLifecycleHandlerFunc turns a function with the right signature into a add multi bucket lifecycle handler
type AddMultiBucketLifecycleHandlerFunc func(AddMultiBucketLifecycleParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn AddMultiBucketLifecycleHandlerFunc) Handle(params AddMultiBucketLifecycleParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// AddMultiBucketLifecycleHandler interface for that can handle valid add multi bucket lifecycle params
type AddMultiBucketLifecycleHandler interface {
Handle(AddMultiBucketLifecycleParams, *models.Principal) middleware.Responder
}
// NewAddMultiBucketLifecycle creates a new http.Handler for the add multi bucket lifecycle operation
func NewAddMultiBucketLifecycle(ctx *middleware.Context, handler AddMultiBucketLifecycleHandler) *AddMultiBucketLifecycle {
return &AddMultiBucketLifecycle{Context: ctx, Handler: handler}
}
/*
AddMultiBucketLifecycle swagger:route POST /buckets/multi-lifecycle Bucket addMultiBucketLifecycle
Add Multi Bucket Lifecycle
*/
type AddMultiBucketLifecycle struct {
Context *middleware.Context
Handler AddMultiBucketLifecycleHandler
}
func (o *AddMultiBucketLifecycle) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewAddMultiBucketLifecycleParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,101 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"io"
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/validate"
"github.com/minio/console/models"
)
// NewAddMultiBucketLifecycleParams creates a new AddMultiBucketLifecycleParams object
//
// There are no default values defined in the spec.
func NewAddMultiBucketLifecycleParams() AddMultiBucketLifecycleParams {
return AddMultiBucketLifecycleParams{}
}
// AddMultiBucketLifecycleParams contains all the bound params for the add multi bucket lifecycle operation
// typically these are obtained from a http.Request
//
// swagger:parameters AddMultiBucketLifecycle
type AddMultiBucketLifecycleParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: body
*/
Body *models.AddMultiBucketLifecycle
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewAddMultiBucketLifecycleParams() beforehand.
func (o *AddMultiBucketLifecycleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if runtime.HasBody(r) {
defer r.Body.Close()
var body models.AddMultiBucketLifecycle
if err := route.Consumer.Consume(r.Body, &body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("body", "body", ""))
} else {
res = append(res, errors.NewParseError("body", "body", "", err))
}
} else {
// validate body object
if err := body.Validate(route.Formats); err != nil {
res = append(res, err)
}
ctx := validate.WithOperationRequest(r.Context())
if err := body.ContextValidate(ctx, route.Formats); err != nil {
res = append(res, err)
}
if len(res) == 0 {
o.Body = &body
}
}
} else {
res = append(res, errors.Required("body", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,135 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// AddMultiBucketLifecycleOKCode is the HTTP code returned for type AddMultiBucketLifecycleOK
const AddMultiBucketLifecycleOKCode int = 200
/*
AddMultiBucketLifecycleOK A successful response.
swagger:response addMultiBucketLifecycleOK
*/
type AddMultiBucketLifecycleOK struct {
/*
In: Body
*/
Payload *models.MultiLifecycleResult `json:"body,omitempty"`
}
// NewAddMultiBucketLifecycleOK creates AddMultiBucketLifecycleOK with default headers values
func NewAddMultiBucketLifecycleOK() *AddMultiBucketLifecycleOK {
return &AddMultiBucketLifecycleOK{}
}
// WithPayload adds the payload to the add multi bucket lifecycle o k response
func (o *AddMultiBucketLifecycleOK) WithPayload(payload *models.MultiLifecycleResult) *AddMultiBucketLifecycleOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the add multi bucket lifecycle o k response
func (o *AddMultiBucketLifecycleOK) SetPayload(payload *models.MultiLifecycleResult) {
o.Payload = payload
}
// WriteResponse to the client
func (o *AddMultiBucketLifecycleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
/*
AddMultiBucketLifecycleDefault Generic error response.
swagger:response addMultiBucketLifecycleDefault
*/
type AddMultiBucketLifecycleDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewAddMultiBucketLifecycleDefault creates AddMultiBucketLifecycleDefault with default headers values
func NewAddMultiBucketLifecycleDefault(code int) *AddMultiBucketLifecycleDefault {
if code <= 0 {
code = 500
}
return &AddMultiBucketLifecycleDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the add multi bucket lifecycle default response
func (o *AddMultiBucketLifecycleDefault) WithStatusCode(code int) *AddMultiBucketLifecycleDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the add multi bucket lifecycle default response
func (o *AddMultiBucketLifecycleDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the add multi bucket lifecycle default response
func (o *AddMultiBucketLifecycleDefault) WithPayload(payload *models.APIError) *AddMultiBucketLifecycleDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the add multi bucket lifecycle default response
func (o *AddMultiBucketLifecycleDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *AddMultiBucketLifecycleDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,104 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
)
// AddMultiBucketLifecycleURL generates an URL for the add multi bucket lifecycle operation
type AddMultiBucketLifecycleURL struct {
_basePath string
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *AddMultiBucketLifecycleURL) WithBasePath(bp string) *AddMultiBucketLifecycleURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *AddMultiBucketLifecycleURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *AddMultiBucketLifecycleURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/buckets/multi-lifecycle"
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *AddMultiBucketLifecycleURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *AddMultiBucketLifecycleURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *AddMultiBucketLifecycleURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on AddMultiBucketLifecycleURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on AddMultiBucketLifecycleURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *AddMultiBucketLifecycleURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// DeleteBucketLifecycleRuleHandlerFunc turns a function with the right signature into a delete bucket lifecycle rule handler
type DeleteBucketLifecycleRuleHandlerFunc func(DeleteBucketLifecycleRuleParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn DeleteBucketLifecycleRuleHandlerFunc) Handle(params DeleteBucketLifecycleRuleParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// DeleteBucketLifecycleRuleHandler interface for that can handle valid delete bucket lifecycle rule params
type DeleteBucketLifecycleRuleHandler interface {
Handle(DeleteBucketLifecycleRuleParams, *models.Principal) middleware.Responder
}
// NewDeleteBucketLifecycleRule creates a new http.Handler for the delete bucket lifecycle rule operation
func NewDeleteBucketLifecycleRule(ctx *middleware.Context, handler DeleteBucketLifecycleRuleHandler) *DeleteBucketLifecycleRule {
return &DeleteBucketLifecycleRule{Context: ctx, Handler: handler}
}
/*
DeleteBucketLifecycleRule swagger:route DELETE /buckets/{bucket_name}/lifecycle/{lifecycle_id} Bucket deleteBucketLifecycleRule
Delete Lifecycle rule
*/
type DeleteBucketLifecycleRule struct {
Context *middleware.Context
Handler DeleteBucketLifecycleRuleHandler
}
func (o *DeleteBucketLifecycleRule) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewDeleteBucketLifecycleRuleParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,112 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
)
// NewDeleteBucketLifecycleRuleParams creates a new DeleteBucketLifecycleRuleParams object
//
// There are no default values defined in the spec.
func NewDeleteBucketLifecycleRuleParams() DeleteBucketLifecycleRuleParams {
return DeleteBucketLifecycleRuleParams{}
}
// DeleteBucketLifecycleRuleParams contains all the bound params for the delete bucket lifecycle rule operation
// typically these are obtained from a http.Request
//
// swagger:parameters DeleteBucketLifecycleRule
type DeleteBucketLifecycleRuleParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: path
*/
BucketName string
/*
Required: true
In: path
*/
LifecycleID string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewDeleteBucketLifecycleRuleParams() beforehand.
func (o *DeleteBucketLifecycleRuleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
rBucketName, rhkBucketName, _ := route.Params.GetOK("bucket_name")
if err := o.bindBucketName(rBucketName, rhkBucketName, route.Formats); err != nil {
res = append(res, err)
}
rLifecycleID, rhkLifecycleID, _ := route.Params.GetOK("lifecycle_id")
if err := o.bindLifecycleID(rLifecycleID, rhkLifecycleID, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindBucketName binds and validates parameter BucketName from path.
func (o *DeleteBucketLifecycleRuleParams) bindBucketName(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.BucketName = raw
return nil
}
// bindLifecycleID binds and validates parameter LifecycleID from path.
func (o *DeleteBucketLifecycleRuleParams) bindLifecycleID(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.LifecycleID = raw
return nil
}

View File

@@ -1,115 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// DeleteBucketLifecycleRuleNoContentCode is the HTTP code returned for type DeleteBucketLifecycleRuleNoContent
const DeleteBucketLifecycleRuleNoContentCode int = 204
/*
DeleteBucketLifecycleRuleNoContent A successful response.
swagger:response deleteBucketLifecycleRuleNoContent
*/
type DeleteBucketLifecycleRuleNoContent struct {
}
// NewDeleteBucketLifecycleRuleNoContent creates DeleteBucketLifecycleRuleNoContent with default headers values
func NewDeleteBucketLifecycleRuleNoContent() *DeleteBucketLifecycleRuleNoContent {
return &DeleteBucketLifecycleRuleNoContent{}
}
// WriteResponse to the client
func (o *DeleteBucketLifecycleRuleNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(204)
}
/*
DeleteBucketLifecycleRuleDefault Generic error response.
swagger:response deleteBucketLifecycleRuleDefault
*/
type DeleteBucketLifecycleRuleDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewDeleteBucketLifecycleRuleDefault creates DeleteBucketLifecycleRuleDefault with default headers values
func NewDeleteBucketLifecycleRuleDefault(code int) *DeleteBucketLifecycleRuleDefault {
if code <= 0 {
code = 500
}
return &DeleteBucketLifecycleRuleDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the delete bucket lifecycle rule default response
func (o *DeleteBucketLifecycleRuleDefault) WithStatusCode(code int) *DeleteBucketLifecycleRuleDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the delete bucket lifecycle rule default response
func (o *DeleteBucketLifecycleRuleDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the delete bucket lifecycle rule default response
func (o *DeleteBucketLifecycleRuleDefault) WithPayload(payload *models.APIError) *DeleteBucketLifecycleRuleDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the delete bucket lifecycle rule default response
func (o *DeleteBucketLifecycleRuleDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *DeleteBucketLifecycleRuleDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,124 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
"strings"
)
// DeleteBucketLifecycleRuleURL generates an URL for the delete bucket lifecycle rule operation
type DeleteBucketLifecycleRuleURL struct {
BucketName string
LifecycleID string
_basePath string
// avoid unkeyed usage
_ struct{}
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *DeleteBucketLifecycleRuleURL) WithBasePath(bp string) *DeleteBucketLifecycleRuleURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *DeleteBucketLifecycleRuleURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *DeleteBucketLifecycleRuleURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/buckets/{bucket_name}/lifecycle/{lifecycle_id}"
bucketName := o.BucketName
if bucketName != "" {
_path = strings.Replace(_path, "{bucket_name}", bucketName, -1)
} else {
return nil, errors.New("bucketName is required on DeleteBucketLifecycleRuleURL")
}
lifecycleID := o.LifecycleID
if lifecycleID != "" {
_path = strings.Replace(_path, "{lifecycle_id}", lifecycleID, -1)
} else {
return nil, errors.New("lifecycleId is required on DeleteBucketLifecycleRuleURL")
}
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *DeleteBucketLifecycleRuleURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *DeleteBucketLifecycleRuleURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *DeleteBucketLifecycleRuleURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on DeleteBucketLifecycleRuleURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on DeleteBucketLifecycleRuleURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *DeleteBucketLifecycleRuleURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// GetBucketLifecycleHandlerFunc turns a function with the right signature into a get bucket lifecycle handler
type GetBucketLifecycleHandlerFunc func(GetBucketLifecycleParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn GetBucketLifecycleHandlerFunc) Handle(params GetBucketLifecycleParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// GetBucketLifecycleHandler interface for that can handle valid get bucket lifecycle params
type GetBucketLifecycleHandler interface {
Handle(GetBucketLifecycleParams, *models.Principal) middleware.Responder
}
// NewGetBucketLifecycle creates a new http.Handler for the get bucket lifecycle operation
func NewGetBucketLifecycle(ctx *middleware.Context, handler GetBucketLifecycleHandler) *GetBucketLifecycle {
return &GetBucketLifecycle{Context: ctx, Handler: handler}
}
/*
GetBucketLifecycle swagger:route GET /buckets/{bucket_name}/lifecycle Bucket getBucketLifecycle
Bucket Lifecycle
*/
type GetBucketLifecycle struct {
Context *middleware.Context
Handler GetBucketLifecycleHandler
}
func (o *GetBucketLifecycle) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewGetBucketLifecycleParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
)
// NewGetBucketLifecycleParams creates a new GetBucketLifecycleParams object
//
// There are no default values defined in the spec.
func NewGetBucketLifecycleParams() GetBucketLifecycleParams {
return GetBucketLifecycleParams{}
}
// GetBucketLifecycleParams contains all the bound params for the get bucket lifecycle operation
// typically these are obtained from a http.Request
//
// swagger:parameters GetBucketLifecycle
type GetBucketLifecycleParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: path
*/
BucketName string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewGetBucketLifecycleParams() beforehand.
func (o *GetBucketLifecycleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
rBucketName, rhkBucketName, _ := route.Params.GetOK("bucket_name")
if err := o.bindBucketName(rBucketName, rhkBucketName, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindBucketName binds and validates parameter BucketName from path.
func (o *GetBucketLifecycleParams) bindBucketName(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.BucketName = raw
return nil
}

View File

@@ -1,135 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// GetBucketLifecycleOKCode is the HTTP code returned for type GetBucketLifecycleOK
const GetBucketLifecycleOKCode int = 200
/*
GetBucketLifecycleOK A successful response.
swagger:response getBucketLifecycleOK
*/
type GetBucketLifecycleOK struct {
/*
In: Body
*/
Payload *models.BucketLifecycleResponse `json:"body,omitempty"`
}
// NewGetBucketLifecycleOK creates GetBucketLifecycleOK with default headers values
func NewGetBucketLifecycleOK() *GetBucketLifecycleOK {
return &GetBucketLifecycleOK{}
}
// WithPayload adds the payload to the get bucket lifecycle o k response
func (o *GetBucketLifecycleOK) WithPayload(payload *models.BucketLifecycleResponse) *GetBucketLifecycleOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the get bucket lifecycle o k response
func (o *GetBucketLifecycleOK) SetPayload(payload *models.BucketLifecycleResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *GetBucketLifecycleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
/*
GetBucketLifecycleDefault Generic error response.
swagger:response getBucketLifecycleDefault
*/
type GetBucketLifecycleDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewGetBucketLifecycleDefault creates GetBucketLifecycleDefault with default headers values
func NewGetBucketLifecycleDefault(code int) *GetBucketLifecycleDefault {
if code <= 0 {
code = 500
}
return &GetBucketLifecycleDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the get bucket lifecycle default response
func (o *GetBucketLifecycleDefault) WithStatusCode(code int) *GetBucketLifecycleDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the get bucket lifecycle default response
func (o *GetBucketLifecycleDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the get bucket lifecycle default response
func (o *GetBucketLifecycleDefault) WithPayload(payload *models.APIError) *GetBucketLifecycleDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the get bucket lifecycle default response
func (o *GetBucketLifecycleDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *GetBucketLifecycleDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,116 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
"strings"
)
// GetBucketLifecycleURL generates an URL for the get bucket lifecycle operation
type GetBucketLifecycleURL struct {
BucketName string
_basePath string
// avoid unkeyed usage
_ struct{}
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *GetBucketLifecycleURL) WithBasePath(bp string) *GetBucketLifecycleURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *GetBucketLifecycleURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *GetBucketLifecycleURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/buckets/{bucket_name}/lifecycle"
bucketName := o.BucketName
if bucketName != "" {
_path = strings.Replace(_path, "{bucket_name}", bucketName, -1)
} else {
return nil, errors.New("bucketName is required on GetBucketLifecycleURL")
}
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *GetBucketLifecycleURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *GetBucketLifecycleURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *GetBucketLifecycleURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on GetBucketLifecycleURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on GetBucketLifecycleURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *GetBucketLifecycleURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// UpdateBucketLifecycleHandlerFunc turns a function with the right signature into a update bucket lifecycle handler
type UpdateBucketLifecycleHandlerFunc func(UpdateBucketLifecycleParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn UpdateBucketLifecycleHandlerFunc) Handle(params UpdateBucketLifecycleParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// UpdateBucketLifecycleHandler interface for that can handle valid update bucket lifecycle params
type UpdateBucketLifecycleHandler interface {
Handle(UpdateBucketLifecycleParams, *models.Principal) middleware.Responder
}
// NewUpdateBucketLifecycle creates a new http.Handler for the update bucket lifecycle operation
func NewUpdateBucketLifecycle(ctx *middleware.Context, handler UpdateBucketLifecycleHandler) *UpdateBucketLifecycle {
return &UpdateBucketLifecycle{Context: ctx, Handler: handler}
}
/*
UpdateBucketLifecycle swagger:route PUT /buckets/{bucket_name}/lifecycle/{lifecycle_id} Bucket updateBucketLifecycle
Update Lifecycle rule
*/
type UpdateBucketLifecycle struct {
Context *middleware.Context
Handler UpdateBucketLifecycleHandler
}
func (o *UpdateBucketLifecycle) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewUpdateBucketLifecycleParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,150 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"io"
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
"github.com/minio/console/models"
)
// NewUpdateBucketLifecycleParams creates a new UpdateBucketLifecycleParams object
//
// There are no default values defined in the spec.
func NewUpdateBucketLifecycleParams() UpdateBucketLifecycleParams {
return UpdateBucketLifecycleParams{}
}
// UpdateBucketLifecycleParams contains all the bound params for the update bucket lifecycle operation
// typically these are obtained from a http.Request
//
// swagger:parameters UpdateBucketLifecycle
type UpdateBucketLifecycleParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: body
*/
Body *models.UpdateBucketLifecycle
/*
Required: true
In: path
*/
BucketName string
/*
Required: true
In: path
*/
LifecycleID string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewUpdateBucketLifecycleParams() beforehand.
func (o *UpdateBucketLifecycleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if runtime.HasBody(r) {
defer r.Body.Close()
var body models.UpdateBucketLifecycle
if err := route.Consumer.Consume(r.Body, &body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("body", "body", ""))
} else {
res = append(res, errors.NewParseError("body", "body", "", err))
}
} else {
// validate body object
if err := body.Validate(route.Formats); err != nil {
res = append(res, err)
}
ctx := validate.WithOperationRequest(r.Context())
if err := body.ContextValidate(ctx, route.Formats); err != nil {
res = append(res, err)
}
if len(res) == 0 {
o.Body = &body
}
}
} else {
res = append(res, errors.Required("body", "body", ""))
}
rBucketName, rhkBucketName, _ := route.Params.GetOK("bucket_name")
if err := o.bindBucketName(rBucketName, rhkBucketName, route.Formats); err != nil {
res = append(res, err)
}
rLifecycleID, rhkLifecycleID, _ := route.Params.GetOK("lifecycle_id")
if err := o.bindLifecycleID(rLifecycleID, rhkLifecycleID, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindBucketName binds and validates parameter BucketName from path.
func (o *UpdateBucketLifecycleParams) bindBucketName(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.BucketName = raw
return nil
}
// bindLifecycleID binds and validates parameter LifecycleID from path.
func (o *UpdateBucketLifecycleParams) bindLifecycleID(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.LifecycleID = raw
return nil
}

View File

@@ -1,115 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// UpdateBucketLifecycleOKCode is the HTTP code returned for type UpdateBucketLifecycleOK
const UpdateBucketLifecycleOKCode int = 200
/*
UpdateBucketLifecycleOK A successful response.
swagger:response updateBucketLifecycleOK
*/
type UpdateBucketLifecycleOK struct {
}
// NewUpdateBucketLifecycleOK creates UpdateBucketLifecycleOK with default headers values
func NewUpdateBucketLifecycleOK() *UpdateBucketLifecycleOK {
return &UpdateBucketLifecycleOK{}
}
// WriteResponse to the client
func (o *UpdateBucketLifecycleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(200)
}
/*
UpdateBucketLifecycleDefault Generic error response.
swagger:response updateBucketLifecycleDefault
*/
type UpdateBucketLifecycleDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewUpdateBucketLifecycleDefault creates UpdateBucketLifecycleDefault with default headers values
func NewUpdateBucketLifecycleDefault(code int) *UpdateBucketLifecycleDefault {
if code <= 0 {
code = 500
}
return &UpdateBucketLifecycleDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the update bucket lifecycle default response
func (o *UpdateBucketLifecycleDefault) WithStatusCode(code int) *UpdateBucketLifecycleDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the update bucket lifecycle default response
func (o *UpdateBucketLifecycleDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the update bucket lifecycle default response
func (o *UpdateBucketLifecycleDefault) WithPayload(payload *models.APIError) *UpdateBucketLifecycleDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the update bucket lifecycle default response
func (o *UpdateBucketLifecycleDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *UpdateBucketLifecycleDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,124 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package bucket
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
"strings"
)
// UpdateBucketLifecycleURL generates an URL for the update bucket lifecycle operation
type UpdateBucketLifecycleURL struct {
BucketName string
LifecycleID string
_basePath string
// avoid unkeyed usage
_ struct{}
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *UpdateBucketLifecycleURL) WithBasePath(bp string) *UpdateBucketLifecycleURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *UpdateBucketLifecycleURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *UpdateBucketLifecycleURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/buckets/{bucket_name}/lifecycle/{lifecycle_id}"
bucketName := o.BucketName
if bucketName != "" {
_path = strings.Replace(_path, "{bucket_name}", bucketName, -1)
} else {
return nil, errors.New("bucketName is required on UpdateBucketLifecycleURL")
}
lifecycleID := o.LifecycleID
if lifecycleID != "" {
_path = strings.Replace(_path, "{lifecycle_id}", lifecycleID, -1)
} else {
return nil, errors.New("lifecycleId is required on UpdateBucketLifecycleURL")
}
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *UpdateBucketLifecycleURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *UpdateBucketLifecycleURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *UpdateBucketLifecycleURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on UpdateBucketLifecycleURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on UpdateBucketLifecycleURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *UpdateBucketLifecycleURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -52,7 +52,6 @@ import (
"github.com/minio/console/api/operations/service" "github.com/minio/console/api/operations/service"
"github.com/minio/console/api/operations/service_account" "github.com/minio/console/api/operations/service_account"
"github.com/minio/console/api/operations/system" "github.com/minio/console/api/operations/system"
"github.com/minio/console/api/operations/tiering"
"github.com/minio/console/api/operations/user" "github.com/minio/console/api/operations/user"
"github.com/minio/console/models" "github.com/minio/console/models"
) )
@@ -84,15 +83,9 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI {
AccountAccountChangePasswordHandler: account.AccountChangePasswordHandlerFunc(func(params account.AccountChangePasswordParams, principal *models.Principal) middleware.Responder { AccountAccountChangePasswordHandler: account.AccountChangePasswordHandlerFunc(func(params account.AccountChangePasswordParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation account.AccountChangePassword has not yet been implemented") return middleware.NotImplemented("operation account.AccountChangePassword has not yet been implemented")
}), }),
BucketAddBucketLifecycleHandler: bucket.AddBucketLifecycleHandlerFunc(func(params bucket.AddBucketLifecycleParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.AddBucketLifecycle has not yet been implemented")
}),
GroupAddGroupHandler: group.AddGroupHandlerFunc(func(params group.AddGroupParams, principal *models.Principal) middleware.Responder { GroupAddGroupHandler: group.AddGroupHandlerFunc(func(params group.AddGroupParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation group.AddGroup has not yet been implemented") return middleware.NotImplemented("operation group.AddGroup has not yet been implemented")
}), }),
BucketAddMultiBucketLifecycleHandler: bucket.AddMultiBucketLifecycleHandlerFunc(func(params bucket.AddMultiBucketLifecycleParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.AddMultiBucketLifecycle has not yet been implemented")
}),
ConfigurationAddNotificationEndpointHandler: configuration.AddNotificationEndpointHandlerFunc(func(params configuration.AddNotificationEndpointParams, principal *models.Principal) middleware.Responder { ConfigurationAddNotificationEndpointHandler: configuration.AddNotificationEndpointHandlerFunc(func(params configuration.AddNotificationEndpointParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation configuration.AddNotificationEndpoint has not yet been implemented") return middleware.NotImplemented("operation configuration.AddNotificationEndpoint has not yet been implemented")
}), }),
@@ -102,9 +95,6 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI {
BucketAddRemoteBucketHandler: bucket.AddRemoteBucketHandlerFunc(func(params bucket.AddRemoteBucketParams, principal *models.Principal) middleware.Responder { BucketAddRemoteBucketHandler: bucket.AddRemoteBucketHandlerFunc(func(params bucket.AddRemoteBucketParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.AddRemoteBucket has not yet been implemented") return middleware.NotImplemented("operation bucket.AddRemoteBucket has not yet been implemented")
}), }),
TieringAddTierHandler: tiering.AddTierHandlerFunc(func(params tiering.AddTierParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation tiering.AddTier has not yet been implemented")
}),
UserAddUserHandler: user.AddUserHandlerFunc(func(params user.AddUserParams, principal *models.Principal) middleware.Responder { UserAddUserHandler: user.AddUserHandlerFunc(func(params user.AddUserParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation user.AddUser has not yet been implemented") return middleware.NotImplemented("operation user.AddUser has not yet been implemented")
}), }),
@@ -165,9 +155,6 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI {
BucketDeleteBucketEventHandler: bucket.DeleteBucketEventHandlerFunc(func(params bucket.DeleteBucketEventParams, principal *models.Principal) middleware.Responder { BucketDeleteBucketEventHandler: bucket.DeleteBucketEventHandlerFunc(func(params bucket.DeleteBucketEventParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.DeleteBucketEvent has not yet been implemented") return middleware.NotImplemented("operation bucket.DeleteBucketEvent has not yet been implemented")
}), }),
BucketDeleteBucketLifecycleRuleHandler: bucket.DeleteBucketLifecycleRuleHandlerFunc(func(params bucket.DeleteBucketLifecycleRuleParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.DeleteBucketLifecycleRule has not yet been implemented")
}),
BucketDeleteBucketReplicationRuleHandler: bucket.DeleteBucketReplicationRuleHandlerFunc(func(params bucket.DeleteBucketReplicationRuleParams, principal *models.Principal) middleware.Responder { BucketDeleteBucketReplicationRuleHandler: bucket.DeleteBucketReplicationRuleHandlerFunc(func(params bucket.DeleteBucketReplicationRuleParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.DeleteBucketReplicationRule has not yet been implemented") return middleware.NotImplemented("operation bucket.DeleteBucketReplicationRule has not yet been implemented")
}), }),
@@ -207,9 +194,6 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI {
PublicDownloadSharedObjectHandler: public.DownloadSharedObjectHandlerFunc(func(params public.DownloadSharedObjectParams) middleware.Responder { PublicDownloadSharedObjectHandler: public.DownloadSharedObjectHandlerFunc(func(params public.DownloadSharedObjectParams) middleware.Responder {
return middleware.NotImplemented("operation public.DownloadSharedObject has not yet been implemented") return middleware.NotImplemented("operation public.DownloadSharedObject has not yet been implemented")
}), }),
TieringEditTierCredentialsHandler: tiering.EditTierCredentialsHandlerFunc(func(params tiering.EditTierCredentialsParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation tiering.EditTierCredentials has not yet been implemented")
}),
BucketEnableBucketEncryptionHandler: bucket.EnableBucketEncryptionHandlerFunc(func(params bucket.EnableBucketEncryptionParams, principal *models.Principal) middleware.Responder { BucketEnableBucketEncryptionHandler: bucket.EnableBucketEncryptionHandlerFunc(func(params bucket.EnableBucketEncryptionParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.EnableBucketEncryption has not yet been implemented") return middleware.NotImplemented("operation bucket.EnableBucketEncryption has not yet been implemented")
}), }),
@@ -219,9 +203,6 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI {
BucketGetBucketEncryptionInfoHandler: bucket.GetBucketEncryptionInfoHandlerFunc(func(params bucket.GetBucketEncryptionInfoParams, principal *models.Principal) middleware.Responder { BucketGetBucketEncryptionInfoHandler: bucket.GetBucketEncryptionInfoHandlerFunc(func(params bucket.GetBucketEncryptionInfoParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.GetBucketEncryptionInfo has not yet been implemented") return middleware.NotImplemented("operation bucket.GetBucketEncryptionInfo has not yet been implemented")
}), }),
BucketGetBucketLifecycleHandler: bucket.GetBucketLifecycleHandlerFunc(func(params bucket.GetBucketLifecycleParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.GetBucketLifecycle has not yet been implemented")
}),
BucketGetBucketObjectLockingStatusHandler: bucket.GetBucketObjectLockingStatusHandlerFunc(func(params bucket.GetBucketObjectLockingStatusParams, principal *models.Principal) middleware.Responder { BucketGetBucketObjectLockingStatusHandler: bucket.GetBucketObjectLockingStatusHandlerFunc(func(params bucket.GetBucketObjectLockingStatusParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.GetBucketObjectLockingStatus has not yet been implemented") return middleware.NotImplemented("operation bucket.GetBucketObjectLockingStatus has not yet been implemented")
}), }),
@@ -261,9 +242,6 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI {
ServiceAccountGetServiceAccountHandler: service_account.GetServiceAccountHandlerFunc(func(params service_account.GetServiceAccountParams, principal *models.Principal) middleware.Responder { ServiceAccountGetServiceAccountHandler: service_account.GetServiceAccountHandlerFunc(func(params service_account.GetServiceAccountParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation service_account.GetServiceAccount has not yet been implemented") return middleware.NotImplemented("operation service_account.GetServiceAccount has not yet been implemented")
}), }),
TieringGetTierHandler: tiering.GetTierHandlerFunc(func(params tiering.GetTierParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation tiering.GetTier has not yet been implemented")
}),
UserGetUserInfoHandler: user.GetUserInfoHandlerFunc(func(params user.GetUserInfoParams, principal *models.Principal) middleware.Responder { UserGetUserInfoHandler: user.GetUserInfoHandlerFunc(func(params user.GetUserInfoParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation user.GetUserInfo has not yet been implemented") return middleware.NotImplemented("operation user.GetUserInfo has not yet been implemented")
}), }),
@@ -408,9 +386,6 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI {
PolicyRemovePolicyHandler: policy.RemovePolicyHandlerFunc(func(params policy.RemovePolicyParams, principal *models.Principal) middleware.Responder { PolicyRemovePolicyHandler: policy.RemovePolicyHandlerFunc(func(params policy.RemovePolicyParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation policy.RemovePolicy has not yet been implemented") return middleware.NotImplemented("operation policy.RemovePolicy has not yet been implemented")
}), }),
TieringRemoveTierHandler: tiering.RemoveTierHandlerFunc(func(params tiering.RemoveTierParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation tiering.RemoveTier has not yet been implemented")
}),
UserRemoveUserHandler: user.RemoveUserHandlerFunc(func(params user.RemoveUserParams, principal *models.Principal) middleware.Responder { UserRemoveUserHandler: user.RemoveUserHandlerFunc(func(params user.RemoveUserParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation user.RemoveUser has not yet been implemented") return middleware.NotImplemented("operation user.RemoveUser has not yet been implemented")
}), }),
@@ -450,15 +425,6 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI {
ObjectShareObjectHandler: object.ShareObjectHandlerFunc(func(params object.ShareObjectParams, principal *models.Principal) middleware.Responder { ObjectShareObjectHandler: object.ShareObjectHandlerFunc(func(params object.ShareObjectParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation object.ShareObject has not yet been implemented") return middleware.NotImplemented("operation object.ShareObject has not yet been implemented")
}), }),
TieringTiersListHandler: tiering.TiersListHandlerFunc(func(params tiering.TiersListParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation tiering.TiersList has not yet been implemented")
}),
TieringTiersListNamesHandler: tiering.TiersListNamesHandlerFunc(func(params tiering.TiersListNamesParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation tiering.TiersListNames has not yet been implemented")
}),
BucketUpdateBucketLifecycleHandler: bucket.UpdateBucketLifecycleHandlerFunc(func(params bucket.UpdateBucketLifecycleParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation bucket.UpdateBucketLifecycle has not yet been implemented")
}),
IdpUpdateConfigurationHandler: idp.UpdateConfigurationHandlerFunc(func(params idp.UpdateConfigurationParams, principal *models.Principal) middleware.Responder { IdpUpdateConfigurationHandler: idp.UpdateConfigurationHandlerFunc(func(params idp.UpdateConfigurationParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation idp.UpdateConfiguration has not yet been implemented") return middleware.NotImplemented("operation idp.UpdateConfiguration has not yet been implemented")
}), }),
@@ -542,20 +508,14 @@ type ConsoleAPI struct {
// AccountAccountChangePasswordHandler sets the operation handler for the account change password operation // AccountAccountChangePasswordHandler sets the operation handler for the account change password operation
AccountAccountChangePasswordHandler account.AccountChangePasswordHandler AccountAccountChangePasswordHandler account.AccountChangePasswordHandler
// BucketAddBucketLifecycleHandler sets the operation handler for the add bucket lifecycle operation
BucketAddBucketLifecycleHandler bucket.AddBucketLifecycleHandler
// GroupAddGroupHandler sets the operation handler for the add group operation // GroupAddGroupHandler sets the operation handler for the add group operation
GroupAddGroupHandler group.AddGroupHandler GroupAddGroupHandler group.AddGroupHandler
// BucketAddMultiBucketLifecycleHandler sets the operation handler for the add multi bucket lifecycle operation
BucketAddMultiBucketLifecycleHandler bucket.AddMultiBucketLifecycleHandler
// ConfigurationAddNotificationEndpointHandler sets the operation handler for the add notification endpoint operation // ConfigurationAddNotificationEndpointHandler sets the operation handler for the add notification endpoint operation
ConfigurationAddNotificationEndpointHandler configuration.AddNotificationEndpointHandler ConfigurationAddNotificationEndpointHandler configuration.AddNotificationEndpointHandler
// PolicyAddPolicyHandler sets the operation handler for the add policy operation // PolicyAddPolicyHandler sets the operation handler for the add policy operation
PolicyAddPolicyHandler policy.AddPolicyHandler PolicyAddPolicyHandler policy.AddPolicyHandler
// BucketAddRemoteBucketHandler sets the operation handler for the add remote bucket operation // BucketAddRemoteBucketHandler sets the operation handler for the add remote bucket operation
BucketAddRemoteBucketHandler bucket.AddRemoteBucketHandler BucketAddRemoteBucketHandler bucket.AddRemoteBucketHandler
// TieringAddTierHandler sets the operation handler for the add tier operation
TieringAddTierHandler tiering.AddTierHandler
// UserAddUserHandler sets the operation handler for the add user operation // UserAddUserHandler sets the operation handler for the add user operation
UserAddUserHandler user.AddUserHandler UserAddUserHandler user.AddUserHandler
// SystemAdminInfoHandler sets the operation handler for the admin info operation // SystemAdminInfoHandler sets the operation handler for the admin info operation
@@ -596,8 +556,6 @@ type ConsoleAPI struct {
BucketDeleteBucketHandler bucket.DeleteBucketHandler BucketDeleteBucketHandler bucket.DeleteBucketHandler
// BucketDeleteBucketEventHandler sets the operation handler for the delete bucket event operation // BucketDeleteBucketEventHandler sets the operation handler for the delete bucket event operation
BucketDeleteBucketEventHandler bucket.DeleteBucketEventHandler BucketDeleteBucketEventHandler bucket.DeleteBucketEventHandler
// BucketDeleteBucketLifecycleRuleHandler sets the operation handler for the delete bucket lifecycle rule operation
BucketDeleteBucketLifecycleRuleHandler bucket.DeleteBucketLifecycleRuleHandler
// BucketDeleteBucketReplicationRuleHandler sets the operation handler for the delete bucket replication rule operation // BucketDeleteBucketReplicationRuleHandler sets the operation handler for the delete bucket replication rule operation
BucketDeleteBucketReplicationRuleHandler bucket.DeleteBucketReplicationRuleHandler BucketDeleteBucketReplicationRuleHandler bucket.DeleteBucketReplicationRuleHandler
// IdpDeleteConfigurationHandler sets the operation handler for the delete configuration operation // IdpDeleteConfigurationHandler sets the operation handler for the delete configuration operation
@@ -624,16 +582,12 @@ type ConsoleAPI struct {
ObjectDownloadMultipleObjectsHandler object.DownloadMultipleObjectsHandler ObjectDownloadMultipleObjectsHandler object.DownloadMultipleObjectsHandler
// PublicDownloadSharedObjectHandler sets the operation handler for the download shared object operation // PublicDownloadSharedObjectHandler sets the operation handler for the download shared object operation
PublicDownloadSharedObjectHandler public.DownloadSharedObjectHandler PublicDownloadSharedObjectHandler public.DownloadSharedObjectHandler
// TieringEditTierCredentialsHandler sets the operation handler for the edit tier credentials operation
TieringEditTierCredentialsHandler tiering.EditTierCredentialsHandler
// BucketEnableBucketEncryptionHandler sets the operation handler for the enable bucket encryption operation // BucketEnableBucketEncryptionHandler sets the operation handler for the enable bucket encryption operation
BucketEnableBucketEncryptionHandler bucket.EnableBucketEncryptionHandler BucketEnableBucketEncryptionHandler bucket.EnableBucketEncryptionHandler
// ConfigurationExportConfigHandler sets the operation handler for the export config operation // ConfigurationExportConfigHandler sets the operation handler for the export config operation
ConfigurationExportConfigHandler configuration.ExportConfigHandler ConfigurationExportConfigHandler configuration.ExportConfigHandler
// BucketGetBucketEncryptionInfoHandler sets the operation handler for the get bucket encryption info operation // BucketGetBucketEncryptionInfoHandler sets the operation handler for the get bucket encryption info operation
BucketGetBucketEncryptionInfoHandler bucket.GetBucketEncryptionInfoHandler BucketGetBucketEncryptionInfoHandler bucket.GetBucketEncryptionInfoHandler
// BucketGetBucketLifecycleHandler sets the operation handler for the get bucket lifecycle operation
BucketGetBucketLifecycleHandler bucket.GetBucketLifecycleHandler
// BucketGetBucketObjectLockingStatusHandler sets the operation handler for the get bucket object locking status operation // BucketGetBucketObjectLockingStatusHandler sets the operation handler for the get bucket object locking status operation
BucketGetBucketObjectLockingStatusHandler bucket.GetBucketObjectLockingStatusHandler BucketGetBucketObjectLockingStatusHandler bucket.GetBucketObjectLockingStatusHandler
// BucketGetBucketQuotaHandler sets the operation handler for the get bucket quota operation // BucketGetBucketQuotaHandler sets the operation handler for the get bucket quota operation
@@ -660,8 +614,6 @@ type ConsoleAPI struct {
PolicyGetSAUserPolicyHandler policy.GetSAUserPolicyHandler PolicyGetSAUserPolicyHandler policy.GetSAUserPolicyHandler
// ServiceAccountGetServiceAccountHandler sets the operation handler for the get service account operation // ServiceAccountGetServiceAccountHandler sets the operation handler for the get service account operation
ServiceAccountGetServiceAccountHandler service_account.GetServiceAccountHandler ServiceAccountGetServiceAccountHandler service_account.GetServiceAccountHandler
// TieringGetTierHandler sets the operation handler for the get tier operation
TieringGetTierHandler tiering.GetTierHandler
// UserGetUserInfoHandler sets the operation handler for the get user info operation // UserGetUserInfoHandler sets the operation handler for the get user info operation
UserGetUserInfoHandler user.GetUserInfoHandler UserGetUserInfoHandler user.GetUserInfoHandler
// PolicyGetUserPolicyHandler sets the operation handler for the get user policy operation // PolicyGetUserPolicyHandler sets the operation handler for the get user policy operation
@@ -758,8 +710,6 @@ type ConsoleAPI struct {
GroupRemoveGroupHandler group.RemoveGroupHandler GroupRemoveGroupHandler group.RemoveGroupHandler
// PolicyRemovePolicyHandler sets the operation handler for the remove policy operation // PolicyRemovePolicyHandler sets the operation handler for the remove policy operation
PolicyRemovePolicyHandler policy.RemovePolicyHandler PolicyRemovePolicyHandler policy.RemovePolicyHandler
// TieringRemoveTierHandler sets the operation handler for the remove tier operation
TieringRemoveTierHandler tiering.RemoveTierHandler
// UserRemoveUserHandler sets the operation handler for the remove user operation // UserRemoveUserHandler sets the operation handler for the remove user operation
UserRemoveUserHandler user.RemoveUserHandler UserRemoveUserHandler user.RemoveUserHandler
// ConfigurationResetConfigHandler sets the operation handler for the reset config operation // ConfigurationResetConfigHandler sets the operation handler for the reset config operation
@@ -786,12 +736,6 @@ type ConsoleAPI struct {
PolicySetPolicyMultipleHandler policy.SetPolicyMultipleHandler PolicySetPolicyMultipleHandler policy.SetPolicyMultipleHandler
// ObjectShareObjectHandler sets the operation handler for the share object operation // ObjectShareObjectHandler sets the operation handler for the share object operation
ObjectShareObjectHandler object.ShareObjectHandler ObjectShareObjectHandler object.ShareObjectHandler
// TieringTiersListHandler sets the operation handler for the tiers list operation
TieringTiersListHandler tiering.TiersListHandler
// TieringTiersListNamesHandler sets the operation handler for the tiers list names operation
TieringTiersListNamesHandler tiering.TiersListNamesHandler
// BucketUpdateBucketLifecycleHandler sets the operation handler for the update bucket lifecycle operation
BucketUpdateBucketLifecycleHandler bucket.UpdateBucketLifecycleHandler
// IdpUpdateConfigurationHandler sets the operation handler for the update configuration operation // IdpUpdateConfigurationHandler sets the operation handler for the update configuration operation
IdpUpdateConfigurationHandler idp.UpdateConfigurationHandler IdpUpdateConfigurationHandler idp.UpdateConfigurationHandler
// GroupUpdateGroupHandler sets the operation handler for the update group operation // GroupUpdateGroupHandler sets the operation handler for the update group operation
@@ -897,15 +841,9 @@ func (o *ConsoleAPI) Validate() error {
if o.AccountAccountChangePasswordHandler == nil { if o.AccountAccountChangePasswordHandler == nil {
unregistered = append(unregistered, "account.AccountChangePasswordHandler") unregistered = append(unregistered, "account.AccountChangePasswordHandler")
} }
if o.BucketAddBucketLifecycleHandler == nil {
unregistered = append(unregistered, "bucket.AddBucketLifecycleHandler")
}
if o.GroupAddGroupHandler == nil { if o.GroupAddGroupHandler == nil {
unregistered = append(unregistered, "group.AddGroupHandler") unregistered = append(unregistered, "group.AddGroupHandler")
} }
if o.BucketAddMultiBucketLifecycleHandler == nil {
unregistered = append(unregistered, "bucket.AddMultiBucketLifecycleHandler")
}
if o.ConfigurationAddNotificationEndpointHandler == nil { if o.ConfigurationAddNotificationEndpointHandler == nil {
unregistered = append(unregistered, "configuration.AddNotificationEndpointHandler") unregistered = append(unregistered, "configuration.AddNotificationEndpointHandler")
} }
@@ -915,9 +853,6 @@ func (o *ConsoleAPI) Validate() error {
if o.BucketAddRemoteBucketHandler == nil { if o.BucketAddRemoteBucketHandler == nil {
unregistered = append(unregistered, "bucket.AddRemoteBucketHandler") unregistered = append(unregistered, "bucket.AddRemoteBucketHandler")
} }
if o.TieringAddTierHandler == nil {
unregistered = append(unregistered, "tiering.AddTierHandler")
}
if o.UserAddUserHandler == nil { if o.UserAddUserHandler == nil {
unregistered = append(unregistered, "user.AddUserHandler") unregistered = append(unregistered, "user.AddUserHandler")
} }
@@ -978,9 +913,6 @@ func (o *ConsoleAPI) Validate() error {
if o.BucketDeleteBucketEventHandler == nil { if o.BucketDeleteBucketEventHandler == nil {
unregistered = append(unregistered, "bucket.DeleteBucketEventHandler") unregistered = append(unregistered, "bucket.DeleteBucketEventHandler")
} }
if o.BucketDeleteBucketLifecycleRuleHandler == nil {
unregistered = append(unregistered, "bucket.DeleteBucketLifecycleRuleHandler")
}
if o.BucketDeleteBucketReplicationRuleHandler == nil { if o.BucketDeleteBucketReplicationRuleHandler == nil {
unregistered = append(unregistered, "bucket.DeleteBucketReplicationRuleHandler") unregistered = append(unregistered, "bucket.DeleteBucketReplicationRuleHandler")
} }
@@ -1020,9 +952,6 @@ func (o *ConsoleAPI) Validate() error {
if o.PublicDownloadSharedObjectHandler == nil { if o.PublicDownloadSharedObjectHandler == nil {
unregistered = append(unregistered, "public.DownloadSharedObjectHandler") unregistered = append(unregistered, "public.DownloadSharedObjectHandler")
} }
if o.TieringEditTierCredentialsHandler == nil {
unregistered = append(unregistered, "tiering.EditTierCredentialsHandler")
}
if o.BucketEnableBucketEncryptionHandler == nil { if o.BucketEnableBucketEncryptionHandler == nil {
unregistered = append(unregistered, "bucket.EnableBucketEncryptionHandler") unregistered = append(unregistered, "bucket.EnableBucketEncryptionHandler")
} }
@@ -1032,9 +961,6 @@ func (o *ConsoleAPI) Validate() error {
if o.BucketGetBucketEncryptionInfoHandler == nil { if o.BucketGetBucketEncryptionInfoHandler == nil {
unregistered = append(unregistered, "bucket.GetBucketEncryptionInfoHandler") unregistered = append(unregistered, "bucket.GetBucketEncryptionInfoHandler")
} }
if o.BucketGetBucketLifecycleHandler == nil {
unregistered = append(unregistered, "bucket.GetBucketLifecycleHandler")
}
if o.BucketGetBucketObjectLockingStatusHandler == nil { if o.BucketGetBucketObjectLockingStatusHandler == nil {
unregistered = append(unregistered, "bucket.GetBucketObjectLockingStatusHandler") unregistered = append(unregistered, "bucket.GetBucketObjectLockingStatusHandler")
} }
@@ -1074,9 +1000,6 @@ func (o *ConsoleAPI) Validate() error {
if o.ServiceAccountGetServiceAccountHandler == nil { if o.ServiceAccountGetServiceAccountHandler == nil {
unregistered = append(unregistered, "service_account.GetServiceAccountHandler") unregistered = append(unregistered, "service_account.GetServiceAccountHandler")
} }
if o.TieringGetTierHandler == nil {
unregistered = append(unregistered, "tiering.GetTierHandler")
}
if o.UserGetUserInfoHandler == nil { if o.UserGetUserInfoHandler == nil {
unregistered = append(unregistered, "user.GetUserInfoHandler") unregistered = append(unregistered, "user.GetUserInfoHandler")
} }
@@ -1221,9 +1144,6 @@ func (o *ConsoleAPI) Validate() error {
if o.PolicyRemovePolicyHandler == nil { if o.PolicyRemovePolicyHandler == nil {
unregistered = append(unregistered, "policy.RemovePolicyHandler") unregistered = append(unregistered, "policy.RemovePolicyHandler")
} }
if o.TieringRemoveTierHandler == nil {
unregistered = append(unregistered, "tiering.RemoveTierHandler")
}
if o.UserRemoveUserHandler == nil { if o.UserRemoveUserHandler == nil {
unregistered = append(unregistered, "user.RemoveUserHandler") unregistered = append(unregistered, "user.RemoveUserHandler")
} }
@@ -1263,15 +1183,6 @@ func (o *ConsoleAPI) Validate() error {
if o.ObjectShareObjectHandler == nil { if o.ObjectShareObjectHandler == nil {
unregistered = append(unregistered, "object.ShareObjectHandler") unregistered = append(unregistered, "object.ShareObjectHandler")
} }
if o.TieringTiersListHandler == nil {
unregistered = append(unregistered, "tiering.TiersListHandler")
}
if o.TieringTiersListNamesHandler == nil {
unregistered = append(unregistered, "tiering.TiersListNamesHandler")
}
if o.BucketUpdateBucketLifecycleHandler == nil {
unregistered = append(unregistered, "bucket.UpdateBucketLifecycleHandler")
}
if o.IdpUpdateConfigurationHandler == nil { if o.IdpUpdateConfigurationHandler == nil {
unregistered = append(unregistered, "idp.UpdateConfigurationHandler") unregistered = append(unregistered, "idp.UpdateConfigurationHandler")
} }
@@ -1405,18 +1316,10 @@ func (o *ConsoleAPI) initHandlerCache() {
if o.handlers["POST"] == nil { if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler) o.handlers["POST"] = make(map[string]http.Handler)
} }
o.handlers["POST"]["/buckets/{bucket_name}/lifecycle"] = bucket.NewAddBucketLifecycle(o.context, o.BucketAddBucketLifecycleHandler)
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
}
o.handlers["POST"]["/groups"] = group.NewAddGroup(o.context, o.GroupAddGroupHandler) o.handlers["POST"]["/groups"] = group.NewAddGroup(o.context, o.GroupAddGroupHandler)
if o.handlers["POST"] == nil { if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler) o.handlers["POST"] = make(map[string]http.Handler)
} }
o.handlers["POST"]["/buckets/multi-lifecycle"] = bucket.NewAddMultiBucketLifecycle(o.context, o.BucketAddMultiBucketLifecycleHandler)
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
}
o.handlers["POST"]["/admin/notification_endpoints"] = configuration.NewAddNotificationEndpoint(o.context, o.ConfigurationAddNotificationEndpointHandler) o.handlers["POST"]["/admin/notification_endpoints"] = configuration.NewAddNotificationEndpoint(o.context, o.ConfigurationAddNotificationEndpointHandler)
if o.handlers["POST"] == nil { if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler) o.handlers["POST"] = make(map[string]http.Handler)
@@ -1429,10 +1332,6 @@ func (o *ConsoleAPI) initHandlerCache() {
if o.handlers["POST"] == nil { if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler) o.handlers["POST"] = make(map[string]http.Handler)
} }
o.handlers["POST"]["/admin/tiers"] = tiering.NewAddTier(o.context, o.TieringAddTierHandler)
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
}
o.handlers["POST"]["/users"] = user.NewAddUser(o.context, o.UserAddUserHandler) o.handlers["POST"]["/users"] = user.NewAddUser(o.context, o.UserAddUserHandler)
if o.handlers["GET"] == nil { if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler) o.handlers["GET"] = make(map[string]http.Handler)
@@ -1513,10 +1412,6 @@ func (o *ConsoleAPI) initHandlerCache() {
if o.handlers["DELETE"] == nil { if o.handlers["DELETE"] == nil {
o.handlers["DELETE"] = make(map[string]http.Handler) o.handlers["DELETE"] = make(map[string]http.Handler)
} }
o.handlers["DELETE"]["/buckets/{bucket_name}/lifecycle/{lifecycle_id}"] = bucket.NewDeleteBucketLifecycleRule(o.context, o.BucketDeleteBucketLifecycleRuleHandler)
if o.handlers["DELETE"] == nil {
o.handlers["DELETE"] = make(map[string]http.Handler)
}
o.handlers["DELETE"]["/buckets/{bucket_name}/replication/{rule_id}"] = bucket.NewDeleteBucketReplicationRule(o.context, o.BucketDeleteBucketReplicationRuleHandler) o.handlers["DELETE"]["/buckets/{bucket_name}/replication/{rule_id}"] = bucket.NewDeleteBucketReplicationRule(o.context, o.BucketDeleteBucketReplicationRuleHandler)
if o.handlers["DELETE"] == nil { if o.handlers["DELETE"] == nil {
o.handlers["DELETE"] = make(map[string]http.Handler) o.handlers["DELETE"] = make(map[string]http.Handler)
@@ -1566,10 +1461,6 @@ func (o *ConsoleAPI) initHandlerCache() {
o.handlers["GET"] = make(map[string]http.Handler) o.handlers["GET"] = make(map[string]http.Handler)
} }
o.handlers["GET"]["/download-shared-object/{url}"] = public.NewDownloadSharedObject(o.context, o.PublicDownloadSharedObjectHandler) o.handlers["GET"]["/download-shared-object/{url}"] = public.NewDownloadSharedObject(o.context, o.PublicDownloadSharedObjectHandler)
if o.handlers["PUT"] == nil {
o.handlers["PUT"] = make(map[string]http.Handler)
}
o.handlers["PUT"]["/admin/tiers/{type}/{name}/credentials"] = tiering.NewEditTierCredentials(o.context, o.TieringEditTierCredentialsHandler)
if o.handlers["POST"] == nil { if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler) o.handlers["POST"] = make(map[string]http.Handler)
} }
@@ -1585,10 +1476,6 @@ func (o *ConsoleAPI) initHandlerCache() {
if o.handlers["GET"] == nil { if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler) o.handlers["GET"] = make(map[string]http.Handler)
} }
o.handlers["GET"]["/buckets/{bucket_name}/lifecycle"] = bucket.NewGetBucketLifecycle(o.context, o.BucketGetBucketLifecycleHandler)
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}
o.handlers["GET"]["/buckets/{bucket_name}/object-locking"] = bucket.NewGetBucketObjectLockingStatus(o.context, o.BucketGetBucketObjectLockingStatusHandler) o.handlers["GET"]["/buckets/{bucket_name}/object-locking"] = bucket.NewGetBucketObjectLockingStatus(o.context, o.BucketGetBucketObjectLockingStatusHandler)
if o.handlers["GET"] == nil { if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler) o.handlers["GET"] = make(map[string]http.Handler)
@@ -1641,10 +1528,6 @@ func (o *ConsoleAPI) initHandlerCache() {
if o.handlers["GET"] == nil { if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler) o.handlers["GET"] = make(map[string]http.Handler)
} }
o.handlers["GET"]["/admin/tiers/{type}/{name}"] = tiering.NewGetTier(o.context, o.TieringGetTierHandler)
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}
o.handlers["GET"]["/user/{name}"] = user.NewGetUserInfo(o.context, o.UserGetUserInfoHandler) o.handlers["GET"]["/user/{name}"] = user.NewGetUserInfo(o.context, o.UserGetUserInfoHandler)
if o.handlers["GET"] == nil { if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler) o.handlers["GET"] = make(map[string]http.Handler)
@@ -1837,10 +1720,6 @@ func (o *ConsoleAPI) initHandlerCache() {
if o.handlers["DELETE"] == nil { if o.handlers["DELETE"] == nil {
o.handlers["DELETE"] = make(map[string]http.Handler) o.handlers["DELETE"] = make(map[string]http.Handler)
} }
o.handlers["DELETE"]["/admin/tiers/{name}/remove"] = tiering.NewRemoveTier(o.context, o.TieringRemoveTierHandler)
if o.handlers["DELETE"] == nil {
o.handlers["DELETE"] = make(map[string]http.Handler)
}
o.handlers["DELETE"]["/user/{name}"] = user.NewRemoveUser(o.context, o.UserRemoveUserHandler) o.handlers["DELETE"]["/user/{name}"] = user.NewRemoveUser(o.context, o.UserRemoveUserHandler)
if o.handlers["POST"] == nil { if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler) o.handlers["POST"] = make(map[string]http.Handler)
@@ -1890,18 +1769,6 @@ func (o *ConsoleAPI) initHandlerCache() {
o.handlers["GET"] = make(map[string]http.Handler) o.handlers["GET"] = make(map[string]http.Handler)
} }
o.handlers["GET"]["/buckets/{bucket_name}/objects/share"] = object.NewShareObject(o.context, o.ObjectShareObjectHandler) o.handlers["GET"]["/buckets/{bucket_name}/objects/share"] = object.NewShareObject(o.context, o.ObjectShareObjectHandler)
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}
o.handlers["GET"]["/admin/tiers"] = tiering.NewTiersList(o.context, o.TieringTiersListHandler)
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}
o.handlers["GET"]["/admin/tiers/names"] = tiering.NewTiersListNames(o.context, o.TieringTiersListNamesHandler)
if o.handlers["PUT"] == nil {
o.handlers["PUT"] = make(map[string]http.Handler)
}
o.handlers["PUT"]["/buckets/{bucket_name}/lifecycle/{lifecycle_id}"] = bucket.NewUpdateBucketLifecycle(o.context, o.BucketUpdateBucketLifecycleHandler)
if o.handlers["PUT"] == nil { if o.handlers["PUT"] == nil {
o.handlers["PUT"] = make(map[string]http.Handler) o.handlers["PUT"] = make(map[string]http.Handler)
} }

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// AddTierHandlerFunc turns a function with the right signature into a add tier handler
type AddTierHandlerFunc func(AddTierParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn AddTierHandlerFunc) Handle(params AddTierParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// AddTierHandler interface for that can handle valid add tier params
type AddTierHandler interface {
Handle(AddTierParams, *models.Principal) middleware.Responder
}
// NewAddTier creates a new http.Handler for the add tier operation
func NewAddTier(ctx *middleware.Context, handler AddTierHandler) *AddTier {
return &AddTier{Context: ctx, Handler: handler}
}
/*
AddTier swagger:route POST /admin/tiers Tiering addTier
Allows to configure a new tier
*/
type AddTier struct {
Context *middleware.Context
Handler AddTierHandler
}
func (o *AddTier) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewAddTierParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,101 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"io"
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/validate"
"github.com/minio/console/models"
)
// NewAddTierParams creates a new AddTierParams object
//
// There are no default values defined in the spec.
func NewAddTierParams() AddTierParams {
return AddTierParams{}
}
// AddTierParams contains all the bound params for the add tier operation
// typically these are obtained from a http.Request
//
// swagger:parameters AddTier
type AddTierParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: body
*/
Body *models.Tier
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewAddTierParams() beforehand.
func (o *AddTierParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if runtime.HasBody(r) {
defer r.Body.Close()
var body models.Tier
if err := route.Consumer.Consume(r.Body, &body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("body", "body", ""))
} else {
res = append(res, errors.NewParseError("body", "body", "", err))
}
} else {
// validate body object
if err := body.Validate(route.Formats); err != nil {
res = append(res, err)
}
ctx := validate.WithOperationRequest(r.Context())
if err := body.ContextValidate(ctx, route.Formats); err != nil {
res = append(res, err)
}
if len(res) == 0 {
o.Body = &body
}
}
} else {
res = append(res, errors.Required("body", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,115 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// AddTierCreatedCode is the HTTP code returned for type AddTierCreated
const AddTierCreatedCode int = 201
/*
AddTierCreated A successful response.
swagger:response addTierCreated
*/
type AddTierCreated struct {
}
// NewAddTierCreated creates AddTierCreated with default headers values
func NewAddTierCreated() *AddTierCreated {
return &AddTierCreated{}
}
// WriteResponse to the client
func (o *AddTierCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(201)
}
/*
AddTierDefault Generic error response.
swagger:response addTierDefault
*/
type AddTierDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewAddTierDefault creates AddTierDefault with default headers values
func NewAddTierDefault(code int) *AddTierDefault {
if code <= 0 {
code = 500
}
return &AddTierDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the add tier default response
func (o *AddTierDefault) WithStatusCode(code int) *AddTierDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the add tier default response
func (o *AddTierDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the add tier default response
func (o *AddTierDefault) WithPayload(payload *models.APIError) *AddTierDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the add tier default response
func (o *AddTierDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *AddTierDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,104 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
)
// AddTierURL generates an URL for the add tier operation
type AddTierURL struct {
_basePath string
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *AddTierURL) WithBasePath(bp string) *AddTierURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *AddTierURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *AddTierURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/admin/tiers"
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *AddTierURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *AddTierURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *AddTierURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on AddTierURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on AddTierURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *AddTierURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// EditTierCredentialsHandlerFunc turns a function with the right signature into a edit tier credentials handler
type EditTierCredentialsHandlerFunc func(EditTierCredentialsParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn EditTierCredentialsHandlerFunc) Handle(params EditTierCredentialsParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// EditTierCredentialsHandler interface for that can handle valid edit tier credentials params
type EditTierCredentialsHandler interface {
Handle(EditTierCredentialsParams, *models.Principal) middleware.Responder
}
// NewEditTierCredentials creates a new http.Handler for the edit tier credentials operation
func NewEditTierCredentials(ctx *middleware.Context, handler EditTierCredentialsHandler) *EditTierCredentials {
return &EditTierCredentials{Context: ctx, Handler: handler}
}
/*
EditTierCredentials swagger:route PUT /admin/tiers/{type}/{name}/credentials Tiering editTierCredentials
Edit Tier Credentials
*/
type EditTierCredentials struct {
Context *middleware.Context
Handler EditTierCredentialsHandler
}
func (o *EditTierCredentials) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewEditTierCredentialsParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,164 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"io"
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
"github.com/minio/console/models"
)
// NewEditTierCredentialsParams creates a new EditTierCredentialsParams object
//
// There are no default values defined in the spec.
func NewEditTierCredentialsParams() EditTierCredentialsParams {
return EditTierCredentialsParams{}
}
// EditTierCredentialsParams contains all the bound params for the edit tier credentials operation
// typically these are obtained from a http.Request
//
// swagger:parameters EditTierCredentials
type EditTierCredentialsParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: body
*/
Body *models.TierCredentialsRequest
/*
Required: true
In: path
*/
Name string
/*
Required: true
In: path
*/
Type string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewEditTierCredentialsParams() beforehand.
func (o *EditTierCredentialsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if runtime.HasBody(r) {
defer r.Body.Close()
var body models.TierCredentialsRequest
if err := route.Consumer.Consume(r.Body, &body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("body", "body", ""))
} else {
res = append(res, errors.NewParseError("body", "body", "", err))
}
} else {
// validate body object
if err := body.Validate(route.Formats); err != nil {
res = append(res, err)
}
ctx := validate.WithOperationRequest(r.Context())
if err := body.ContextValidate(ctx, route.Formats); err != nil {
res = append(res, err)
}
if len(res) == 0 {
o.Body = &body
}
}
} else {
res = append(res, errors.Required("body", "body", ""))
}
rName, rhkName, _ := route.Params.GetOK("name")
if err := o.bindName(rName, rhkName, route.Formats); err != nil {
res = append(res, err)
}
rType, rhkType, _ := route.Params.GetOK("type")
if err := o.bindType(rType, rhkType, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindName binds and validates parameter Name from path.
func (o *EditTierCredentialsParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.Name = raw
return nil
}
// bindType binds and validates parameter Type from path.
func (o *EditTierCredentialsParams) bindType(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.Type = raw
if err := o.validateType(formats); err != nil {
return err
}
return nil
}
// validateType carries on validations for parameter Type
func (o *EditTierCredentialsParams) validateType(formats strfmt.Registry) error {
if err := validate.EnumCase("type", "path", o.Type, []interface{}{"s3", "gcs", "azure", "minio"}, true); err != nil {
return err
}
return nil
}

View File

@@ -1,115 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// EditTierCredentialsOKCode is the HTTP code returned for type EditTierCredentialsOK
const EditTierCredentialsOKCode int = 200
/*
EditTierCredentialsOK A successful response.
swagger:response editTierCredentialsOK
*/
type EditTierCredentialsOK struct {
}
// NewEditTierCredentialsOK creates EditTierCredentialsOK with default headers values
func NewEditTierCredentialsOK() *EditTierCredentialsOK {
return &EditTierCredentialsOK{}
}
// WriteResponse to the client
func (o *EditTierCredentialsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(200)
}
/*
EditTierCredentialsDefault Generic error response.
swagger:response editTierCredentialsDefault
*/
type EditTierCredentialsDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewEditTierCredentialsDefault creates EditTierCredentialsDefault with default headers values
func NewEditTierCredentialsDefault(code int) *EditTierCredentialsDefault {
if code <= 0 {
code = 500
}
return &EditTierCredentialsDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the edit tier credentials default response
func (o *EditTierCredentialsDefault) WithStatusCode(code int) *EditTierCredentialsDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the edit tier credentials default response
func (o *EditTierCredentialsDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the edit tier credentials default response
func (o *EditTierCredentialsDefault) WithPayload(payload *models.APIError) *EditTierCredentialsDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the edit tier credentials default response
func (o *EditTierCredentialsDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *EditTierCredentialsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,124 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
"strings"
)
// EditTierCredentialsURL generates an URL for the edit tier credentials operation
type EditTierCredentialsURL struct {
Name string
Type string
_basePath string
// avoid unkeyed usage
_ struct{}
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *EditTierCredentialsURL) WithBasePath(bp string) *EditTierCredentialsURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *EditTierCredentialsURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *EditTierCredentialsURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/admin/tiers/{type}/{name}/credentials"
name := o.Name
if name != "" {
_path = strings.Replace(_path, "{name}", name, -1)
} else {
return nil, errors.New("name is required on EditTierCredentialsURL")
}
typeVar := o.Type
if typeVar != "" {
_path = strings.Replace(_path, "{type}", typeVar, -1)
} else {
return nil, errors.New("type is required on EditTierCredentialsURL")
}
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *EditTierCredentialsURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *EditTierCredentialsURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *EditTierCredentialsURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on EditTierCredentialsURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on EditTierCredentialsURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *EditTierCredentialsURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// GetTierHandlerFunc turns a function with the right signature into a get tier handler
type GetTierHandlerFunc func(GetTierParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn GetTierHandlerFunc) Handle(params GetTierParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// GetTierHandler interface for that can handle valid get tier params
type GetTierHandler interface {
Handle(GetTierParams, *models.Principal) middleware.Responder
}
// NewGetTier creates a new http.Handler for the get tier operation
func NewGetTier(ctx *middleware.Context, handler GetTierHandler) *GetTier {
return &GetTier{Context: ctx, Handler: handler}
}
/*
GetTier swagger:route GET /admin/tiers/{type}/{name} Tiering getTier
Get Tier
*/
type GetTier struct {
Context *middleware.Context
Handler GetTierHandler
}
func (o *GetTier) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewGetTierParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,127 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
)
// NewGetTierParams creates a new GetTierParams object
//
// There are no default values defined in the spec.
func NewGetTierParams() GetTierParams {
return GetTierParams{}
}
// GetTierParams contains all the bound params for the get tier operation
// typically these are obtained from a http.Request
//
// swagger:parameters GetTier
type GetTierParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: path
*/
Name string
/*
Required: true
In: path
*/
Type string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewGetTierParams() beforehand.
func (o *GetTierParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
rName, rhkName, _ := route.Params.GetOK("name")
if err := o.bindName(rName, rhkName, route.Formats); err != nil {
res = append(res, err)
}
rType, rhkType, _ := route.Params.GetOK("type")
if err := o.bindType(rType, rhkType, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindName binds and validates parameter Name from path.
func (o *GetTierParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.Name = raw
return nil
}
// bindType binds and validates parameter Type from path.
func (o *GetTierParams) bindType(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.Type = raw
if err := o.validateType(formats); err != nil {
return err
}
return nil
}
// validateType carries on validations for parameter Type
func (o *GetTierParams) validateType(formats strfmt.Registry) error {
if err := validate.EnumCase("type", "path", o.Type, []interface{}{"s3", "gcs", "azure", "minio"}, true); err != nil {
return err
}
return nil
}

View File

@@ -1,135 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// GetTierOKCode is the HTTP code returned for type GetTierOK
const GetTierOKCode int = 200
/*
GetTierOK A successful response.
swagger:response getTierOK
*/
type GetTierOK struct {
/*
In: Body
*/
Payload *models.Tier `json:"body,omitempty"`
}
// NewGetTierOK creates GetTierOK with default headers values
func NewGetTierOK() *GetTierOK {
return &GetTierOK{}
}
// WithPayload adds the payload to the get tier o k response
func (o *GetTierOK) WithPayload(payload *models.Tier) *GetTierOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the get tier o k response
func (o *GetTierOK) SetPayload(payload *models.Tier) {
o.Payload = payload
}
// WriteResponse to the client
func (o *GetTierOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
/*
GetTierDefault Generic error response.
swagger:response getTierDefault
*/
type GetTierDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewGetTierDefault creates GetTierDefault with default headers values
func NewGetTierDefault(code int) *GetTierDefault {
if code <= 0 {
code = 500
}
return &GetTierDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the get tier default response
func (o *GetTierDefault) WithStatusCode(code int) *GetTierDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the get tier default response
func (o *GetTierDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the get tier default response
func (o *GetTierDefault) WithPayload(payload *models.APIError) *GetTierDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the get tier default response
func (o *GetTierDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *GetTierDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,124 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
"strings"
)
// GetTierURL generates an URL for the get tier operation
type GetTierURL struct {
Name string
Type string
_basePath string
// avoid unkeyed usage
_ struct{}
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *GetTierURL) WithBasePath(bp string) *GetTierURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *GetTierURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *GetTierURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/admin/tiers/{type}/{name}"
name := o.Name
if name != "" {
_path = strings.Replace(_path, "{name}", name, -1)
} else {
return nil, errors.New("name is required on GetTierURL")
}
typeVar := o.Type
if typeVar != "" {
_path = strings.Replace(_path, "{type}", typeVar, -1)
} else {
return nil, errors.New("type is required on GetTierURL")
}
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *GetTierURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *GetTierURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *GetTierURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on GetTierURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on GetTierURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *GetTierURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// RemoveTierHandlerFunc turns a function with the right signature into a remove tier handler
type RemoveTierHandlerFunc func(RemoveTierParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn RemoveTierHandlerFunc) Handle(params RemoveTierParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// RemoveTierHandler interface for that can handle valid remove tier params
type RemoveTierHandler interface {
Handle(RemoveTierParams, *models.Principal) middleware.Responder
}
// NewRemoveTier creates a new http.Handler for the remove tier operation
func NewRemoveTier(ctx *middleware.Context, handler RemoveTierHandler) *RemoveTier {
return &RemoveTier{Context: ctx, Handler: handler}
}
/*
RemoveTier swagger:route DELETE /admin/tiers/{name}/remove Tiering removeTier
Remove Tier
*/
type RemoveTier struct {
Context *middleware.Context
Handler RemoveTierHandler
}
func (o *RemoveTier) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewRemoveTierParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
)
// NewRemoveTierParams creates a new RemoveTierParams object
//
// There are no default values defined in the spec.
func NewRemoveTierParams() RemoveTierParams {
return RemoveTierParams{}
}
// RemoveTierParams contains all the bound params for the remove tier operation
// typically these are obtained from a http.Request
//
// swagger:parameters RemoveTier
type RemoveTierParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: path
*/
Name string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewRemoveTierParams() beforehand.
func (o *RemoveTierParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
rName, rhkName, _ := route.Params.GetOK("name")
if err := o.bindName(rName, rhkName, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindName binds and validates parameter Name from path.
func (o *RemoveTierParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.Name = raw
return nil
}

View File

@@ -1,115 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// RemoveTierNoContentCode is the HTTP code returned for type RemoveTierNoContent
const RemoveTierNoContentCode int = 204
/*
RemoveTierNoContent A successful response.
swagger:response removeTierNoContent
*/
type RemoveTierNoContent struct {
}
// NewRemoveTierNoContent creates RemoveTierNoContent with default headers values
func NewRemoveTierNoContent() *RemoveTierNoContent {
return &RemoveTierNoContent{}
}
// WriteResponse to the client
func (o *RemoveTierNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(204)
}
/*
RemoveTierDefault Generic error response.
swagger:response removeTierDefault
*/
type RemoveTierDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewRemoveTierDefault creates RemoveTierDefault with default headers values
func NewRemoveTierDefault(code int) *RemoveTierDefault {
if code <= 0 {
code = 500
}
return &RemoveTierDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the remove tier default response
func (o *RemoveTierDefault) WithStatusCode(code int) *RemoveTierDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the remove tier default response
func (o *RemoveTierDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the remove tier default response
func (o *RemoveTierDefault) WithPayload(payload *models.APIError) *RemoveTierDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the remove tier default response
func (o *RemoveTierDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *RemoveTierDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,116 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
"strings"
)
// RemoveTierURL generates an URL for the remove tier operation
type RemoveTierURL struct {
Name string
_basePath string
// avoid unkeyed usage
_ struct{}
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *RemoveTierURL) WithBasePath(bp string) *RemoveTierURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *RemoveTierURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *RemoveTierURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/admin/tiers/{name}/remove"
name := o.Name
if name != "" {
_path = strings.Replace(_path, "{name}", name, -1)
} else {
return nil, errors.New("name is required on RemoveTierURL")
}
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *RemoveTierURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *RemoveTierURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *RemoveTierURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on RemoveTierURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on RemoveTierURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *RemoveTierURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// TiersListHandlerFunc turns a function with the right signature into a tiers list handler
type TiersListHandlerFunc func(TiersListParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn TiersListHandlerFunc) Handle(params TiersListParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// TiersListHandler interface for that can handle valid tiers list params
type TiersListHandler interface {
Handle(TiersListParams, *models.Principal) middleware.Responder
}
// NewTiersList creates a new http.Handler for the tiers list operation
func NewTiersList(ctx *middleware.Context, handler TiersListHandler) *TiersList {
return &TiersList{Context: ctx, Handler: handler}
}
/*
TiersList swagger:route GET /admin/tiers Tiering tiersList
Returns a list of tiers for ilm
*/
type TiersList struct {
Context *middleware.Context
Handler TiersListHandler
}
func (o *TiersList) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewTiersListParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,88 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// TiersListNamesHandlerFunc turns a function with the right signature into a tiers list names handler
type TiersListNamesHandlerFunc func(TiersListNamesParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn TiersListNamesHandlerFunc) Handle(params TiersListNamesParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// TiersListNamesHandler interface for that can handle valid tiers list names params
type TiersListNamesHandler interface {
Handle(TiersListNamesParams, *models.Principal) middleware.Responder
}
// NewTiersListNames creates a new http.Handler for the tiers list names operation
func NewTiersListNames(ctx *middleware.Context, handler TiersListNamesHandler) *TiersListNames {
return &TiersListNames{Context: ctx, Handler: handler}
}
/*
TiersListNames swagger:route GET /admin/tiers/names Tiering tiersListNames
Returns a list of tiers' names for ilm
*/
type TiersListNames struct {
Context *middleware.Context
Handler TiersListNamesHandler
}
func (o *TiersListNames) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewTiersListNamesParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -1,63 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime/middleware"
)
// NewTiersListNamesParams creates a new TiersListNamesParams object
//
// There are no default values defined in the spec.
func NewTiersListNamesParams() TiersListNamesParams {
return TiersListNamesParams{}
}
// TiersListNamesParams contains all the bound params for the tiers list names operation
// typically these are obtained from a http.Request
//
// swagger:parameters TiersListNames
type TiersListNamesParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewTiersListNamesParams() beforehand.
func (o *TiersListNamesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,135 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// TiersListNamesOKCode is the HTTP code returned for type TiersListNamesOK
const TiersListNamesOKCode int = 200
/*
TiersListNamesOK A successful response.
swagger:response tiersListNamesOK
*/
type TiersListNamesOK struct {
/*
In: Body
*/
Payload *models.TiersNameListResponse `json:"body,omitempty"`
}
// NewTiersListNamesOK creates TiersListNamesOK with default headers values
func NewTiersListNamesOK() *TiersListNamesOK {
return &TiersListNamesOK{}
}
// WithPayload adds the payload to the tiers list names o k response
func (o *TiersListNamesOK) WithPayload(payload *models.TiersNameListResponse) *TiersListNamesOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the tiers list names o k response
func (o *TiersListNamesOK) SetPayload(payload *models.TiersNameListResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TiersListNamesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
/*
TiersListNamesDefault Generic error response.
swagger:response tiersListNamesDefault
*/
type TiersListNamesDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewTiersListNamesDefault creates TiersListNamesDefault with default headers values
func NewTiersListNamesDefault(code int) *TiersListNamesDefault {
if code <= 0 {
code = 500
}
return &TiersListNamesDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the tiers list names default response
func (o *TiersListNamesDefault) WithStatusCode(code int) *TiersListNamesDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the tiers list names default response
func (o *TiersListNamesDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the tiers list names default response
func (o *TiersListNamesDefault) WithPayload(payload *models.APIError) *TiersListNamesDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the tiers list names default response
func (o *TiersListNamesDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TiersListNamesDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,104 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
)
// TiersListNamesURL generates an URL for the tiers list names operation
type TiersListNamesURL struct {
_basePath string
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *TiersListNamesURL) WithBasePath(bp string) *TiersListNamesURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *TiersListNamesURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *TiersListNamesURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/admin/tiers/names"
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *TiersListNamesURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *TiersListNamesURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *TiersListNamesURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on TiersListNamesURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on TiersListNamesURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *TiersListNamesURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,63 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime/middleware"
)
// NewTiersListParams creates a new TiersListParams object
//
// There are no default values defined in the spec.
func NewTiersListParams() TiersListParams {
return TiersListParams{}
}
// TiersListParams contains all the bound params for the tiers list operation
// typically these are obtained from a http.Request
//
// swagger:parameters TiersList
type TiersListParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewTiersListParams() beforehand.
func (o *TiersListParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,135 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// TiersListOKCode is the HTTP code returned for type TiersListOK
const TiersListOKCode int = 200
/*
TiersListOK A successful response.
swagger:response tiersListOK
*/
type TiersListOK struct {
/*
In: Body
*/
Payload *models.TierListResponse `json:"body,omitempty"`
}
// NewTiersListOK creates TiersListOK with default headers values
func NewTiersListOK() *TiersListOK {
return &TiersListOK{}
}
// WithPayload adds the payload to the tiers list o k response
func (o *TiersListOK) WithPayload(payload *models.TierListResponse) *TiersListOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the tiers list o k response
func (o *TiersListOK) SetPayload(payload *models.TierListResponse) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TiersListOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
/*
TiersListDefault Generic error response.
swagger:response tiersListDefault
*/
type TiersListDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.APIError `json:"body,omitempty"`
}
// NewTiersListDefault creates TiersListDefault with default headers values
func NewTiersListDefault(code int) *TiersListDefault {
if code <= 0 {
code = 500
}
return &TiersListDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the tiers list default response
func (o *TiersListDefault) WithStatusCode(code int) *TiersListDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the tiers list default response
func (o *TiersListDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the tiers list default response
func (o *TiersListDefault) WithPayload(payload *models.APIError) *TiersListDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the tiers list default response
func (o *TiersListDefault) SetPayload(payload *models.APIError) {
o.Payload = payload
}
// WriteResponse to the client
func (o *TiersListDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -1,104 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package tiering
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
)
// TiersListURL generates an URL for the tiers list operation
type TiersListURL struct {
_basePath string
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *TiersListURL) WithBasePath(bp string) *TiersListURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *TiersListURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *TiersListURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/admin/tiers"
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *TiersListURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *TiersListURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *TiersListURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on TiersListURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on TiersListURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *TiersListURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -1,543 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/rs/xid"
"github.com/minio/mc/cmd/ilm"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/api/operations"
bucketApi "github.com/minio/console/api/operations/bucket"
"github.com/minio/console/models"
)
type MultiLifecycleResult struct {
BucketName string
Error string
}
func registerBucketsLifecycleHandlers(api *operations.ConsoleAPI) {
api.BucketGetBucketLifecycleHandler = bucketApi.GetBucketLifecycleHandlerFunc(func(params bucketApi.GetBucketLifecycleParams, session *models.Principal) middleware.Responder {
listBucketLifecycleResponse, err := getBucketLifecycleResponse(session, params)
if err != nil {
return bucketApi.NewGetBucketLifecycleDefault(err.Code).WithPayload(err.APIError)
}
return bucketApi.NewGetBucketLifecycleOK().WithPayload(listBucketLifecycleResponse)
})
api.BucketAddBucketLifecycleHandler = bucketApi.AddBucketLifecycleHandlerFunc(func(params bucketApi.AddBucketLifecycleParams, session *models.Principal) middleware.Responder {
err := getAddBucketLifecycleResponse(session, params)
if err != nil {
return bucketApi.NewAddBucketLifecycleDefault(err.Code).WithPayload(err.APIError)
}
return bucketApi.NewAddBucketLifecycleCreated()
})
api.BucketUpdateBucketLifecycleHandler = bucketApi.UpdateBucketLifecycleHandlerFunc(func(params bucketApi.UpdateBucketLifecycleParams, session *models.Principal) middleware.Responder {
err := getEditBucketLifecycleRule(session, params)
if err != nil {
return bucketApi.NewUpdateBucketLifecycleDefault(err.Code).WithPayload(err.APIError)
}
return bucketApi.NewUpdateBucketLifecycleOK()
})
api.BucketDeleteBucketLifecycleRuleHandler = bucketApi.DeleteBucketLifecycleRuleHandlerFunc(func(params bucketApi.DeleteBucketLifecycleRuleParams, session *models.Principal) middleware.Responder {
err := getDeleteBucketLifecycleRule(session, params)
if err != nil {
return bucketApi.NewDeleteBucketLifecycleRuleDefault(err.Code).WithPayload(err.APIError)
}
return bucketApi.NewDeleteBucketLifecycleRuleNoContent()
})
api.BucketAddMultiBucketLifecycleHandler = bucketApi.AddMultiBucketLifecycleHandlerFunc(func(params bucketApi.AddMultiBucketLifecycleParams, session *models.Principal) middleware.Responder {
multiBucketResponse, err := getAddMultiBucketLifecycleResponse(session, params)
if err != nil {
bucketApi.NewAddMultiBucketLifecycleDefault(err.Code).WithPayload(err.APIError)
}
return bucketApi.NewAddMultiBucketLifecycleOK().WithPayload(multiBucketResponse)
})
}
// getBucketLifecycle() gets lifecycle lists for a bucket from MinIO API and returns their implementations
func getBucketLifecycle(ctx context.Context, client MinioClient, bucketName string) (*models.BucketLifecycleResponse, error) {
lifecycleList, err := client.getLifecycleRules(ctx, bucketName)
if err != nil {
return nil, err
}
var rules []*models.ObjectBucketLifecycle
for _, rule := range lifecycleList.Rules {
var tags []*models.LifecycleTag
for _, tagData := range rule.RuleFilter.And.Tags {
tags = append(tags, &models.LifecycleTag{
Key: tagData.Key,
Value: tagData.Value,
})
}
if rule.RuleFilter.Tag.Key != "" {
tags = append(tags, &models.LifecycleTag{
Key: rule.RuleFilter.Tag.Key,
Value: rule.RuleFilter.Tag.Value,
})
}
rulePrefix := rule.RuleFilter.And.Prefix
if rulePrefix == "" {
rulePrefix = rule.RuleFilter.Prefix
}
rules = append(rules, &models.ObjectBucketLifecycle{
ID: rule.ID,
Status: rule.Status,
Prefix: rulePrefix,
Expiration: &models.ExpirationResponse{
Date: rule.Expiration.Date.Format(time.RFC3339),
Days: int64(rule.Expiration.Days),
DeleteMarker: rule.Expiration.DeleteMarker.IsEnabled(),
DeleteAll: bool(rule.Expiration.DeleteAll),
NoncurrentExpirationDays: int64(rule.NoncurrentVersionExpiration.NoncurrentDays),
NewerNoncurrentExpirationVersions: int64(rule.NoncurrentVersionExpiration.NewerNoncurrentVersions),
},
Transition: &models.TransitionResponse{
Date: rule.Transition.Date.Format(time.RFC3339),
Days: int64(rule.Transition.Days),
StorageClass: rule.Transition.StorageClass,
NoncurrentStorageClass: rule.NoncurrentVersionTransition.StorageClass,
NoncurrentTransitionDays: int64(rule.NoncurrentVersionTransition.NoncurrentDays),
},
Tags: tags,
})
}
// serialize output
lifecycleBucketsResponse := &models.BucketLifecycleResponse{
Lifecycle: rules,
}
return lifecycleBucketsResponse, nil
}
// getBucketLifecycleResponse performs getBucketLifecycle() and serializes it to the handler's output
func getBucketLifecycleResponse(session *models.Principal, params bucketApi.GetBucketLifecycleParams) (*models.BucketLifecycleResponse, *CodedAPIError) {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mClient, err := newMinioClient(session, getClientIP(params.HTTPRequest))
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
minioClient := minioClient{client: mClient}
bucketEvents, err := getBucketLifecycle(ctx, minioClient, params.BucketName)
if err != nil {
return nil, ErrorWithContext(ctx, ErrBucketLifeCycleNotConfigured, err)
}
return bucketEvents, nil
}
// addBucketLifecycle gets lifecycle lists for a bucket from MinIO API and returns their implementations
func addBucketLifecycle(ctx context.Context, client MinioClient, params bucketApi.AddBucketLifecycleParams) error {
// Configuration that is already set.
lfcCfg, err := client.getLifecycleRules(ctx, params.BucketName)
if err != nil {
if e := err; minio.ToErrorResponse(e).Code == "NoSuchLifecycleConfiguration" {
lfcCfg = lifecycle.NewConfiguration()
} else {
return err
}
}
id := xid.New().String()
opts := ilm.LifecycleOptions{}
// Verify if transition rule is requested
switch params.Body.Type {
case models.AddBucketLifecycleTypeTransition:
if params.Body.TransitionDays == 0 && params.Body.NoncurrentversionTransitionDays == 0 {
return errors.New("you must provide a value for transition days or date")
}
status := !params.Body.Disable
opts = ilm.LifecycleOptions{
ID: id,
Prefix: &params.Body.Prefix,
Status: &status,
Tags: &params.Body.Tags,
ExpiredObjectDeleteMarker: &params.Body.ExpiredObjectDeleteMarker,
ExpiredObjectAllversions: &params.Body.ExpiredObjectDeleteAll,
}
if params.Body.NoncurrentversionTransitionDays > 0 {
noncurrentVersionTransitionDays := int(params.Body.NoncurrentversionTransitionDays)
noncurrentVersionTransitionStorageClass := strings.ToUpper(params.Body.NoncurrentversionTransitionStorageClass)
opts.NoncurrentVersionTransitionDays = &noncurrentVersionTransitionDays
opts.NoncurrentVersionTransitionStorageClass = &noncurrentVersionTransitionStorageClass
} else if params.Body.TransitionDays > 0 {
tdays := strconv.Itoa(int(params.Body.TransitionDays))
sclass := strings.ToUpper(params.Body.StorageClass)
opts.TransitionDays = &tdays
opts.StorageClass = &sclass
}
case models.AddBucketLifecycleTypeExpiry:
// Verify if expiry items are set
if params.Body.NoncurrentversionTransitionDays != 0 {
return errors.New("non current version Transition Days cannot be set when expiry is being configured")
}
if params.Body.NoncurrentversionTransitionStorageClass != "" {
return errors.New("non current version Transition Storage Class cannot be set when expiry is being configured")
}
status := !params.Body.Disable
opts = ilm.LifecycleOptions{
ID: id,
Prefix: &params.Body.Prefix,
Status: &status,
Tags: &params.Body.Tags,
ExpiredObjectDeleteMarker: &params.Body.ExpiredObjectDeleteMarker,
ExpiredObjectAllversions: &params.Body.ExpiredObjectDeleteAll,
}
if params.Body.NewerNoncurrentversionExpirationVersions > 0 {
versions := int(params.Body.NewerNoncurrentversionExpirationVersions)
opts.NewerNoncurrentExpirationVersions = &versions
}
switch {
case params.Body.NoncurrentversionExpirationDays > 0:
days := int(params.Body.NoncurrentversionExpirationDays)
opts.NoncurrentVersionExpirationDays = &days
case params.Body.ExpiryDays > 0:
days := strconv.Itoa(int(params.Body.ExpiryDays))
opts.ExpiryDays = &days
}
default:
// Non set, we return errors
return errors.New("no valid lifecycle configuration requested")
}
newRule, merr := opts.ToILMRule()
if merr != nil {
return merr.ToGoError()
}
lfcCfg.Rules = append(lfcCfg.Rules, newRule)
return client.setBucketLifecycle(ctx, params.BucketName, lfcCfg)
}
// getAddBucketLifecycleResponse returns the response of adding a bucket lifecycle response
func getAddBucketLifecycleResponse(session *models.Principal, params bucketApi.AddBucketLifecycleParams) *CodedAPIError {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mClient, err := newMinioClient(session, getClientIP(params.HTTPRequest))
if err != nil {
return ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
minioClient := minioClient{client: mClient}
err = addBucketLifecycle(ctx, minioClient, params)
if err != nil {
return ErrorWithContext(ctx, err)
}
return nil
}
// editBucketLifecycle gets lifecycle lists for a bucket from MinIO API and updates the selected lifecycle rule
func editBucketLifecycle(ctx context.Context, client MinioClient, params bucketApi.UpdateBucketLifecycleParams) error {
// Configuration that is already set.
lfcCfg, err := client.getLifecycleRules(ctx, params.BucketName)
if err != nil {
if e := err; minio.ToErrorResponse(e).Code == "NoSuchLifecycleConfiguration" {
lfcCfg = lifecycle.NewConfiguration()
} else {
return err
}
}
id := params.LifecycleID
opts := ilm.LifecycleOptions{}
// Verify if transition items are set
switch *params.Body.Type {
case models.UpdateBucketLifecycleTypeTransition:
if params.Body.TransitionDays == 0 && params.Body.NoncurrentversionTransitionDays == 0 {
return errors.New("you must select transition days or non-current transition days configuration")
}
status := !params.Body.Disable
opts = ilm.LifecycleOptions{
ID: id,
Prefix: &params.Body.Prefix,
Status: &status,
Tags: &params.Body.Tags,
ExpiredObjectDeleteMarker: &params.Body.ExpiredObjectDeleteMarker,
ExpiredObjectAllversions: &params.Body.ExpiredObjectDeleteAll,
}
if params.Body.NoncurrentversionTransitionDays > 0 {
noncurrentVersionTransitionDays := int(params.Body.NoncurrentversionTransitionDays)
noncurrentVersionTransitionStorageClass := strings.ToUpper(params.Body.NoncurrentversionTransitionStorageClass)
opts.NoncurrentVersionTransitionDays = &noncurrentVersionTransitionDays
opts.NoncurrentVersionTransitionStorageClass = &noncurrentVersionTransitionStorageClass
} else {
tdays := strconv.Itoa(int(params.Body.TransitionDays))
sclass := strings.ToUpper(params.Body.StorageClass)
opts.TransitionDays = &tdays
opts.StorageClass = &sclass
}
case models.UpdateBucketLifecycleTypeExpiry: // Verify if expiry configuration is set
if params.Body.NoncurrentversionTransitionDays != 0 {
return errors.New("non current version Transition Days cannot be set when expiry is being configured")
}
if params.Body.NoncurrentversionTransitionStorageClass != "" {
return errors.New("non current version Transition Storage Class cannot be set when expiry is being configured")
}
status := !params.Body.Disable
opts = ilm.LifecycleOptions{
ID: id,
Prefix: &params.Body.Prefix,
Status: &status,
Tags: &params.Body.Tags,
ExpiredObjectDeleteMarker: &params.Body.ExpiredObjectDeleteMarker,
ExpiredObjectAllversions: &params.Body.ExpiredObjectDeleteAll,
}
if params.Body.NoncurrentversionExpirationDays > 0 {
days := int(params.Body.NoncurrentversionExpirationDays)
opts.NoncurrentVersionExpirationDays = &days
} else {
days := strconv.Itoa(int(params.Body.ExpiryDays))
opts.ExpiryDays = &days
}
default:
// Non set, we return errors
return errors.New("no valid configuration requested")
}
var rule *lifecycle.Rule
for i := range lfcCfg.Rules {
if lfcCfg.Rules[i].ID == opts.ID {
rule = &lfcCfg.Rules[i]
break
}
}
if rule == nil {
return errors.New("unable to find the matching rule to update")
}
err2 := ilm.ApplyRuleFields(rule, opts)
if err2.ToGoError() != nil {
return fmt.Errorf("Unable to generate new lifecycle rule: %v", err2.ToGoError())
}
return client.setBucketLifecycle(ctx, params.BucketName, lfcCfg)
}
// getEditBucketLifecycleRule returns the response of bucket lifecycle tier edit
func getEditBucketLifecycleRule(session *models.Principal, params bucketApi.UpdateBucketLifecycleParams) *CodedAPIError {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mClient, err := newMinioClient(session, getClientIP(params.HTTPRequest))
if err != nil {
return ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
minioClient := minioClient{client: mClient}
err = editBucketLifecycle(ctx, minioClient, params)
if err != nil {
return ErrorWithContext(ctx, err)
}
return nil
}
// deleteBucketLifecycle deletes lifecycle rule by passing an empty rule to a selected ID
func deleteBucketLifecycle(ctx context.Context, client MinioClient, params bucketApi.DeleteBucketLifecycleRuleParams) error {
// Configuration that is already set.
lfcCfg, err := client.getLifecycleRules(ctx, params.BucketName)
if err != nil {
if e := err; minio.ToErrorResponse(e).Code == "NoSuchLifecycleConfiguration" {
lfcCfg = lifecycle.NewConfiguration()
} else {
return err
}
}
if len(lfcCfg.Rules) == 0 {
return errors.New("no rules available to delete")
}
var newRules []lifecycle.Rule
for _, rule := range lfcCfg.Rules {
if rule.ID != params.LifecycleID {
newRules = append(newRules, rule)
}
}
if len(newRules) == len(lfcCfg.Rules) && len(lfcCfg.Rules) > 0 {
// rule doesn't exist
return fmt.Errorf("lifecycle rule for id '%s' doesn't exist", params.LifecycleID)
}
lfcCfg.Rules = newRules
return client.setBucketLifecycle(ctx, params.BucketName, lfcCfg)
}
// getDeleteBucketLifecycleRule returns the response of bucket lifecycle tier delete
func getDeleteBucketLifecycleRule(session *models.Principal, params bucketApi.DeleteBucketLifecycleRuleParams) *CodedAPIError {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mClient, err := newMinioClient(session, getClientIP(params.HTTPRequest))
if err != nil {
return ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
minioClient := minioClient{client: mClient}
err = deleteBucketLifecycle(ctx, minioClient, params)
if err != nil {
return ErrorWithContext(ctx, err)
}
return nil
}
// addMultiBucketLifecycle creates multibuckets lifecycle assignments
func addMultiBucketLifecycle(ctx context.Context, client MinioClient, params bucketApi.AddMultiBucketLifecycleParams) []MultiLifecycleResult {
bucketsRelation := params.Body.Buckets
// Parallel Lifecycle rules set
parallelLifecycleBucket := func(bucketName string) chan MultiLifecycleResult {
remoteProc := make(chan MultiLifecycleResult)
lifecycleParams := models.AddBucketLifecycle{
Type: *params.Body.Type,
StorageClass: params.Body.StorageClass,
TransitionDays: params.Body.TransitionDays,
Prefix: params.Body.Prefix,
NoncurrentversionTransitionDays: params.Body.NoncurrentversionTransitionDays,
NoncurrentversionTransitionStorageClass: params.Body.NoncurrentversionTransitionStorageClass,
NoncurrentversionExpirationDays: params.Body.NoncurrentversionExpirationDays,
Tags: params.Body.Tags,
ExpiryDays: params.Body.ExpiryDays,
Disable: false,
ExpiredObjectDeleteMarker: params.Body.ExpiredObjectDeleteMarker,
ExpiredObjectDeleteAll: params.Body.ExpiredObjectDeleteMarker,
}
go func() {
defer close(remoteProc)
lifecycleParams := bucketApi.AddBucketLifecycleParams{
BucketName: bucketName,
Body: &lifecycleParams,
}
// We add lifecycle rule & expect a response
err := addBucketLifecycle(ctx, client, lifecycleParams)
errorReturn := ""
if err != nil {
errorReturn = err.Error()
}
retParams := MultiLifecycleResult{
BucketName: bucketName,
Error: errorReturn,
}
remoteProc <- retParams
}()
return remoteProc
}
var lifecycleManagement []chan MultiLifecycleResult
for _, bucketName := range bucketsRelation {
rBucket := parallelLifecycleBucket(bucketName)
lifecycleManagement = append(lifecycleManagement, rBucket)
}
var resultsList []MultiLifecycleResult
for _, result := range lifecycleManagement {
res := <-result
resultsList = append(resultsList, res)
}
return resultsList
}
// getAddMultiBucketLifecycleResponse returns the response of multibucket lifecycle assignment
func getAddMultiBucketLifecycleResponse(session *models.Principal, params bucketApi.AddMultiBucketLifecycleParams) (*models.MultiLifecycleResult, *CodedAPIError) {
ctx, cancel := context.WithCancel(params.HTTPRequest.Context())
defer cancel()
mClient, err := newMinioClient(session, getClientIP(params.HTTPRequest))
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
// create a minioClient interface implementation
// defining the client to be used
minioClient := minioClient{client: mClient}
multiCycleResult := addMultiBucketLifecycle(ctx, minioClient, params)
var returnList []*models.MulticycleResultItem
for _, resultItem := range multiCycleResult {
multicycleRS := models.MulticycleResultItem{
BucketName: resultItem.BucketName,
Error: resultItem.Error,
}
returnList = append(returnList, &multicycleRS)
}
finalResult := models.MultiLifecycleResult{Results: returnList}
return &finalResult, nil
}

View File

@@ -1,370 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"context"
"errors"
"fmt"
"testing"
"github.com/minio/console/models"
"github.com/stretchr/testify/assert"
bucketApi "github.com/minio/console/api/operations/bucket"
"github.com/minio/minio-go/v7/pkg/lifecycle"
)
// assigning mock at runtime instead of compile time
var minioGetLifecycleRulesMock func(ctx context.Context, bucketName string) (lifecycle *lifecycle.Configuration, err error)
// mock function of getLifecycleRules()
func (ac minioClientMock) getLifecycleRules(ctx context.Context, bucketName string) (lifecycle *lifecycle.Configuration, err error) {
return minioGetLifecycleRulesMock(ctx, bucketName)
}
// assign mock for set Bucket Lifecycle
var minioSetBucketLifecycleMock func(ctx context.Context, bucketName string, config *lifecycle.Configuration) error
// mock function of setBucketLifecycle()
func (ac minioClientMock) setBucketLifecycle(ctx context.Context, bucketName string, config *lifecycle.Configuration) error {
return minioSetBucketLifecycleMock(ctx, bucketName, config)
}
func TestGetLifecycleRules(t *testing.T) {
assert := assert.New(t)
// mock minIO client
minClient := minioClientMock{}
function := "getBucketLifecycle()"
bucketName := "testBucket"
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Test-1 : getBucketLifecycle() get list of events for a particular bucket only one config
// mock lifecycle response from MinIO
mockLifecycle := lifecycle.Configuration{
Rules: []lifecycle.Rule{
{
ID: "TESTRULE",
Expiration: lifecycle.Expiration{Days: 15},
Status: "Enabled",
RuleFilter: lifecycle.Filter{Tag: lifecycle.Tag{Key: "tag1", Value: "val1"}, And: lifecycle.And{Prefix: "prefix1"}},
},
},
}
expectedOutput := models.BucketLifecycleResponse{
Lifecycle: []*models.ObjectBucketLifecycle{
{
ID: "TESTRULE",
Status: "Enabled",
Prefix: "prefix1",
Expiration: &models.ExpirationResponse{Days: int64(15)},
Transition: &models.TransitionResponse{},
Tags: []*models.LifecycleTag{{Key: "tag1", Value: "val1"}},
},
},
}
minioGetLifecycleRulesMock = func(_ context.Context, _ string) (lifecycle *lifecycle.Configuration, err error) {
return &mockLifecycle, nil
}
lifeCycleConfigs, err := getBucketLifecycle(ctx, minClient, bucketName)
if err != nil {
t.Errorf("Failed on %s:, error occurred: %s", function, err.Error())
}
// verify length of buckets is correct
assert.Equal(len(expectedOutput.Lifecycle), len(lifeCycleConfigs.Lifecycle), fmt.Sprintf("Failed on %s: length of lists is not the same", function))
for i, conf := range lifeCycleConfigs.Lifecycle {
assert.Equal(expectedOutput.Lifecycle[i].ID, conf.ID)
assert.Equal(expectedOutput.Lifecycle[i].Status, conf.Status)
assert.Equal(expectedOutput.Lifecycle[i].Prefix, conf.Prefix)
assert.Equal(expectedOutput.Lifecycle[i].Expiration.Days, conf.Expiration.Days)
for j, event := range conf.Tags {
assert.Equal(expectedOutput.Lifecycle[i].Tags[j], event)
}
}
// Test-2 : getBucketLifecycle() get list of events is empty
mockLifecycleT2 := lifecycle.Configuration{
Rules: []lifecycle.Rule{},
}
expectedOutputT2 := models.BucketLifecycleResponse{
Lifecycle: []*models.ObjectBucketLifecycle{},
}
minioGetLifecycleRulesMock = func(_ context.Context, _ string) (lifecycle *lifecycle.Configuration, err error) {
return &mockLifecycleT2, nil
}
lifeCycleConfigsT2, err := getBucketLifecycle(ctx, minClient, bucketName)
if err != nil {
t.Errorf("Failed on %s:, error occurred: %s", function, err.Error())
}
// verify length of buckets is correct
assert.Equal(len(expectedOutputT2.Lifecycle), len(lifeCycleConfigsT2.Lifecycle), fmt.Sprintf("Failed on %s: length of lists is not the same", function))
// Test-3 : getBucketLifecycle() get list of events returns an error
minioGetLifecycleRulesMock = func(_ context.Context, _ string) (lifecycle *lifecycle.Configuration, err error) {
return nil, errors.New("error returned")
}
_, errT3 := getBucketLifecycle(ctx, minClient, bucketName)
errorCompare := errors.New("error returned")
assert.Equal(errorCompare, errT3, fmt.Sprintf("Failed on %s: Invalid error message", function))
// verify length of buckets is correct
assert.Equal(len(expectedOutputT2.Lifecycle), len(lifeCycleConfigsT2.Lifecycle), fmt.Sprintf("Failed on %s: length of lists is not the same", function))
}
func TestSetLifecycleRule(t *testing.T) {
assert := assert.New(t)
// mock minIO client
minClient := minioClientMock{}
function := "addBucketLifecycle()"
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Test-1 : addBucketLifecycle() get list of events for a particular bucket only one config
// mock create request
mockLifecycle := lifecycle.Configuration{
Rules: []lifecycle.Rule{
{
ID: "TESTRULE",
Expiration: lifecycle.Expiration{Days: 15},
Status: "Enabled",
RuleFilter: lifecycle.Filter{Tag: lifecycle.Tag{Key: "tag1", Value: "val1"}, And: lifecycle.And{Prefix: "prefix1"}},
},
},
}
minioGetLifecycleRulesMock = func(_ context.Context, _ string) (lifecycle *lifecycle.Configuration, err error) {
return &mockLifecycle, nil
}
expiryRule := "expiry"
insertMock := bucketApi.AddBucketLifecycleParams{
BucketName: "testBucket",
Body: &models.AddBucketLifecycle{
Type: expiryRule,
Disable: false,
ExpiredObjectDeleteMarker: false,
ExpiryDays: int32(16),
NoncurrentversionExpirationDays: 0,
NoncurrentversionTransitionDays: 0,
NoncurrentversionTransitionStorageClass: "",
Prefix: "pref1",
StorageClass: "",
Tags: "",
TransitionDays: 0,
},
}
minioSetBucketLifecycleMock = func(_ context.Context, _ string, _ *lifecycle.Configuration) error {
return nil
}
err := addBucketLifecycle(ctx, minClient, insertMock)
assert.Equal(nil, err, fmt.Sprintf("Failed on %s: Error returned", function))
// Test-2 : addBucketLifecycle() returns error
minioSetBucketLifecycleMock = func(_ context.Context, _ string, _ *lifecycle.Configuration) error {
return errors.New("error setting lifecycle")
}
err2 := addBucketLifecycle(ctx, minClient, insertMock)
assert.Equal(errors.New("error setting lifecycle"), err2, fmt.Sprintf("Failed on %s: Error returned", function))
}
func TestUpdateLifecycleRule(t *testing.T) {
assert := assert.New(t)
// mock minIO client
minClient := minioClientMock{}
function := "editBucketLifecycle()"
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Test-1 : editBucketLifecycle() get list of events for a particular bucket only one config (get lifecycle mock)
// mock create request
mockLifecycle := lifecycle.Configuration{
Rules: []lifecycle.Rule{
{
ID: "TESTRULE",
Expiration: lifecycle.Expiration{Days: 15},
Status: "Enabled",
RuleFilter: lifecycle.Filter{Tag: lifecycle.Tag{Key: "tag1", Value: "val1"}, And: lifecycle.And{Prefix: "prefix1"}},
},
},
}
minioGetLifecycleRulesMock = func(_ context.Context, _ string) (lifecycle *lifecycle.Configuration, err error) {
return &mockLifecycle, nil
}
// Test-2 : editBucketLifecycle() Update lifecycle rule
expiryRule := "expiry"
editMock := bucketApi.UpdateBucketLifecycleParams{
BucketName: "testBucket",
Body: &models.UpdateBucketLifecycle{
Type: &expiryRule,
Disable: false,
ExpiredObjectDeleteMarker: false,
ExpiryDays: int32(16),
NoncurrentversionExpirationDays: 0,
NoncurrentversionTransitionDays: 0,
NoncurrentversionTransitionStorageClass: "",
Prefix: "pref1",
StorageClass: "",
Tags: "",
TransitionDays: 0,
},
LifecycleID: "TESTRULE",
}
minioSetBucketLifecycleMock = func(_ context.Context, _ string, _ *lifecycle.Configuration) error {
return nil
}
err := editBucketLifecycle(ctx, minClient, editMock)
assert.Equal(nil, err, fmt.Sprintf("Failed on %s: Error returned", function))
// Test-2a : editBucketLifecycle() Update lifecycle rule
transitionRule := "transition"
editMock = bucketApi.UpdateBucketLifecycleParams{
BucketName: "testBucket",
Body: &models.UpdateBucketLifecycle{
Type: &transitionRule,
Disable: false,
ExpiredObjectDeleteMarker: false,
NoncurrentversionTransitionDays: 5,
Prefix: "pref1",
StorageClass: "TEST",
NoncurrentversionTransitionStorageClass: "TESTNC",
Tags: "",
TransitionDays: int32(16),
},
LifecycleID: "TESTRULE",
}
minioSetBucketLifecycleMock = func(_ context.Context, _ string, _ *lifecycle.Configuration) error {
return nil
}
err = editBucketLifecycle(ctx, minClient, editMock)
assert.Equal(nil, err, fmt.Sprintf("Failed on %s: Error returned", function))
// Test-3 : editBucketLifecycle() returns error
minioSetBucketLifecycleMock = func(_ context.Context, _ string, _ *lifecycle.Configuration) error {
return errors.New("error setting lifecycle")
}
err2 := editBucketLifecycle(ctx, minClient, editMock)
assert.Equal(errors.New("error setting lifecycle"), err2, fmt.Sprintf("Failed on %s: Error returned", function))
}
func TestDeleteLifecycleRule(t *testing.T) {
assert := assert.New(t)
// mock minIO client
minClient := minioClientMock{}
function := "deleteBucketLifecycle()"
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
minioSetBucketLifecycleMock = func(_ context.Context, _ string, _ *lifecycle.Configuration) error {
return nil
}
// Test-1 : deleteBucketLifecycle() get list of events for a particular bucket only one config (get lifecycle mock)
// mock create request
mockLifecycle := lifecycle.Configuration{
Rules: []lifecycle.Rule{
{
ID: "TESTRULE",
Expiration: lifecycle.Expiration{Days: 15},
Status: "Enabled",
RuleFilter: lifecycle.Filter{Tag: lifecycle.Tag{Key: "tag1", Value: "val1"}, And: lifecycle.And{Prefix: "prefix1"}},
},
{
ID: "TESTRULE2",
Transition: lifecycle.Transition{Days: 10, StorageClass: "TESTSTCLASS"},
Status: "Enabled",
RuleFilter: lifecycle.Filter{Tag: lifecycle.Tag{Key: "tag1", Value: "val1"}, And: lifecycle.And{Prefix: "prefix1"}},
},
},
}
minioGetLifecycleRulesMock = func(_ context.Context, _ string) (lifecycle *lifecycle.Configuration, err error) {
return &mockLifecycle, nil
}
// Test-2 : deleteBucketLifecycle() try to delete an available rule
availableParams := bucketApi.DeleteBucketLifecycleRuleParams{
LifecycleID: "TESTRULE2",
BucketName: "testBucket",
}
err := deleteBucketLifecycle(ctx, minClient, availableParams)
assert.Equal(nil, err, fmt.Sprintf("Failed on %s: Error returned", function))
// Test-3 : deleteBucketLifecycle() returns error trying to delete a non available rule
nonAvailableParams := bucketApi.DeleteBucketLifecycleRuleParams{
LifecycleID: "INVALIDTESTRULE",
BucketName: "testBucket",
}
err2 := deleteBucketLifecycle(ctx, minClient, nonAvailableParams)
assert.Equal(fmt.Errorf("lifecycle rule for id '%s' doesn't exist", nonAvailableParams.LifecycleID), err2, fmt.Sprintf("Failed on %s: Error returned", function))
// Test-4 : deleteBucketLifecycle() returns error trying to delete a rule when no rules are available
mockLifecycle2 := lifecycle.Configuration{
Rules: []lifecycle.Rule{},
}
minioGetLifecycleRulesMock = func(_ context.Context, _ string) (lifecycle *lifecycle.Configuration, err error) {
return &mockLifecycle2, nil
}
err3 := deleteBucketLifecycle(ctx, minClient, nonAvailableParams)
assert.Equal(errors.New("no rules available to delete"), err3, fmt.Sprintf("Failed on %s: Error returned", function))
}

View File

@@ -3224,276 +3224,6 @@ func DisableBucketEncryption(bucketName string) (*http.Response, error) {
return response, err return response, err
} }
func UpdateLifecycleRule(bucketName, ltype string, disable bool, prefix, tags string, expiredObjectDeleteMarker bool, expiryDays, noncurrentversionExpirationDays int64, lifecycleID string) (*http.Response, error) {
// Helper function to update lifecycle rule
// HTTP Verb: PUT
// URL: /buckets/{bucket_name}/lifecycle/{lifecycle_id}
// Body Example:
// {
// "type":"expiry",
// "disable":false,
// "prefix":"",
// "tags":"",
// "expired_object_delete_marker":false,
// "expiry_days":2,
// "noncurrentversion_expiration_days":0
// }
requestDataAdd := map[string]interface{}{
"type": ltype,
"disable": disable,
"prefix": prefix,
"tags": tags,
"expired_object_delete_marker": expiredObjectDeleteMarker,
"expiry_days": expiryDays,
"noncurrentversion_expiration_days": noncurrentversionExpirationDays,
}
requestDataJSON, _ := json.Marshal(requestDataAdd)
requestDataBody := bytes.NewReader(requestDataJSON)
request, err := http.NewRequest("PUT",
"http://localhost:9090/api/v1/buckets/"+bucketName+"/lifecycle/"+lifecycleID,
requestDataBody)
if err != nil {
log.Println(err)
}
request.Header.Add("Cookie", fmt.Sprintf("token=%s", token))
request.Header.Add("Content-Type", "application/json")
client := &http.Client{
Timeout: 2 * time.Second,
}
response, err := client.Do(request)
return response, err
}
func GetBucketLifeCycle(bucketName string) (*http.Response, error) {
// Get Bucket Lifecycle
// HTTP Verb: GET
// URL: /buckets/{bucket_name}/lifecycle
// Response Example:
// {
// "lifecycle": [
// {
// "expiration": {
// "date": "0001-01-01T00:00:00Z",
// "days": 1
// },
// "id": "c8nmpte49b3m6uu3pac0",
// "status": "Enabled",
// "tags": null,
// "transition": {
// "date": "0001-01-01T00:00:00Z"
// }
// }
// ]
// }
request, err := http.NewRequest(
"GET", "http://localhost:9090/api/v1/buckets/"+bucketName+"/lifecycle", nil)
if err != nil {
log.Println(err)
}
request.Header.Add("Cookie", fmt.Sprintf("token=%s", token))
request.Header.Add("Content-Type", "application/json")
client := &http.Client{
Timeout: 2 * time.Second,
}
response, err := client.Do(request)
return response, err
}
func AddBucketLifecycle(bucketName, ltype, prefix, tags string, expiredObjectDeleteMarker bool, expiryDays, noncurrentversionExpirationDays int64) (*http.Response, error) {
// Helper function to add bucket lifecycle
// URL: /buckets/{bucket_name}/lifecycle
// HTTP Verb: POST
// Body Example:
// {
// "type":"expiry",
// "prefix":"",
// "tags":"",
// "expired_object_delete_marker":false,
// "expiry_days":1,
// "noncurrentversion_expiration_days":null
// }
// Needed Parameters for API Call
requestDataAdd := map[string]interface{}{
"type": ltype,
"prefix": prefix,
"tags": tags,
"expired_object_delete_marker": expiredObjectDeleteMarker,
"expiry_days": expiryDays,
"noncurrentversion_expiration_days": noncurrentversionExpirationDays,
}
// Creating the Call by adding the URL and Headers
requestDataJSON, _ := json.Marshal(requestDataAdd)
requestDataBody := bytes.NewReader(requestDataJSON)
request, err := http.NewRequest(
"POST",
"http://localhost:9090/api/v1/buckets/"+bucketName+"/lifecycle",
requestDataBody,
)
if err != nil {
log.Println(err)
}
request.Header.Add("Cookie", fmt.Sprintf("token=%s", token))
request.Header.Add("Content-Type", "application/json")
// Performing the call
client := &http.Client{
Timeout: 2 * time.Second,
}
response, err := client.Do(request)
return response, err
}
func DeleteLifecycleRule(bucketName, lifecycleID string) (*http.Response, error) {
// Helper function to delete lifecycle rule
// HTTP Verb: DELETE
// URL: /buckets/{bucket_name}/lifecycle/{lifecycle_id}
request, err := http.NewRequest(
"DELETE", "http://localhost:9090/api/v1/buckets/"+bucketName+"/lifecycle/"+lifecycleID, nil)
if err != nil {
log.Println(err)
}
request.Header.Add("Cookie", fmt.Sprintf("token=%s", token))
request.Header.Add("Content-Type", "application/json")
client := &http.Client{
Timeout: 2 * time.Second,
}
response, err := client.Do(request)
return response, err
}
func TestBucketLifeCycle(t *testing.T) {
// Variables
assert := assert.New(t)
bucketName := "test-bucket-life-cycle"
locking := false
ltype := "expiry"
prefix := ""
tags := ""
var expiryDays int64 = 1
var expiryDays2 int64 = 2
disable := false
expiredObjectDeleteMarker := false
var noncurrentversionExpirationDays int64
// 1. Add bucket
if !setupBucket(bucketName, locking, nil, nil, nil, assert, 200) {
return
}
// 2. Add Bucket Lifecycle
resp, err := AddBucketLifecycle(
bucketName,
ltype,
prefix,
tags,
expiredObjectDeleteMarker,
expiryDays,
noncurrentversionExpirationDays,
)
assert.Nil(err)
if err != nil {
log.Println(err)
return
}
if resp != nil {
assert.Equal(
201, resp.StatusCode, "Status Code is incorrect")
}
// 3. Get Bucket LifeCycle
resp, err = GetBucketLifeCycle(bucketName)
assert.Nil(err)
if err != nil {
log.Println(err)
return
}
if resp != nil {
assert.Equal(
200, resp.StatusCode, "Status Code is incorrect")
}
bodyBytes, _ := io.ReadAll(resp.Body)
result := models.BucketLifecycleResponse{}
err = json.Unmarshal(bodyBytes, &result)
if err != nil {
log.Println(err)
assert.Nil(err)
}
Status := &result.Lifecycle[0].Status
Days := &result.Lifecycle[0].Expiration.Days
lifecycleID := &result.Lifecycle[0].ID
assert.Equal(expiryDays, *Days, *Days) // Checking it is one day expiration
assert.Equal("Enabled", *Status, *Status) // Checking it's enabled
// 4. Update from 1 day expiration to 2 days expiration
resp, err = UpdateLifecycleRule(
bucketName,
ltype,
disable,
prefix,
tags,
expiredObjectDeleteMarker,
expiryDays2,
noncurrentversionExpirationDays,
*lifecycleID,
)
assert.Nil(err)
if err != nil {
log.Println(err)
return
}
if resp != nil {
assert.Equal(
200, resp.StatusCode, "Status Code is incorrect")
}
// 5. Verify 2 expiration days got updated
resp, err = GetBucketLifeCycle(bucketName)
assert.Nil(err)
if err != nil {
log.Println(err)
return
}
if resp != nil {
assert.Equal(
200, resp.StatusCode, "Status Code is incorrect")
}
bodyBytes, _ = io.ReadAll(resp.Body)
result = models.BucketLifecycleResponse{}
err = json.Unmarshal(bodyBytes, &result)
if err != nil {
log.Println(err)
assert.Nil(err)
}
Days = &result.Lifecycle[0].Expiration.Days
assert.Equal(expiryDays2, *Days, *Days) // Checking it is two days expiration
// 6. Delete Bucket Lifecycle
resp, err = DeleteLifecycleRule(bucketName, *lifecycleID)
assert.Nil(err)
if err != nil {
log.Println(err)
return
}
if resp != nil {
assert.Equal(
204, resp.StatusCode, "Status Code is incorrect")
}
// 6. Verify bucket lifecycle got deleted
resp, err = GetBucketLifeCycle(bucketName)
assert.Nil(err)
if err != nil {
log.Println(err)
return
}
if resp != nil {
assert.Equal(
404, resp.StatusCode, "Status Code is incorrect")
}
}
func SetAccessRuleWithBucket(bucketName, prefix, access string) (*http.Response, error) { func SetAccessRuleWithBucket(bucketName, prefix, access string) (*http.Response, error) {
/* /*
Helper function to Set Access Rule within Bucket Helper function to Set Access Rule within Bucket

View File

@@ -1,158 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"encoding/json"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// AddBucketLifecycle add bucket lifecycle
//
// swagger:model addBucketLifecycle
type AddBucketLifecycle struct {
// Non required, toggle to disable or enable rule
Disable bool `json:"disable,omitempty"`
// Non required, toggle to disable or enable rule
ExpiredObjectDeleteAll bool `json:"expired_object_delete_all,omitempty"`
// Non required, toggle to disable or enable rule
ExpiredObjectDeleteMarker bool `json:"expired_object_delete_marker,omitempty"`
// Required in case of expiry_date or transition fields are not set. it defines an expiry days for ILM
ExpiryDays int32 `json:"expiry_days,omitempty"`
// Non required, can be set in case of expiration is enabled
NewerNoncurrentversionExpirationVersions int32 `json:"newer_noncurrentversion_expiration_versions,omitempty"`
// Non required, can be set in case of expiration is enabled
NoncurrentversionExpirationDays int32 `json:"noncurrentversion_expiration_days,omitempty"`
// Non required, can be set in case of transition is enabled
NoncurrentversionTransitionDays int32 `json:"noncurrentversion_transition_days,omitempty"`
// Non required, can be set in case of transition is enabled
NoncurrentversionTransitionStorageClass string `json:"noncurrentversion_transition_storage_class,omitempty"`
// Non required field, it matches a prefix to perform ILM operations on it
Prefix string `json:"prefix,omitempty"`
// Required only in case of transition is set. it refers to a tier
StorageClass string `json:"storage_class,omitempty"`
// Non required field, tags to match ILM files
Tags string `json:"tags,omitempty"`
// Required in case of transition_date or expiry fields are not set. it defines a transition days for ILM
TransitionDays int32 `json:"transition_days,omitempty"`
// ILM Rule type (Expiry or transition)
// Enum: [expiry transition]
Type string `json:"type,omitempty"`
}
// Validate validates this add bucket lifecycle
func (m *AddBucketLifecycle) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateType(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
var addBucketLifecycleTypeTypePropEnum []interface{}
func init() {
var res []string
if err := json.Unmarshal([]byte(`["expiry","transition"]`), &res); err != nil {
panic(err)
}
for _, v := range res {
addBucketLifecycleTypeTypePropEnum = append(addBucketLifecycleTypeTypePropEnum, v)
}
}
const (
// AddBucketLifecycleTypeExpiry captures enum value "expiry"
AddBucketLifecycleTypeExpiry string = "expiry"
// AddBucketLifecycleTypeTransition captures enum value "transition"
AddBucketLifecycleTypeTransition string = "transition"
)
// prop value enum
func (m *AddBucketLifecycle) validateTypeEnum(path, location string, value string) error {
if err := validate.EnumCase(path, location, value, addBucketLifecycleTypeTypePropEnum, true); err != nil {
return err
}
return nil
}
func (m *AddBucketLifecycle) validateType(formats strfmt.Registry) error {
if swag.IsZero(m.Type) { // not required
return nil
}
// value enum
if err := m.validateTypeEnum("type", "body", m.Type); err != nil {
return err
}
return nil
}
// ContextValidate validates this add bucket lifecycle based on context it is used
func (m *AddBucketLifecycle) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *AddBucketLifecycle) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *AddBucketLifecycle) UnmarshalBinary(b []byte) error {
var res AddBucketLifecycle
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,171 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"encoding/json"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// AddMultiBucketLifecycle add multi bucket lifecycle
//
// swagger:model addMultiBucketLifecycle
type AddMultiBucketLifecycle struct {
// buckets
// Required: true
Buckets []string `json:"buckets"`
// Non required, toggle to disable or enable rule
ExpiredObjectDeleteAll bool `json:"expired_object_delete_all,omitempty"`
// Non required, toggle to disable or enable rule
ExpiredObjectDeleteMarker bool `json:"expired_object_delete_marker,omitempty"`
// Required in case of expiry_date or transition fields are not set. it defines an expiry days for ILM
ExpiryDays int32 `json:"expiry_days,omitempty"`
// Non required, can be set in case of expiration is enabled
NoncurrentversionExpirationDays int32 `json:"noncurrentversion_expiration_days,omitempty"`
// Non required, can be set in case of transition is enabled
NoncurrentversionTransitionDays int32 `json:"noncurrentversion_transition_days,omitempty"`
// Non required, can be set in case of transition is enabled
NoncurrentversionTransitionStorageClass string `json:"noncurrentversion_transition_storage_class,omitempty"`
// Non required field, it matches a prefix to perform ILM operations on it
Prefix string `json:"prefix,omitempty"`
// Required only in case of transition is set. it refers to a tier
StorageClass string `json:"storage_class,omitempty"`
// Non required field, tags to match ILM files
Tags string `json:"tags,omitempty"`
// Required in case of transition_date or expiry fields are not set. it defines a transition days for ILM
TransitionDays int32 `json:"transition_days,omitempty"`
// ILM Rule type (Expiry or transition)
// Required: true
// Enum: [expiry transition]
Type *string `json:"type"`
}
// Validate validates this add multi bucket lifecycle
func (m *AddMultiBucketLifecycle) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateBuckets(formats); err != nil {
res = append(res, err)
}
if err := m.validateType(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *AddMultiBucketLifecycle) validateBuckets(formats strfmt.Registry) error {
if err := validate.Required("buckets", "body", m.Buckets); err != nil {
return err
}
return nil
}
var addMultiBucketLifecycleTypeTypePropEnum []interface{}
func init() {
var res []string
if err := json.Unmarshal([]byte(`["expiry","transition"]`), &res); err != nil {
panic(err)
}
for _, v := range res {
addMultiBucketLifecycleTypeTypePropEnum = append(addMultiBucketLifecycleTypeTypePropEnum, v)
}
}
const (
// AddMultiBucketLifecycleTypeExpiry captures enum value "expiry"
AddMultiBucketLifecycleTypeExpiry string = "expiry"
// AddMultiBucketLifecycleTypeTransition captures enum value "transition"
AddMultiBucketLifecycleTypeTransition string = "transition"
)
// prop value enum
func (m *AddMultiBucketLifecycle) validateTypeEnum(path, location string, value string) error {
if err := validate.EnumCase(path, location, value, addMultiBucketLifecycleTypeTypePropEnum, true); err != nil {
return err
}
return nil
}
func (m *AddMultiBucketLifecycle) validateType(formats strfmt.Registry) error {
if err := validate.Required("type", "body", m.Type); err != nil {
return err
}
// value enum
if err := m.validateTypeEnum("type", "body", *m.Type); err != nil {
return err
}
return nil
}
// ContextValidate validates this add multi bucket lifecycle based on context it is used
func (m *AddMultiBucketLifecycle) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *AddMultiBucketLifecycle) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *AddMultiBucketLifecycle) UnmarshalBinary(b []byte) error {
var res AddMultiBucketLifecycle
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,138 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// BucketLifecycleResponse bucket lifecycle response
//
// swagger:model bucketLifecycleResponse
type BucketLifecycleResponse struct {
// lifecycle
Lifecycle []*ObjectBucketLifecycle `json:"lifecycle"`
}
// Validate validates this bucket lifecycle response
func (m *BucketLifecycleResponse) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateLifecycle(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *BucketLifecycleResponse) validateLifecycle(formats strfmt.Registry) error {
if swag.IsZero(m.Lifecycle) { // not required
return nil
}
for i := 0; i < len(m.Lifecycle); i++ {
if swag.IsZero(m.Lifecycle[i]) { // not required
continue
}
if m.Lifecycle[i] != nil {
if err := m.Lifecycle[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("lifecycle" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("lifecycle" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
// ContextValidate validate this bucket lifecycle response based on the context it is used
func (m *BucketLifecycleResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateLifecycle(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *BucketLifecycleResponse) contextValidateLifecycle(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.Lifecycle); i++ {
if m.Lifecycle[i] != nil {
if swag.IsZero(m.Lifecycle[i]) { // not required
return nil
}
if err := m.Lifecycle[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("lifecycle" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("lifecycle" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
// MarshalBinary interface implementation
func (m *BucketLifecycleResponse) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *BucketLifecycleResponse) UnmarshalBinary(b []byte) error {
var res BucketLifecycleResponse
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,82 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// ExpirationResponse expiration response
//
// swagger:model expirationResponse
type ExpirationResponse struct {
// date
Date string `json:"date,omitempty"`
// days
Days int64 `json:"days,omitempty"`
// delete all
DeleteAll bool `json:"delete_all,omitempty"`
// delete marker
DeleteMarker bool `json:"delete_marker,omitempty"`
// newer noncurrent expiration versions
NewerNoncurrentExpirationVersions int64 `json:"newer_noncurrent_expiration_versions,omitempty"`
// noncurrent expiration days
NoncurrentExpirationDays int64 `json:"noncurrent_expiration_days,omitempty"`
}
// Validate validates this expiration response
func (m *ExpirationResponse) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this expiration response based on context it is used
func (m *ExpirationResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *ExpirationResponse) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *ExpirationResponse) UnmarshalBinary(b []byte) error {
var res ExpirationResponse
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,70 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// LifecycleTag lifecycle tag
//
// swagger:model lifecycleTag
type LifecycleTag struct {
// key
Key string `json:"key,omitempty"`
// value
Value string `json:"value,omitempty"`
}
// Validate validates this lifecycle tag
func (m *LifecycleTag) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this lifecycle tag based on context it is used
func (m *LifecycleTag) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *LifecycleTag) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *LifecycleTag) UnmarshalBinary(b []byte) error {
var res LifecycleTag
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,138 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// MultiLifecycleResult multi lifecycle result
//
// swagger:model multiLifecycleResult
type MultiLifecycleResult struct {
// results
Results []*MulticycleResultItem `json:"results"`
}
// Validate validates this multi lifecycle result
func (m *MultiLifecycleResult) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateResults(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *MultiLifecycleResult) validateResults(formats strfmt.Registry) error {
if swag.IsZero(m.Results) { // not required
return nil
}
for i := 0; i < len(m.Results); i++ {
if swag.IsZero(m.Results[i]) { // not required
continue
}
if m.Results[i] != nil {
if err := m.Results[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("results" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("results" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
// ContextValidate validate this multi lifecycle result based on the context it is used
func (m *MultiLifecycleResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateResults(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *MultiLifecycleResult) contextValidateResults(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.Results); i++ {
if m.Results[i] != nil {
if swag.IsZero(m.Results[i]) { // not required
return nil
}
if err := m.Results[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("results" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("results" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
// MarshalBinary interface implementation
func (m *MultiLifecycleResult) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *MultiLifecycleResult) UnmarshalBinary(b []byte) error {
var res MultiLifecycleResult
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,70 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// MulticycleResultItem multicycle result item
//
// swagger:model multicycleResultItem
type MulticycleResultItem struct {
// bucket name
BucketName string `json:"bucketName,omitempty"`
// error
Error string `json:"error,omitempty"`
}
// Validate validates this multicycle result item
func (m *MulticycleResultItem) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this multicycle result item based on context it is used
func (m *MulticycleResultItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *MulticycleResultItem) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *MulticycleResultItem) UnmarshalBinary(b []byte) error {
var res MulticycleResultItem
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,249 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// ObjectBucketLifecycle object bucket lifecycle
//
// swagger:model objectBucketLifecycle
type ObjectBucketLifecycle struct {
// expiration
Expiration *ExpirationResponse `json:"expiration,omitempty"`
// id
ID string `json:"id,omitempty"`
// prefix
Prefix string `json:"prefix,omitempty"`
// status
Status string `json:"status,omitempty"`
// tags
Tags []*LifecycleTag `json:"tags"`
// transition
Transition *TransitionResponse `json:"transition,omitempty"`
}
// Validate validates this object bucket lifecycle
func (m *ObjectBucketLifecycle) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateExpiration(formats); err != nil {
res = append(res, err)
}
if err := m.validateTags(formats); err != nil {
res = append(res, err)
}
if err := m.validateTransition(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *ObjectBucketLifecycle) validateExpiration(formats strfmt.Registry) error {
if swag.IsZero(m.Expiration) { // not required
return nil
}
if m.Expiration != nil {
if err := m.Expiration.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("expiration")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("expiration")
}
return err
}
}
return nil
}
func (m *ObjectBucketLifecycle) validateTags(formats strfmt.Registry) error {
if swag.IsZero(m.Tags) { // not required
return nil
}
for i := 0; i < len(m.Tags); i++ {
if swag.IsZero(m.Tags[i]) { // not required
continue
}
if m.Tags[i] != nil {
if err := m.Tags[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("tags" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("tags" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *ObjectBucketLifecycle) validateTransition(formats strfmt.Registry) error {
if swag.IsZero(m.Transition) { // not required
return nil
}
if m.Transition != nil {
if err := m.Transition.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("transition")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("transition")
}
return err
}
}
return nil
}
// ContextValidate validate this object bucket lifecycle based on the context it is used
func (m *ObjectBucketLifecycle) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateExpiration(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateTags(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateTransition(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *ObjectBucketLifecycle) contextValidateExpiration(ctx context.Context, formats strfmt.Registry) error {
if m.Expiration != nil {
if swag.IsZero(m.Expiration) { // not required
return nil
}
if err := m.Expiration.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("expiration")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("expiration")
}
return err
}
}
return nil
}
func (m *ObjectBucketLifecycle) contextValidateTags(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.Tags); i++ {
if m.Tags[i] != nil {
if swag.IsZero(m.Tags[i]) { // not required
return nil
}
if err := m.Tags[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("tags" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("tags" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *ObjectBucketLifecycle) contextValidateTransition(ctx context.Context, formats strfmt.Registry) error {
if m.Transition != nil {
if swag.IsZero(m.Transition) { // not required
return nil
}
if err := m.Transition.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("transition")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("transition")
}
return err
}
}
return nil
}
// MarshalBinary interface implementation
func (m *ObjectBucketLifecycle) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *ObjectBucketLifecycle) UnmarshalBinary(b []byte) error {
var res ObjectBucketLifecycle
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,343 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"encoding/json"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// Tier tier
//
// swagger:model tier
type Tier struct {
// azure
Azure *TierAzure `json:"azure,omitempty"`
// gcs
Gcs *TierGcs `json:"gcs,omitempty"`
// minio
Minio *TierMinio `json:"minio,omitempty"`
// s3
S3 *TierS3 `json:"s3,omitempty"`
// status
Status bool `json:"status,omitempty"`
// type
// Enum: [s3 gcs azure minio unsupported]
Type string `json:"type,omitempty"`
}
// Validate validates this tier
func (m *Tier) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateAzure(formats); err != nil {
res = append(res, err)
}
if err := m.validateGcs(formats); err != nil {
res = append(res, err)
}
if err := m.validateMinio(formats); err != nil {
res = append(res, err)
}
if err := m.validateS3(formats); err != nil {
res = append(res, err)
}
if err := m.validateType(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *Tier) validateAzure(formats strfmt.Registry) error {
if swag.IsZero(m.Azure) { // not required
return nil
}
if m.Azure != nil {
if err := m.Azure.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("azure")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("azure")
}
return err
}
}
return nil
}
func (m *Tier) validateGcs(formats strfmt.Registry) error {
if swag.IsZero(m.Gcs) { // not required
return nil
}
if m.Gcs != nil {
if err := m.Gcs.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("gcs")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("gcs")
}
return err
}
}
return nil
}
func (m *Tier) validateMinio(formats strfmt.Registry) error {
if swag.IsZero(m.Minio) { // not required
return nil
}
if m.Minio != nil {
if err := m.Minio.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("minio")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("minio")
}
return err
}
}
return nil
}
func (m *Tier) validateS3(formats strfmt.Registry) error {
if swag.IsZero(m.S3) { // not required
return nil
}
if m.S3 != nil {
if err := m.S3.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("s3")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("s3")
}
return err
}
}
return nil
}
var tierTypeTypePropEnum []interface{}
func init() {
var res []string
if err := json.Unmarshal([]byte(`["s3","gcs","azure","minio","unsupported"]`), &res); err != nil {
panic(err)
}
for _, v := range res {
tierTypeTypePropEnum = append(tierTypeTypePropEnum, v)
}
}
const (
// TierTypeS3 captures enum value "s3"
TierTypeS3 string = "s3"
// TierTypeGcs captures enum value "gcs"
TierTypeGcs string = "gcs"
// TierTypeAzure captures enum value "azure"
TierTypeAzure string = "azure"
// TierTypeMinio captures enum value "minio"
TierTypeMinio string = "minio"
// TierTypeUnsupported captures enum value "unsupported"
TierTypeUnsupported string = "unsupported"
)
// prop value enum
func (m *Tier) validateTypeEnum(path, location string, value string) error {
if err := validate.EnumCase(path, location, value, tierTypeTypePropEnum, true); err != nil {
return err
}
return nil
}
func (m *Tier) validateType(formats strfmt.Registry) error {
if swag.IsZero(m.Type) { // not required
return nil
}
// value enum
if err := m.validateTypeEnum("type", "body", m.Type); err != nil {
return err
}
return nil
}
// ContextValidate validate this tier based on the context it is used
func (m *Tier) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateAzure(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateGcs(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateMinio(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateS3(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *Tier) contextValidateAzure(ctx context.Context, formats strfmt.Registry) error {
if m.Azure != nil {
if swag.IsZero(m.Azure) { // not required
return nil
}
if err := m.Azure.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("azure")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("azure")
}
return err
}
}
return nil
}
func (m *Tier) contextValidateGcs(ctx context.Context, formats strfmt.Registry) error {
if m.Gcs != nil {
if swag.IsZero(m.Gcs) { // not required
return nil
}
if err := m.Gcs.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("gcs")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("gcs")
}
return err
}
}
return nil
}
func (m *Tier) contextValidateMinio(ctx context.Context, formats strfmt.Registry) error {
if m.Minio != nil {
if swag.IsZero(m.Minio) { // not required
return nil
}
if err := m.Minio.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("minio")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("minio")
}
return err
}
}
return nil
}
func (m *Tier) contextValidateS3(ctx context.Context, formats strfmt.Registry) error {
if m.S3 != nil {
if swag.IsZero(m.S3) { // not required
return nil
}
if err := m.S3.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("s3")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("s3")
}
return err
}
}
return nil
}
// MarshalBinary interface implementation
func (m *Tier) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *Tier) UnmarshalBinary(b []byte) error {
var res Tier
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,94 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// TierAzure tier azure
//
// swagger:model tier_azure
type TierAzure struct {
// accountkey
Accountkey string `json:"accountkey,omitempty"`
// accountname
Accountname string `json:"accountname,omitempty"`
// bucket
Bucket string `json:"bucket,omitempty"`
// endpoint
Endpoint string `json:"endpoint,omitempty"`
// name
Name string `json:"name,omitempty"`
// objects
Objects string `json:"objects,omitempty"`
// prefix
Prefix string `json:"prefix,omitempty"`
// region
Region string `json:"region,omitempty"`
// usage
Usage string `json:"usage,omitempty"`
// versions
Versions string `json:"versions,omitempty"`
}
// Validate validates this tier azure
func (m *TierAzure) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this tier azure based on context it is used
func (m *TierAzure) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *TierAzure) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *TierAzure) UnmarshalBinary(b []byte) error {
var res TierAzure
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,73 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// TierCredentialsRequest tier credentials request
//
// swagger:model tierCredentialsRequest
type TierCredentialsRequest struct {
// access key
AccessKey string `json:"access_key,omitempty"`
// a base64 encoded value
Creds string `json:"creds,omitempty"`
// secret key
SecretKey string `json:"secret_key,omitempty"`
}
// Validate validates this tier credentials request
func (m *TierCredentialsRequest) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this tier credentials request based on context it is used
func (m *TierCredentialsRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *TierCredentialsRequest) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *TierCredentialsRequest) UnmarshalBinary(b []byte) error {
var res TierCredentialsRequest
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,91 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// TierGcs tier gcs
//
// swagger:model tier_gcs
type TierGcs struct {
// bucket
Bucket string `json:"bucket,omitempty"`
// creds
Creds string `json:"creds,omitempty"`
// endpoint
Endpoint string `json:"endpoint,omitempty"`
// name
Name string `json:"name,omitempty"`
// objects
Objects string `json:"objects,omitempty"`
// prefix
Prefix string `json:"prefix,omitempty"`
// region
Region string `json:"region,omitempty"`
// usage
Usage string `json:"usage,omitempty"`
// versions
Versions string `json:"versions,omitempty"`
}
// Validate validates this tier gcs
func (m *TierGcs) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this tier gcs based on context it is used
func (m *TierGcs) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *TierGcs) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *TierGcs) UnmarshalBinary(b []byte) error {
var res TierGcs
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,138 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// TierListResponse tier list response
//
// swagger:model tierListResponse
type TierListResponse struct {
// items
Items []*Tier `json:"items"`
}
// Validate validates this tier list response
func (m *TierListResponse) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateItems(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *TierListResponse) validateItems(formats strfmt.Registry) error {
if swag.IsZero(m.Items) { // not required
return nil
}
for i := 0; i < len(m.Items); i++ {
if swag.IsZero(m.Items[i]) { // not required
continue
}
if m.Items[i] != nil {
if err := m.Items[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("items" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("items" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
// ContextValidate validate this tier list response based on the context it is used
func (m *TierListResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateItems(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *TierListResponse) contextValidateItems(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.Items); i++ {
if m.Items[i] != nil {
if swag.IsZero(m.Items[i]) { // not required
return nil
}
if err := m.Items[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("items" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("items" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
// MarshalBinary interface implementation
func (m *TierListResponse) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *TierListResponse) UnmarshalBinary(b []byte) error {
var res TierListResponse
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,97 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// TierMinio tier minio
//
// swagger:model tier_minio
type TierMinio struct {
// accesskey
Accesskey string `json:"accesskey,omitempty"`
// bucket
Bucket string `json:"bucket,omitempty"`
// endpoint
Endpoint string `json:"endpoint,omitempty"`
// name
Name string `json:"name,omitempty"`
// objects
Objects string `json:"objects,omitempty"`
// prefix
Prefix string `json:"prefix,omitempty"`
// region
Region string `json:"region,omitempty"`
// secretkey
Secretkey string `json:"secretkey,omitempty"`
// storageclass
Storageclass string `json:"storageclass,omitempty"`
// usage
Usage string `json:"usage,omitempty"`
// versions
Versions string `json:"versions,omitempty"`
}
// Validate validates this tier minio
func (m *TierMinio) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this tier minio based on context it is used
func (m *TierMinio) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *TierMinio) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *TierMinio) UnmarshalBinary(b []byte) error {
var res TierMinio
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,97 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// TierS3 tier s3
//
// swagger:model tier_s3
type TierS3 struct {
// accesskey
Accesskey string `json:"accesskey,omitempty"`
// bucket
Bucket string `json:"bucket,omitempty"`
// endpoint
Endpoint string `json:"endpoint,omitempty"`
// name
Name string `json:"name,omitempty"`
// objects
Objects string `json:"objects,omitempty"`
// prefix
Prefix string `json:"prefix,omitempty"`
// region
Region string `json:"region,omitempty"`
// secretkey
Secretkey string `json:"secretkey,omitempty"`
// storageclass
Storageclass string `json:"storageclass,omitempty"`
// usage
Usage string `json:"usage,omitempty"`
// versions
Versions string `json:"versions,omitempty"`
}
// Validate validates this tier s3
func (m *TierS3) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this tier s3 based on context it is used
func (m *TierS3) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *TierS3) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *TierS3) UnmarshalBinary(b []byte) error {
var res TierS3
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,67 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// TiersNameListResponse tiers name list response
//
// swagger:model tiersNameListResponse
type TiersNameListResponse struct {
// items
Items []string `json:"items"`
}
// Validate validates this tiers name list response
func (m *TiersNameListResponse) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this tiers name list response based on context it is used
func (m *TiersNameListResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *TiersNameListResponse) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *TiersNameListResponse) UnmarshalBinary(b []byte) error {
var res TiersNameListResponse
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,79 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// TransitionResponse transition response
//
// swagger:model transitionResponse
type TransitionResponse struct {
// date
Date string `json:"date,omitempty"`
// days
Days int64 `json:"days,omitempty"`
// noncurrent storage class
NoncurrentStorageClass string `json:"noncurrent_storage_class,omitempty"`
// noncurrent transition days
NoncurrentTransitionDays int64 `json:"noncurrent_transition_days,omitempty"`
// storage class
StorageClass string `json:"storage_class,omitempty"`
}
// Validate validates this transition response
func (m *TransitionResponse) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this transition response based on context it is used
func (m *TransitionResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *TransitionResponse) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *TransitionResponse) UnmarshalBinary(b []byte) error {
var res TransitionResponse
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,157 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"encoding/json"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// UpdateBucketLifecycle update bucket lifecycle
//
// swagger:model updateBucketLifecycle
type UpdateBucketLifecycle struct {
// Non required, toggle to disable or enable rule
Disable bool `json:"disable,omitempty"`
// Non required, toggle to disable or enable rule
ExpiredObjectDeleteAll bool `json:"expired_object_delete_all,omitempty"`
// Non required, toggle to disable or enable rule
ExpiredObjectDeleteMarker bool `json:"expired_object_delete_marker,omitempty"`
// Required in case of expiry_date or transition fields are not set. it defines an expiry days for ILM
ExpiryDays int32 `json:"expiry_days,omitempty"`
// Non required, can be set in case of expiration is enabled
NoncurrentversionExpirationDays int32 `json:"noncurrentversion_expiration_days,omitempty"`
// Non required, can be set in case of transition is enabled
NoncurrentversionTransitionDays int32 `json:"noncurrentversion_transition_days,omitempty"`
// Non required, can be set in case of transition is enabled
NoncurrentversionTransitionStorageClass string `json:"noncurrentversion_transition_storage_class,omitempty"`
// Non required field, it matches a prefix to perform ILM operations on it
Prefix string `json:"prefix,omitempty"`
// Required only in case of transition is set. it refers to a tier
StorageClass string `json:"storage_class,omitempty"`
// Non required field, tags to match ILM files
Tags string `json:"tags,omitempty"`
// Required in case of transition_date or expiry fields are not set. it defines a transition days for ILM
TransitionDays int32 `json:"transition_days,omitempty"`
// ILM Rule type (Expiry or transition)
// Required: true
// Enum: [expiry transition]
Type *string `json:"type"`
}
// Validate validates this update bucket lifecycle
func (m *UpdateBucketLifecycle) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateType(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
var updateBucketLifecycleTypeTypePropEnum []interface{}
func init() {
var res []string
if err := json.Unmarshal([]byte(`["expiry","transition"]`), &res); err != nil {
panic(err)
}
for _, v := range res {
updateBucketLifecycleTypeTypePropEnum = append(updateBucketLifecycleTypeTypePropEnum, v)
}
}
const (
// UpdateBucketLifecycleTypeExpiry captures enum value "expiry"
UpdateBucketLifecycleTypeExpiry string = "expiry"
// UpdateBucketLifecycleTypeTransition captures enum value "transition"
UpdateBucketLifecycleTypeTransition string = "transition"
)
// prop value enum
func (m *UpdateBucketLifecycle) validateTypeEnum(path, location string, value string) error {
if err := validate.EnumCase(path, location, value, updateBucketLifecycleTypeTypePropEnum, true); err != nil {
return err
}
return nil
}
func (m *UpdateBucketLifecycle) validateType(formats strfmt.Registry) error {
if err := validate.Required("type", "body", m.Type); err != nil {
return err
}
// value enum
if err := m.validateTypeEnum("type", "body", *m.Type); err != nil {
return err
}
return nil
}
// ContextValidate validates this update bucket lifecycle based on context it is used
func (m *UpdateBucketLifecycle) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *UpdateBucketLifecycle) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *UpdateBucketLifecycle) UnmarshalBinary(b []byte) error {
var res UpdateBucketLifecycle
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1153,121 +1153,6 @@ paths:
tags: tags:
- Bucket - Bucket
/buckets/{bucket_name}/lifecycle:
get:
summary: Bucket Lifecycle
operationId: GetBucketLifecycle
parameters:
- name: bucket_name
in: path
required: true
type: string
responses:
200:
description: A successful response.
schema:
$ref: "#/definitions/bucketLifecycleResponse"
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Bucket
post:
summary: Add Bucket Lifecycle
operationId: AddBucketLifecycle
parameters:
- name: bucket_name
in: path
required: true
type: string
- name: body
in: body
required: true
schema:
$ref: "#/definitions/addBucketLifecycle"
responses:
201:
description: A successful response.
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Bucket
/buckets/multi-lifecycle:
post:
summary: Add Multi Bucket Lifecycle
operationId: AddMultiBucketLifecycle
parameters:
- name: body
in: body
required: true
schema:
$ref: "#/definitions/addMultiBucketLifecycle"
responses:
200:
description: A successful response.
schema:
$ref: "#/definitions/multiLifecycleResult"
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Bucket
/buckets/{bucket_name}/lifecycle/{lifecycle_id}:
put:
summary: Update Lifecycle rule
operationId: UpdateBucketLifecycle
parameters:
- name: bucket_name
in: path
required: true
type: string
- name: lifecycle_id
in: path
required: true
type: string
- name: body
in: body
required: true
schema:
$ref: "#/definitions/updateBucketLifecycle"
responses:
200:
description: A successful response.
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Bucket
delete:
summary: Delete Lifecycle rule
operationId: DeleteBucketLifecycleRule
parameters:
- name: bucket_name
in: path
required: true
type: string
- name: lifecycle_id
in: path
required: true
type: string
responses:
204:
description: A successful response.
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Bucket
/buckets/{bucket_name}/rewind/{date}: /buckets/{bucket_name}/rewind/{date}:
get: get:
summary: Get objects in a bucket for a rewind date summary: Get objects in a bucket for a rewind date
@@ -2394,137 +2279,6 @@ paths:
tags: tags:
- Configuration - Configuration
/admin/tiers:
get:
summary: Returns a list of tiers for ilm
operationId: TiersList
responses:
200:
description: A successful response.
schema:
$ref: "#/definitions/tierListResponse"
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Tiering
post:
summary: Allows to configure a new tier
operationId: AddTier
parameters:
- name: body
in: body
required: true
schema:
$ref: "#/definitions/tier"
responses:
201:
description: A successful response.
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Tiering
/admin/tiers/names:
get:
summary: Returns a list of tiers' names for ilm
operationId: TiersListNames
responses:
200:
description: A successful response.
schema:
$ref: "#/definitions/tiersNameListResponse"
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Tiering
/admin/tiers/{type}/{name}:
get:
summary: Get Tier
operationId: GetTier
parameters:
- name: type
in: path
required: true
type: string
enum:
- s3
- gcs
- azure
- minio
- name: name
in: path
required: true
type: string
responses:
200:
description: A successful response.
schema:
$ref: "#/definitions/tier"
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Tiering
/admin/tiers/{type}/{name}/credentials:
put:
summary: Edit Tier Credentials
operationId: EditTierCredentials
parameters:
- name: type
in: path
required: true
type: string
enum:
- s3
- gcs
- azure
- minio
- name: name
in: path
required: true
type: string
- name: body
in: body
required: true
schema:
$ref: "#/definitions/tierCredentialsRequest"
responses:
200:
description: A successful response.
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Tiering
/admin/tiers/{name}/remove:
delete:
summary: Remove Tier
operationId: RemoveTier
parameters:
- name: name
in: path
required: true
type: string
responses:
204:
description: A successful response.
default:
description: Generic error response.
schema:
$ref: "#/definitions/ApiError"
tags:
- Tiering
/nodes: /nodes:
get: get:
summary: Lists Nodes summary: Lists Nodes
@@ -4601,254 +4355,6 @@ definitions:
type: integer type: integer
format: int32 format: int32
bucketLifecycleResponse:
type: object
properties:
lifecycle:
type: array
items:
$ref: "#/definitions/objectBucketLifecycle"
expirationResponse:
type: object
properties:
date:
type: string
days:
type: integer
format: int64
delete_marker:
type: boolean
delete_all:
type: boolean
noncurrent_expiration_days:
type: integer
format: int64
newer_noncurrent_expiration_versions:
type: integer
format: int64
transitionResponse:
type: object
properties:
date:
type: string
storage_class:
type: string
days:
type: integer
format: int64
noncurrent_transition_days:
type: integer
format: int64
noncurrent_storage_class:
type: string
lifecycleTag:
type: object
properties:
key:
type: string
value:
type: string
objectBucketLifecycle:
type: object
properties:
id:
type: string
prefix:
type: string
status:
type: string
expiration:
$ref: "#/definitions/expirationResponse"
transition:
$ref: "#/definitions/transitionResponse"
tags:
type: array
items:
$ref: "#/definitions/lifecycleTag"
addBucketLifecycle:
type: object
properties:
type:
description: ILM Rule type (Expiry or transition)
type: string
enum:
- expiry
- transition
prefix:
description: Non required field, it matches a prefix to perform ILM operations on it
type: string
tags:
description: Non required field, tags to match ILM files
type: string
expiry_days:
description: Required in case of expiry_date or transition fields are not set. it defines an expiry days for ILM
type: integer
format: int32
default: 0
transition_days:
description: Required in case of transition_date or expiry fields are not set. it defines a transition days for ILM
type: integer
format: int32
default: 0
storage_class:
description: Required only in case of transition is set. it refers to a tier
type: string
disable:
description: Non required, toggle to disable or enable rule
type: boolean
expired_object_delete_marker:
description: Non required, toggle to disable or enable rule
type: boolean
expired_object_delete_all:
description: Non required, toggle to disable or enable rule
type: boolean
noncurrentversion_expiration_days:
description: Non required, can be set in case of expiration is enabled
type: integer
format: int32
default: 0
noncurrentversion_transition_days:
description: Non required, can be set in case of transition is enabled
type: integer
format: int32
default: 0
newer_noncurrentversion_expiration_versions:
description: Non required, can be set in case of expiration is enabled
type: integer
format: int32
default: 0
noncurrentversion_transition_storage_class:
description: Non required, can be set in case of transition is enabled
type: string
updateBucketLifecycle:
type: object
required:
- type
properties:
type:
description: ILM Rule type (Expiry or transition)
type: string
enum:
- expiry
- transition
prefix:
description: Non required field, it matches a prefix to perform ILM operations on it
type: string
tags:
description: Non required field, tags to match ILM files
type: string
expiry_days:
description: Required in case of expiry_date or transition fields are not set. it defines an expiry days for ILM
type: integer
format: int32
default: 0
transition_days:
description: Required in case of transition_date or expiry fields are not set. it defines a transition days for ILM
type: integer
format: int32
default: 0
storage_class:
description: Required only in case of transition is set. it refers to a tier
type: string
disable:
description: Non required, toggle to disable or enable rule
type: boolean
expired_object_delete_marker:
description: Non required, toggle to disable or enable rule
type: boolean
expired_object_delete_all:
description: Non required, toggle to disable or enable rule
type: boolean
noncurrentversion_expiration_days:
description: Non required, can be set in case of expiration is enabled
type: integer
format: int32
default: 0
noncurrentversion_transition_days:
description: Non required, can be set in case of transition is enabled
type: integer
format: int32
default: 0
noncurrentversion_transition_storage_class:
description: Non required, can be set in case of transition is enabled
type: string
addMultiBucketLifecycle:
type: object
required:
- buckets
- type
properties:
buckets:
type: array
items:
type: string
type:
description: ILM Rule type (Expiry or transition)
type: string
enum:
- expiry
- transition
prefix:
description: Non required field, it matches a prefix to perform ILM operations on it
type: string
tags:
description: Non required field, tags to match ILM files
type: string
expiry_days:
description: Required in case of expiry_date or transition fields are not set. it defines an expiry days for ILM
type: integer
format: int32
default: 0
transition_days:
description: Required in case of transition_date or expiry fields are not set. it defines a transition days for ILM
type: integer
format: int32
default: 0
storage_class:
description: Required only in case of transition is set. it refers to a tier
type: string
expired_object_delete_marker:
description: Non required, toggle to disable or enable rule
type: boolean
expired_object_delete_all:
description: Non required, toggle to disable or enable rule
type: boolean
noncurrentversion_expiration_days:
description: Non required, can be set in case of expiration is enabled
type: integer
format: int32
default: 0
noncurrentversion_transition_days:
description: Non required, can be set in case of transition is enabled
type: integer
format: int32
default: 0
noncurrentversion_transition_storage_class:
description: Non required, can be set in case of transition is enabled
type: string
multicycleResultItem:
type: object
properties:
bucketName:
type: string
error:
type: string
multiLifecycleResult:
properties:
results:
type: array
items:
$ref: "#/definitions/multicycleResultItem"
prefixAccessPair: prefixAccessPair:
type: object type: object
properties: properties:
@@ -4910,104 +4416,6 @@ definitions:
bucket_name: bucket_name:
type: string type: string
tier_s3:
type: object
properties:
name:
type: string
endpoint:
type: string
accesskey:
type: string
secretkey:
type: string
bucket:
type: string
prefix:
type: string
region:
type: string
storageclass:
type: string
usage:
type: string
objects:
type: string
versions:
type: string
tier_minio:
type: object
properties:
name:
type: string
endpoint:
type: string
accesskey:
type: string
secretkey:
type: string
bucket:
type: string
prefix:
type: string
region:
type: string
storageclass:
type: string
usage:
type: string
objects:
type: string
versions:
type: string
tier_azure:
type: object
properties:
name:
type: string
endpoint:
type: string
accountname:
type: string
accountkey:
type: string
bucket:
type: string
prefix:
type: string
region:
type: string
usage:
type: string
objects:
type: string
versions:
type: string
tier_gcs:
type: object
properties:
name:
type: string
endpoint:
type: string
creds:
type: string
bucket:
type: string
prefix:
type: string
region:
type: string
usage:
type: string
objects:
type: string
versions:
type: string
deleteFile: deleteFile:
type: object type: object
properties: properties:
@@ -5028,59 +4436,6 @@ definitions:
recursive: recursive:
type: boolean type: boolean
tier:
type: object
properties:
status:
type: boolean
type:
type: string
enum:
- s3
- gcs
- azure
- minio
- unsupported
s3:
type: object
$ref: "#/definitions/tier_s3"
gcs:
type: object
$ref: "#/definitions/tier_gcs"
azure:
type: object
$ref: "#/definitions/tier_azure"
minio:
type: object
$ref: "#/definitions/tier_minio"
tierListResponse:
type: object
properties:
items:
type: array
items:
$ref: "#/definitions/tier"
tiersNameListResponse:
type: object
properties:
items:
type: array
items:
type: string
tierCredentialsRequest:
type: object
properties:
access_key:
type: string
secret_key:
type: string
creds:
type: string
description: a base64 encoded value
rewindItem: rewindItem:
type: object type: object
properties: properties:

View File

@@ -1,112 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2023 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { expect, Page } from "@playwright/test";
import { test as baseTest } from "./fixtures/baseFixture";
import { minioadminFile } from "./consts";
import { BucketsListPage } from "./pom/BucketsListPage";
import { CreateBucketPage } from "./pom/CreateBucketPage";
import { BucketSummaryPage } from "./pom/BucketSummaryPage";
type LifeCycleObjectVersionFx = {
activeBucketName: string;
bucketsListPage: BucketsListPage;
createBucketPage: CreateBucketPage;
bucketSummaryPage: any;
};
const test = baseTest.extend<LifeCycleObjectVersionFx>({
activeBucketName: "",
bucketListPage: async ({ page }: { page: Page }, use: any) => {
let bucketListPage = new BucketsListPage(page);
await bucketListPage.loadPage();
await bucketListPage.goToCreateBucket();
await use(bucketListPage);
},
createBucketPage: async ({ page }: { page: Page }, use: any) => {
let createBucketPage = new CreateBucketPage(page);
await use(createBucketPage);
},
//bucket name is dynamic in parallel test runs.
bucketSummaryPage: async ({ page }: { page: Page }, use: any) => {
await use((bucketName: string) => {
return new BucketSummaryPage(page, bucketName);
});
},
});
test.use({ storageState: minioadminFile });
const versionedBucketName = "versioned-bucket";
const nonVersionedBucketName = "non-versioned-bucket";
test.describe("Add Lifecycle Rule Modal in bucket settings tests for object version ", () => {
test("Test if Object Version selector is present in Lifecycle rule modal", async ({
page,
bucketListPage,
createBucketPage,
bucketSummaryPage,
}) => {
await test.step("Create Versioned Bucket", async () => {
await createBucketPage.createVersionedBucket(versionedBucketName);
await bucketListPage.clickOnBucketRow(versionedBucketName);
bucketSummaryPage = bucketSummaryPage(versionedBucketName);
await bucketSummaryPage.clickOnTab("lifecycle"); //Tab Text is used.
});
await test.step("Check if object version option is available on a versioned bucket", async () => {
const objectVersionsEl = await bucketSummaryPage.getObjectVersionOption();
await expect(await objectVersionsEl).toHaveText("Current Version");
await expect(await objectVersionsEl).toBeTruthy();
await bucketSummaryPage.getLocator("#close").click();
});
await test.step("Clean up bucket and verify the clean up", async () => {
await bucketSummaryPage.confirmDeleteBucket();
const existBukCount =
await bucketListPage.isBucketExist(versionedBucketName);
await expect(existBukCount).toEqual(0);
});
});
test("Test if Object Version selector is NOT present in Lifecycle rule modal", async ({
page,
createBucketPage,
bucketListPage,
bucketSummaryPage,
}) => {
await test.step("Create NON Versioned Bucket and navigate to lifecycle settings in summary page", async () => {
await createBucketPage.createBucket(nonVersionedBucketName);
await bucketListPage.clickOnBucketRow(nonVersionedBucketName);
bucketSummaryPage = bucketSummaryPage(versionedBucketName);
await bucketSummaryPage.clickOnTab("lifecycle");
});
await test.step("Check if object version option is NOT available on a non versioned bucket", async () => {
const objectVersionsEl = await bucketSummaryPage.getObjectVersionOption();
await expect(await objectVersionsEl.count()).toEqual(0);
await bucketSummaryPage.getLocator("#close").click();
});
await test.step("Clean up bucket and verify the clean up", async () => {
await bucketSummaryPage.confirmDeleteBucket();
const existBukCount = await bucketListPage.isBucketExist(
nonVersionedBucketName,
);
await expect(existBukCount).toEqual(0);
});
});
});

View File

@@ -1,45 +0,0 @@
import { Page, Locator } from "@playwright/test";
export class BucketSummaryPage {
page: Page;
bucketName: string;
/* Locators */
deleteBucketBtn: Locator | undefined;
constructor(page: Page, bucketName: string) {
this.page = page;
this.bucketName = bucketName;
this.initLocators();
}
getLocator(selector: string): Locator {
const page = this.page;
const locator: Locator = page.locator(`${selector}`);
return locator;
}
initLocators() {
this.deleteBucketBtn = this.getLocator("#delete-bucket-button");
}
async loadPage() {
await this.clickOnTab(`Summary`);
}
async clickOnTab(tabID: string) {
await this.getLocator(`#${tabID}`).click();
// await page.goto(`${BUCKET_LIST_PAGE}/${this.bucketName}/admin/${tabName}`);
}
async confirmDeleteBucket() {
await this.getLocator("#delete-bucket-button").click();
await this.getLocator("#confirm-ok").click();
}
async getObjectVersionOption() {
await this.page.getByRole("button", { name: "Add Lifecycle Rule" }).click();
return this.getLocator("#object_version-select > div").nth(0);
}
}

View File

@@ -1,58 +0,0 @@
import { Page, Locator } from "@playwright/test";
import { BUCKET_LIST_PAGE } from "../consts";
export class BucketsListPage {
page: Page;
/* Locators */
createBucketBtn: Locator | undefined;
refreshBucketsBtn: Locator | undefined;
setReplicationBtn: Locator | undefined;
bucketListItemPrefix = "#manageBucket-";
constructor(page: Page) {
this.page = page;
this.initLocators();
}
getLocator(selector: string): Locator {
const page = this.page;
const locator: Locator = page.locator(`${selector}`);
return locator;
}
initLocators() {
this.createBucketBtn = this.getLocator("#create-bucket");
this.refreshBucketsBtn = this.getLocator("#refresh-buckets");
this.setReplicationBtn = this.getLocator("#set-replication");
}
locateBucket(bucketName: string): Locator {
const bucketRow = this.getLocator(
`${this.bucketListItemPrefix}${bucketName}`,
);
return bucketRow;
}
async clickOnBucketRow(bucketName: string) {
const bucketRow = this.locateBucket(bucketName);
await this.page.waitForTimeout(2500);
await this.refreshBucketsBtn.click();
await bucketRow.click();
}
async goToCreateBucket() {
await this.createBucketBtn?.click();
}
async isBucketExist(bucketName: string) {
const existBukCount = await this.locateBucket(bucketName).count();
return existBukCount;
}
async loadPage() {
const page = this.page;
await page.goto(BUCKET_LIST_PAGE);
}
}

View File

@@ -1,114 +0,0 @@
import { Page, Locator } from "@playwright/test";
import { BUCKET_LIST_PAGE } from "../consts";
export class CreateBucketPage {
page: Page;
/* Locators */
submitBtn: Locator | undefined;
clearBtn: Locator | undefined;
bucketNameInput: Locator | undefined;
versioningToggle: Locator | undefined;
lockingToggle: Locator | undefined;
quotaToggle: Locator | undefined;
bucketNamingRules: Locator | undefined;
bucketRetentionToggle: Locator | undefined;
quotaSizeInput: Locator | undefined;
retentionModeRadio: Locator | undefined;
retentionValidity: Locator | undefined;
constructor(page: Page) {
this.page = page;
this.initLocators();
}
getLocator(selector: string): Locator {
const page = this.page;
const locator: Locator = page.locator(`${selector}`);
return locator;
}
initLocators() {
this.submitBtn = this.getLocator("#create-bucket");
this.clearBtn = this.getLocator("#clear");
this.versioningToggle = this.getLocator("#versioned-switch");
this.lockingToggle = this.getLocator("#locking-switch");
this.quotaToggle = this.getLocator("#bucket_quota-switch");
this.bucketNamingRules = this.getLocator("#toggle-naming-rules");
this.bucketNameInput = this.getLocator("#bucket-name");
}
//Lazy/Conditional selectors Note: These respective methods must be called before using them.
onVersioningToggleOn() {
this.bucketRetentionToggle = this.getLocator("#bucket_retention");
}
onBucketQuotaToggleOn() {
this.quotaSizeInput = this.getLocator("#quota_size");
}
onRetentionToggleOn() {
this.retentionModeRadio = this.getLocator("#retention_mode");
this.retentionValidity = this.getLocator("#retention_validity");
}
loadPage() {
const page = this.page;
page.goto(BUCKET_LIST_PAGE);
}
async fillBucketName(bucketName: string) {
await this.bucketNameInput?.click();
await this.bucketNameInput?.fill(bucketName);
}
async toggleBucketNamingRules() {
await this.bucketNamingRules?.click();
}
async toggleVersioning() {
await this.versioningToggle?.check();
this.onVersioningToggleOn();
//expect to be on
}
async toggleObjectLocking() {
await this.lockingToggle?.click();
this.onVersioningToggleOn();
this.onRetentionToggleOn();
}
async toggleBucketQuota() {
await this.quotaToggle?.click();
this.onBucketQuotaToggleOn();
}
async toggleRetention() {
await this.bucketRetentionToggle?.click();
}
async submitForm() {
await this.submitBtn?.click();
}
//Convenience Methods for easy testing
//create a bucket without any features like versioning, locking, quota etc.
async createBucket(bucketName: string) {
await this.fillBucketName(bucketName);
await this.submitForm();
}
//create a bucket with versioning feature
async createVersionedBucket(bucketName: string) {
await this.fillBucketName(bucketName);
await this.toggleVersioning();
await this.submitForm();
}
//create a bucket with locking feature
async goToCreateBucket() {
await this.submitBtn?.click();
}
}

View File

@@ -894,189 +894,6 @@ export interface GetBucketRetentionConfig {
validity?: number; validity?: number;
} }
export interface BucketLifecycleResponse {
lifecycle?: ObjectBucketLifecycle[];
}
export interface ExpirationResponse {
date?: string;
/** @format int64 */
days?: number;
delete_marker?: boolean;
delete_all?: boolean;
/** @format int64 */
noncurrent_expiration_days?: number;
/** @format int64 */
newer_noncurrent_expiration_versions?: number;
}
export interface TransitionResponse {
date?: string;
storage_class?: string;
/** @format int64 */
days?: number;
/** @format int64 */
noncurrent_transition_days?: number;
noncurrent_storage_class?: string;
}
export interface LifecycleTag {
key?: string;
value?: string;
}
export interface ObjectBucketLifecycle {
id?: string;
prefix?: string;
status?: string;
expiration?: ExpirationResponse;
transition?: TransitionResponse;
tags?: LifecycleTag[];
}
export interface AddBucketLifecycle {
/** ILM Rule type (Expiry or transition) */
type?: "expiry" | "transition";
/** Non required field, it matches a prefix to perform ILM operations on it */
prefix?: string;
/** Non required field, tags to match ILM files */
tags?: string;
/**
* Required in case of expiry_date or transition fields are not set. it defines an expiry days for ILM
* @format int32
* @default 0
*/
expiry_days?: number;
/**
* Required in case of transition_date or expiry fields are not set. it defines a transition days for ILM
* @format int32
* @default 0
*/
transition_days?: number;
/** Required only in case of transition is set. it refers to a tier */
storage_class?: string;
/** Non required, toggle to disable or enable rule */
disable?: boolean;
/** Non required, toggle to disable or enable rule */
expired_object_delete_marker?: boolean;
/** Non required, toggle to disable or enable rule */
expired_object_delete_all?: boolean;
/**
* Non required, can be set in case of expiration is enabled
* @format int32
* @default 0
*/
noncurrentversion_expiration_days?: number;
/**
* Non required, can be set in case of transition is enabled
* @format int32
* @default 0
*/
noncurrentversion_transition_days?: number;
/**
* Non required, can be set in case of expiration is enabled
* @format int32
* @default 0
*/
newer_noncurrentversion_expiration_versions?: number;
/** Non required, can be set in case of transition is enabled */
noncurrentversion_transition_storage_class?: string;
}
export interface UpdateBucketLifecycle {
/** ILM Rule type (Expiry or transition) */
type: "expiry" | "transition";
/** Non required field, it matches a prefix to perform ILM operations on it */
prefix?: string;
/** Non required field, tags to match ILM files */
tags?: string;
/**
* Required in case of expiry_date or transition fields are not set. it defines an expiry days for ILM
* @format int32
* @default 0
*/
expiry_days?: number;
/**
* Required in case of transition_date or expiry fields are not set. it defines a transition days for ILM
* @format int32
* @default 0
*/
transition_days?: number;
/** Required only in case of transition is set. it refers to a tier */
storage_class?: string;
/** Non required, toggle to disable or enable rule */
disable?: boolean;
/** Non required, toggle to disable or enable rule */
expired_object_delete_marker?: boolean;
/** Non required, toggle to disable or enable rule */
expired_object_delete_all?: boolean;
/**
* Non required, can be set in case of expiration is enabled
* @format int32
* @default 0
*/
noncurrentversion_expiration_days?: number;
/**
* Non required, can be set in case of transition is enabled
* @format int32
* @default 0
*/
noncurrentversion_transition_days?: number;
/** Non required, can be set in case of transition is enabled */
noncurrentversion_transition_storage_class?: string;
}
export interface AddMultiBucketLifecycle {
buckets: string[];
/** ILM Rule type (Expiry or transition) */
type: "expiry" | "transition";
/** Non required field, it matches a prefix to perform ILM operations on it */
prefix?: string;
/** Non required field, tags to match ILM files */
tags?: string;
/**
* Required in case of expiry_date or transition fields are not set. it defines an expiry days for ILM
* @format int32
* @default 0
*/
expiry_days?: number;
/**
* Required in case of transition_date or expiry fields are not set. it defines a transition days for ILM
* @format int32
* @default 0
*/
transition_days?: number;
/** Required only in case of transition is set. it refers to a tier */
storage_class?: string;
/** Non required, toggle to disable or enable rule */
expired_object_delete_marker?: boolean;
/** Non required, toggle to disable or enable rule */
expired_object_delete_all?: boolean;
/**
* Non required, can be set in case of expiration is enabled
* @format int32
* @default 0
*/
noncurrentversion_expiration_days?: number;
/**
* Non required, can be set in case of transition is enabled
* @format int32
* @default 0
*/
noncurrentversion_transition_days?: number;
/** Non required, can be set in case of transition is enabled */
noncurrentversion_transition_storage_class?: string;
}
export interface MulticycleResultItem {
bucketName?: string;
error?: string;
}
export interface MultiLifecycleResult {
results?: MulticycleResultItem[];
}
export interface PrefixAccessPair { export interface PrefixAccessPair {
prefix?: string; prefix?: string;
access?: string; access?: string;
@@ -1116,59 +933,6 @@ export interface PolicyArgs {
bucket_name?: string; bucket_name?: string;
} }
export interface TierS3 {
name?: string;
endpoint?: string;
accesskey?: string;
secretkey?: string;
bucket?: string;
prefix?: string;
region?: string;
storageclass?: string;
usage?: string;
objects?: string;
versions?: string;
}
export interface TierMinio {
name?: string;
endpoint?: string;
accesskey?: string;
secretkey?: string;
bucket?: string;
prefix?: string;
region?: string;
storageclass?: string;
usage?: string;
objects?: string;
versions?: string;
}
export interface TierAzure {
name?: string;
endpoint?: string;
accountname?: string;
accountkey?: string;
bucket?: string;
prefix?: string;
region?: string;
usage?: string;
objects?: string;
versions?: string;
}
export interface TierGcs {
name?: string;
endpoint?: string;
creds?: string;
bucket?: string;
prefix?: string;
region?: string;
usage?: string;
objects?: string;
versions?: string;
}
export interface DeleteFile { export interface DeleteFile {
path?: string; path?: string;
versionID?: string; versionID?: string;
@@ -1181,30 +945,6 @@ export interface UserSAs {
recursive?: boolean; recursive?: boolean;
} }
export interface Tier {
status?: boolean;
type?: "s3" | "gcs" | "azure" | "minio" | "unsupported";
s3?: TierS3;
gcs?: TierGcs;
azure?: TierAzure;
minio?: TierMinio;
}
export interface TierListResponse {
items?: Tier[];
}
export interface TiersNameListResponse {
items?: string[];
}
export interface TierCredentialsRequest {
access_key?: string;
secret_key?: string;
/** a base64 encoded value */
creds?: string;
}
export interface RewindItem { export interface RewindItem {
last_modified?: string; last_modified?: string;
/** @format int64 */ /** @format int64 */
@@ -2729,115 +2469,6 @@ export class Api<
...params, ...params,
}), }),
/**
* No description
*
* @tags Bucket
* @name GetBucketLifecycle
* @summary Bucket Lifecycle
* @request GET:/buckets/{bucket_name}/lifecycle
* @secure
*/
getBucketLifecycle: (bucketName: string, params: RequestParams = {}) =>
this.request<BucketLifecycleResponse, ApiError>({
path: `/buckets/${encodeURIComponent(bucketName)}/lifecycle`,
method: "GET",
secure: true,
format: "json",
...params,
}),
/**
* No description
*
* @tags Bucket
* @name AddBucketLifecycle
* @summary Add Bucket Lifecycle
* @request POST:/buckets/{bucket_name}/lifecycle
* @secure
*/
addBucketLifecycle: (
bucketName: string,
body: AddBucketLifecycle,
params: RequestParams = {},
) =>
this.request<void, ApiError>({
path: `/buckets/${encodeURIComponent(bucketName)}/lifecycle`,
method: "POST",
body: body,
secure: true,
type: ContentType.Json,
...params,
}),
/**
* No description
*
* @tags Bucket
* @name AddMultiBucketLifecycle
* @summary Add Multi Bucket Lifecycle
* @request POST:/buckets/multi-lifecycle
* @secure
*/
addMultiBucketLifecycle: (
body: AddMultiBucketLifecycle,
params: RequestParams = {},
) =>
this.request<MultiLifecycleResult, ApiError>({
path: `/buckets/multi-lifecycle`,
method: "POST",
body: body,
secure: true,
type: ContentType.Json,
format: "json",
...params,
}),
/**
* No description
*
* @tags Bucket
* @name UpdateBucketLifecycle
* @summary Update Lifecycle rule
* @request PUT:/buckets/{bucket_name}/lifecycle/{lifecycle_id}
* @secure
*/
updateBucketLifecycle: (
bucketName: string,
lifecycleId: string,
body: UpdateBucketLifecycle,
params: RequestParams = {},
) =>
this.request<void, ApiError>({
path: `/buckets/${encodeURIComponent(bucketName)}/lifecycle/${encodeURIComponent(lifecycleId)}`,
method: "PUT",
body: body,
secure: true,
type: ContentType.Json,
...params,
}),
/**
* No description
*
* @tags Bucket
* @name DeleteBucketLifecycleRule
* @summary Delete Lifecycle rule
* @request DELETE:/buckets/{bucket_name}/lifecycle/{lifecycle_id}
* @secure
*/
deleteBucketLifecycleRule: (
bucketName: string,
lifecycleId: string,
params: RequestParams = {},
) =>
this.request<void, ApiError>({
path: `/buckets/${encodeURIComponent(bucketName)}/lifecycle/${encodeURIComponent(lifecycleId)}`,
method: "DELETE",
secure: true,
...params,
}),
/** /**
* No description * No description
* *
@@ -4073,124 +3704,6 @@ export class Api<
...params, ...params,
}), }),
/**
* No description
*
* @tags Tiering
* @name TiersList
* @summary Returns a list of tiers for ilm
* @request GET:/admin/tiers
* @secure
*/
tiersList: (params: RequestParams = {}) =>
this.request<TierListResponse, ApiError>({
path: `/admin/tiers`,
method: "GET",
secure: true,
format: "json",
...params,
}),
/**
* No description
*
* @tags Tiering
* @name AddTier
* @summary Allows to configure a new tier
* @request POST:/admin/tiers
* @secure
*/
addTier: (body: Tier, params: RequestParams = {}) =>
this.request<void, ApiError>({
path: `/admin/tiers`,
method: "POST",
body: body,
secure: true,
type: ContentType.Json,
...params,
}),
/**
* No description
*
* @tags Tiering
* @name TiersListNames
* @summary Returns a list of tiers' names for ilm
* @request GET:/admin/tiers/names
* @secure
*/
tiersListNames: (params: RequestParams = {}) =>
this.request<TiersNameListResponse, ApiError>({
path: `/admin/tiers/names`,
method: "GET",
secure: true,
format: "json",
...params,
}),
/**
* No description
*
* @tags Tiering
* @name GetTier
* @summary Get Tier
* @request GET:/admin/tiers/{type}/{name}
* @secure
*/
getTier: (
type: "s3" | "gcs" | "azure" | "minio",
name: string,
params: RequestParams = {},
) =>
this.request<Tier, ApiError>({
path: `/admin/tiers/${encodeURIComponent(type)}/${encodeURIComponent(name)}`,
method: "GET",
secure: true,
format: "json",
...params,
}),
/**
* No description
*
* @tags Tiering
* @name EditTierCredentials
* @summary Edit Tier Credentials
* @request PUT:/admin/tiers/{type}/{name}/credentials
* @secure
*/
editTierCredentials: (
type: "s3" | "gcs" | "azure" | "minio",
name: string,
body: TierCredentialsRequest,
params: RequestParams = {},
) =>
this.request<void, ApiError>({
path: `/admin/tiers/${encodeURIComponent(type)}/${encodeURIComponent(name)}/credentials`,
method: "PUT",
body: body,
secure: true,
type: ContentType.Json,
...params,
}),
/**
* No description
*
* @tags Tiering
* @name RemoveTier
* @summary Remove Tier
* @request DELETE:/admin/tiers/{name}/remove
* @secure
*/
removeTier: (name: string, params: RequestParams = {}) =>
this.request<void, ApiError>({
path: `/admin/tiers/${encodeURIComponent(name)}/remove`,
method: "DELETE",
secure: true,
...params,
}),
/** /**
* No description * No description
* *

View File

@@ -18,7 +18,6 @@ export const IAM_ROLES = {
BUCKET_OWNER: "BUCKET_OWNER", // upload/delete objects from the bucket BUCKET_OWNER: "BUCKET_OWNER", // upload/delete objects from the bucket
BUCKET_VIEWER: "BUCKET_VIEWER", // only view objects on the bucket BUCKET_VIEWER: "BUCKET_VIEWER", // only view objects on the bucket
BUCKET_ADMIN: "BUCKET_ADMIN", // administrate the bucket BUCKET_ADMIN: "BUCKET_ADMIN", // administrate the bucket
BUCKET_LIFECYCLE: "BUCKET_LIFECYCLE", // can manage bucket lifecycle
}; };
export const IAM_SCOPES = { export const IAM_SCOPES = {
@@ -51,8 +50,6 @@ export const IAM_SCOPES = {
S3_PUT_BUCKET_NOTIFICATIONS: "s3:PutBucketNotification", S3_PUT_BUCKET_NOTIFICATIONS: "s3:PutBucketNotification",
S3_GET_REPLICATION_CONFIGURATION: "s3:GetReplicationConfiguration", S3_GET_REPLICATION_CONFIGURATION: "s3:GetReplicationConfiguration",
S3_PUT_REPLICATION_CONFIGURATION: "s3:PutReplicationConfiguration", S3_PUT_REPLICATION_CONFIGURATION: "s3:PutReplicationConfiguration",
S3_GET_LIFECYCLE_CONFIGURATION: "s3:GetLifecycleConfiguration",
S3_PUT_LIFECYCLE_CONFIGURATION: "s3:PutLifecycleConfiguration",
S3_GET_BUCKET_OBJECT_LOCK_CONFIGURATION: S3_GET_BUCKET_OBJECT_LOCK_CONFIGURATION:
"s3:GetBucketObjectLockConfiguration", "s3:GetBucketObjectLockConfiguration",
S3_PUT_BUCKET_OBJECT_LOCK_CONFIGURATION: S3_PUT_BUCKET_OBJECT_LOCK_CONFIGURATION:
@@ -68,8 +65,6 @@ export const IAM_SCOPES = {
ADMIN_SERVER_INFO: "admin:ServerInfo", ADMIN_SERVER_INFO: "admin:ServerInfo",
ADMIN_GET_BUCKET_QUOTA: "admin:GetBucketQuota", ADMIN_GET_BUCKET_QUOTA: "admin:GetBucketQuota",
ADMIN_SET_BUCKET_QUOTA: "admin:SetBucketQuota", ADMIN_SET_BUCKET_QUOTA: "admin:SetBucketQuota",
ADMIN_LIST_TIERS: "admin:ListTier",
ADMIN_SET_TIER: "admin:SetTier",
ADMIN_LIST_GROUPS: "admin:ListGroups", ADMIN_LIST_GROUPS: "admin:ListGroups",
S3_GET_OBJECT_VERSION_FOR_REPLICATION: "s3:GetObjectVersionForReplication", S3_GET_OBJECT_VERSION_FOR_REPLICATION: "s3:GetObjectVersionForReplication",
S3_REPLICATE_TAGS: "s3:ReplicateTags", S3_REPLICATE_TAGS: "s3:ReplicateTags",
@@ -194,9 +189,6 @@ export const IAM_PAGES = {
EVENT_DESTINATIONS: "/settings/event-destinations", EVENT_DESTINATIONS: "/settings/event-destinations",
EVENT_DESTINATIONS_ADD: "/settings/event-destinations/add", EVENT_DESTINATIONS_ADD: "/settings/event-destinations/add",
EVENT_DESTINATIONS_ADD_SERVICE: "/settings/event-destinations/add/:service", EVENT_DESTINATIONS_ADD_SERVICE: "/settings/event-destinations/add/:service",
TIERS: "/settings/tiers",
TIERS_ADD: "/settings/tiers/add",
TIERS_ADD_SERVICE: "/settings/tiers/add/:service",
}; };
// roles // roles
@@ -242,8 +234,6 @@ export const IAM_PERMISSIONS = {
IAM_SCOPES.S3_BYPASS_GOVERNANCE_RETENTION, IAM_SCOPES.S3_BYPASS_GOVERNANCE_RETENTION,
IAM_SCOPES.S3_PUT_BUCKET_POLICY, IAM_SCOPES.S3_PUT_BUCKET_POLICY,
IAM_SCOPES.S3_PUT_BUCKET_NOTIFICATIONS, IAM_SCOPES.S3_PUT_BUCKET_NOTIFICATIONS,
IAM_SCOPES.S3_GET_LIFECYCLE_CONFIGURATION,
IAM_SCOPES.S3_PUT_LIFECYCLE_CONFIGURATION,
IAM_SCOPES.S3_LIST_MULTIPART_UPLOAD_PARTS, IAM_SCOPES.S3_LIST_MULTIPART_UPLOAD_PARTS,
IAM_SCOPES.S3_LISTEN_BUCKET_NOTIFICATIONS, IAM_SCOPES.S3_LISTEN_BUCKET_NOTIFICATIONS,
IAM_SCOPES.S3_LISTEN_NOTIFICATIONS, IAM_SCOPES.S3_LISTEN_NOTIFICATIONS,
@@ -267,14 +257,6 @@ export const IAM_PERMISSIONS = {
IAM_SCOPES.S3_GET_ACTIONS, IAM_SCOPES.S3_GET_ACTIONS,
IAM_SCOPES.S3_PUT_ACTIONS, IAM_SCOPES.S3_PUT_ACTIONS,
], ],
[IAM_ROLES.BUCKET_LIFECYCLE]: [
IAM_SCOPES.S3_GET_LIFECYCLE_CONFIGURATION,
IAM_SCOPES.S3_PUT_LIFECYCLE_CONFIGURATION,
IAM_SCOPES.S3_GET_ACTIONS,
IAM_SCOPES.S3_PUT_ACTIONS,
IAM_SCOPES.ADMIN_LIST_TIERS,
IAM_SCOPES.ADMIN_SET_TIER,
],
}; };
// application pages/routes and required scopes/roles // application pages/routes and required scopes/roles
@@ -366,17 +348,6 @@ export const IAM_PAGES_PERMISSIONS = {
IAM_SCOPES.ADMIN_SERVER_INFO, // displays notifications endpoints IAM_SCOPES.ADMIN_SERVER_INFO, // displays notifications endpoints
IAM_SCOPES.ADMIN_CONFIG_UPDATE, // displays create notification button IAM_SCOPES.ADMIN_CONFIG_UPDATE, // displays create notification button
], ],
[IAM_PAGES.TIERS]: [
IAM_SCOPES.ADMIN_LIST_TIERS, // display tiers list
],
[IAM_PAGES.TIERS_ADD]: [
IAM_SCOPES.ADMIN_SET_TIER, // display "add tier" button / shows add service tier page
IAM_SCOPES.ADMIN_LIST_TIERS, // display tiers list
],
[IAM_PAGES.TIERS_ADD_SERVICE]: [
IAM_SCOPES.ADMIN_SET_TIER, // display "add tier" button / shows add service tier page
IAM_SCOPES.ADMIN_LIST_TIERS, // display tiers list
],
[IAM_PAGES.TOOLS_LOGS]: [IAM_SCOPES.ADMIN_GET_CONSOLE_LOG], [IAM_PAGES.TOOLS_LOGS]: [IAM_SCOPES.ADMIN_GET_CONSOLE_LOG],
[IAM_PAGES.TOOLS_AUDITLOGS]: [IAM_SCOPES.ADMIN_HEALTH_INFO], [IAM_PAGES.TOOLS_AUDITLOGS]: [IAM_SCOPES.ADMIN_HEALTH_INFO],
[IAM_PAGES.TOOLS_WATCH]: [ [IAM_PAGES.TOOLS_WATCH]: [

View File

@@ -1,493 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { Fragment, useEffect, useState } from "react";
import get from "lodash/get";
import {
Accordion,
AlertIcon,
Button,
FormLayout,
Grid,
HelpTip,
InputBox,
LifecycleConfigIcon,
ProgressBar,
RadioGroup,
Select,
Switch,
} from "mds";
import { useSelector } from "react-redux";
import { api } from "api";
import { BucketVersioningResponse } from "api/consoleApi";
import { errorToHandler } from "api/errors";
import { modalStyleUtils } from "../../Common/FormComponents/common/styleLibrary";
import { selDistSet, setModalErrorSnackMessage } from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
import { ITiersDropDown } from "../types";
import ModalWrapper from "../../Common/ModalWrapper/ModalWrapper";
import QueryMultiSelector from "../../Common/FormComponents/QueryMultiSelector/QueryMultiSelector";
import InputUnitMenu from "../../Common/FormComponents/InputUnitMenu/InputUnitMenu";
import { IAM_PAGES } from "common/SecureComponent/permissions";
interface IReplicationModal {
open: boolean;
closeModalAndRefresh: (refresh: boolean) => any;
bucketName: string;
}
const AddLifecycleModal = ({
open,
closeModalAndRefresh,
bucketName,
}: IReplicationModal) => {
const dispatch = useAppDispatch();
const distributedSetup = useSelector(selDistSet);
const [loadingTiers, setLoadingTiers] = useState<boolean>(true);
const [tiersList, setTiersList] = useState<ITiersDropDown[]>([]);
const [addLoading, setAddLoading] = useState(false);
const [versioningInfo, setVersioningInfo] =
useState<BucketVersioningResponse | null>(null);
const [prefix, setPrefix] = useState("");
const [tags, setTags] = useState<string>("");
const [storageClass, setStorageClass] = useState("");
const [ilmType, setIlmType] = useState<"expiry" | "transition">("expiry");
const [targetVersion, setTargetVersion] = useState<"current" | "noncurrent">(
"current",
);
const [lifecycleDays, setLifecycleDays] = useState<string>("");
const [isFormValid, setIsFormValid] = useState<boolean>(false);
const [expiredObjectDM, setExpiredObjectDM] = useState<boolean>(false);
const [expiredAllVersionsDM, setExpiredAllVersionsDM] =
useState<boolean>(false);
const [loadingVersioning, setLoadingVersioning] = useState<boolean>(true);
const [expandedAdv, setExpandedAdv] = useState<boolean>(false);
const [expanded, setExpanded] = useState<boolean>(false);
const [expiryUnit, setExpiryUnit] = useState<string>("days");
/*To be removed on component replacement*/
const formFieldRowFilter = {
"& .MuiPaper-root": { padding: 0 },
};
useEffect(() => {
if (loadingTiers) {
api.admin
.tiersListNames()
.then((res) => {
const tiersList: string[] | null = get(res.data, "items", []);
if (tiersList !== null && tiersList.length >= 1) {
const objList = tiersList.map((tierName: string) => {
return { label: tierName, value: tierName };
});
setTiersList(objList);
if (objList.length > 0) {
setStorageClass(objList[0].value);
}
}
setLoadingTiers(false);
})
.catch((err) => {
setLoadingTiers(false);
dispatch(setModalErrorSnackMessage(errorToHandler(err.error)));
});
}
}, [dispatch, loadingTiers]);
useEffect(() => {
let valid = true;
if (ilmType !== "expiry") {
if (storageClass === "") {
valid = false;
}
}
if (!lifecycleDays || parseInt(lifecycleDays) === 0) {
valid = false;
}
if (parseInt(lifecycleDays) > 2147483647) {
//values over int32 cannot be parsed
valid = false;
}
setIsFormValid(valid);
}, [ilmType, lifecycleDays, storageClass]);
useEffect(() => {
if (loadingVersioning && distributedSetup) {
api.buckets
.getBucketVersioning(bucketName)
.then((res) => {
setVersioningInfo(res.data);
setLoadingVersioning(false);
})
.catch((err) => {
dispatch(setModalErrorSnackMessage(errorToHandler(err)));
setLoadingVersioning(false);
});
}
}, [loadingVersioning, dispatch, bucketName, distributedSetup]);
const addRecord = () => {
let rules = {};
if (ilmType === "expiry") {
let expiry: { [key: string]: number } = {};
if (targetVersion === "current") {
expiry["expiry_days"] = parseInt(lifecycleDays);
} else if (expiryUnit === "days") {
expiry["noncurrentversion_expiration_days"] = parseInt(lifecycleDays);
} else {
expiry["newer_noncurrentversion_expiration_versions"] =
parseInt(lifecycleDays);
}
rules = {
...expiry,
};
} else {
let transition: { [key: string]: number | string } = {};
if (targetVersion === "current") {
transition["transition_days"] = parseInt(lifecycleDays);
transition["storage_class"] = storageClass;
} else if (expiryUnit === "days") {
transition["noncurrentversion_transition_days"] =
parseInt(lifecycleDays);
transition["noncurrentversion_transition_storage_class"] = storageClass;
}
rules = {
...transition,
};
}
const lifecycleInsert = {
type: ilmType,
prefix,
tags,
expired_object_delete_marker: expiredObjectDM,
expired_object_delete_all: expiredAllVersionsDM,
...rules,
};
api.buckets
.addBucketLifecycle(bucketName, lifecycleInsert)
.then(() => {
setAddLoading(false);
closeModalAndRefresh(true);
})
.catch((err) => {
setAddLoading(false);
dispatch(setModalErrorSnackMessage(errorToHandler(err)));
});
};
return (
<ModalWrapper
modalOpen={open}
onClose={() => {
closeModalAndRefresh(false);
}}
title="Add Lifecycle Rule"
titleIcon={<LifecycleConfigIcon />}
>
{loadingTiers && (
<Grid container>
<Grid item xs={12}>
<ProgressBar />
</Grid>
</Grid>
)}
{!loadingTiers && (
<form
noValidate
autoComplete="off"
onSubmit={(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setAddLoading(true);
addRecord();
}}
>
<FormLayout withBorders={false} containerPadding={false}>
<RadioGroup
currentValue={ilmType}
id="ilm_type"
name="ilm_type"
label="Type of Lifecycle"
onChange={(e) => {
setIlmType(e.target.value as "expiry" | "transition");
}}
selectorOptions={[
{ value: "expiry", label: "Expiry" },
{ value: "transition", label: "Transition" },
]}
helpTip={
<Fragment>
Select{" "}
<a
target="blank"
href="https://min.io/docs/minio/kubernetes/upstream/administration/object-management/create-lifecycle-management-expiration-rule.html"
>
Expiry
</a>{" "}
to delete Objects per this rule. Select{" "}
<a
target="blank"
href="https://min.io/docs/minio/kubernetes/upstream/administration/object-management/transition-objects-to-minio.html"
>
Transition
</a>{" "}
to move Objects to a remote storage{" "}
<a
target="blank"
href="https://min.io/docs/minio/windows/administration/object-management/transition-objects-to-minio.html#configure-the-remote-storage-tier"
>
Tier
</a>{" "}
per this rule.
</Fragment>
}
helpTipPlacement="right"
/>
{versioningInfo?.status === "Enabled" && (
<Select
value={targetVersion}
id="object_version"
name="object_version"
label="Object Version"
onChange={(value) => {
setTargetVersion(value as "current" | "noncurrent");
}}
options={[
{ value: "current", label: "Current Version" },
{ value: "noncurrent", label: "Non-Current Version" },
]}
helpTip={
<Fragment>
Select whether to apply the rule to current or non-current
Object
<a
target="blank"
href="https://min.io/docs/minio/kubernetes/upstream/administration/object-management/create-lifecycle-management-expiration-rule.html#expire-versioned-objects"
>
{" "}
Versions
</a>
</Fragment>
}
helpTipPlacement="right"
/>
)}
<InputBox
error={
lifecycleDays && !isFormValid
? parseInt(lifecycleDays) <= 0
? `Number of ${expiryUnit} to retain must be greater than zero`
: parseInt(lifecycleDays) > 2147483647
? `Number of ${expiryUnit} must be less than or equal to 2147483647`
: ""
: ""
}
id="expiry_days"
name="expiry_days"
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.validity.valid) {
setLifecycleDays(e.target.value);
}
}}
pattern={"[0-9]*"}
label="After"
value={lifecycleDays}
overlayObject={
<Fragment>
<Grid container sx={{ justifyContent: "center" }}>
<InputUnitMenu
id={"expire-current-unit"}
unitSelected={expiryUnit}
unitsList={[
{ label: "Days", value: "days" },
{ label: "Versions", value: "versions" },
]}
disabled={
targetVersion !== "noncurrent" || ilmType !== "expiry"
}
onUnitChange={(newValue) => {
setExpiryUnit(newValue);
}}
/>
{ilmType === "expiry" && targetVersion === "noncurrent" && (
<HelpTip
content={
<Fragment>
Select to set expiry by days or newer noncurrent
versions
</Fragment>
}
placement="right"
>
{" "}
<AlertIcon style={{ width: 15, height: 15 }} />
</HelpTip>
)}
</Grid>
</Fragment>
}
/>
{ilmType === "expiry" ? (
<Fragment />
) : (
<Select
label="To Tier"
id="storage_class"
name="storage_class"
value={storageClass}
onChange={(value) => {
setStorageClass(value as string);
}}
options={tiersList}
helpTip={
<Fragment>
Configure a{" "}
<a
href={IAM_PAGES.TIERS_ADD}
color="secondary"
style={{ textDecoration: "underline" }}
>
remote tier
</a>{" "}
to receive transitioned Objects
</Fragment>
}
helpTipPlacement="right"
/>
)}
<Grid item xs={12} sx={formFieldRowFilter}>
<Accordion
title={"Filters"}
id={"lifecycle-filters"}
expanded={expanded}
onTitleClick={() => setExpanded(!expanded)}
>
<Grid item xs={12}>
<InputBox
id="prefix"
name="prefix"
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setPrefix(e.target.value);
}}
label="Prefix"
value={prefix}
/>
</Grid>
<Grid item xs={12}>
<QueryMultiSelector
name="tags"
label="Tags"
elements={""}
onChange={(vl: string) => {
setTags(vl);
}}
keyPlaceholder="Tag Key"
valuePlaceholder="Tag Value"
withBorder
/>
</Grid>
</Accordion>
</Grid>
{ilmType === "expiry" && targetVersion === "noncurrent" && (
<Grid item xs={12} sx={formFieldRowFilter}>
<Accordion
title={"Advanced"}
id={"lifecycle-advanced-filters"}
expanded={expandedAdv}
onTitleClick={() => setExpandedAdv(!expandedAdv)}
sx={{ marginTop: 15 }}
>
<Grid item xs={12}>
<Switch
value="expired_delete_marker"
id="expired_delete_marker"
name="expired_delete_marker"
checked={expiredObjectDM}
onChange={(
event: React.ChangeEvent<HTMLInputElement>,
) => {
setExpiredObjectDM(event.target.checked);
}}
label={"Expire Delete Marker"}
description={
"Remove the reference to the object if no versions are left"
}
/>
<Switch
value="expired_delete_all"
id="expired_delete_all"
name="expired_delete_all"
checked={expiredAllVersionsDM}
onChange={(
event: React.ChangeEvent<HTMLInputElement>,
) => {
setExpiredAllVersionsDM(event.target.checked);
}}
label={"Expire All Versions"}
description={
"Removes all the versions of the object already expired"
}
/>
</Grid>
</Accordion>
</Grid>
)}
<Grid item xs={12} sx={modalStyleUtils.modalButtonBar}>
<Button
id={"reset"}
type="button"
variant="regular"
disabled={addLoading}
onClick={() => {
closeModalAndRefresh(false);
}}
label={"Cancel"}
/>
<Button
id={"save-lifecycle"}
type="submit"
variant="callAction"
color="primary"
disabled={addLoading || !isFormValid}
label={"Save"}
/>
</Grid>
{addLoading && (
<Grid item xs={12}>
<ProgressBar />
</Grid>
)}
</FormLayout>
</form>
)}
</ModalWrapper>
);
};
export default AddLifecycleModal;

View File

@@ -88,9 +88,6 @@ const BucketEventsPanel = withSuspense(
const BucketReplicationPanel = withSuspense( const BucketReplicationPanel = withSuspense(
React.lazy(() => import("./BucketReplicationPanel")), React.lazy(() => import("./BucketReplicationPanel")),
); );
const BucketLifecyclePanel = withSuspense(
React.lazy(() => import("./BucketLifecyclePanel")),
);
const BucketDetails = () => { const BucketDetails = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
@@ -143,7 +140,6 @@ const BucketDetails = () => {
const manageBucketRoutes: Record<string, any> = { const manageBucketRoutes: Record<string, any> = {
events: "/admin/events", events: "/admin/events",
replication: "/admin/replication", replication: "/admin/replication",
lifecycle: "/admin/lifecycle",
access: "/admin/access", access: "/admin/access",
prefix: "/admin/prefix", prefix: "/admin/prefix",
}; };
@@ -330,21 +326,6 @@ const BucketDetails = () => {
to: getRoutePath("replication"), to: getRoutePath("replication"),
}, },
}, },
{
tabConfig: {
label: "Lifecycle",
id: "lifecycle",
disabled:
!distributedSetup ||
!hasPermission(bucketName, [
IAM_SCOPES.S3_GET_LIFECYCLE_CONFIGURATION,
IAM_SCOPES.S3_PUT_LIFECYCLE_CONFIGURATION,
IAM_SCOPES.S3_GET_ACTIONS,
IAM_SCOPES.S3_PUT_ACTIONS,
]),
to: getRoutePath("lifecycle"),
},
},
{ {
tabConfig: { tabConfig: {
label: "Access", label: "Access",
@@ -379,10 +360,6 @@ const BucketDetails = () => {
element={<BucketReplicationPanel />} element={<BucketReplicationPanel />}
/> />
)} )}
{distributedSetup && (
<Route path="lifecycle" element={<BucketLifecyclePanel />} />
)}
<Route path="access" element={<AccessDetailsPanel />} /> <Route path="access" element={<AccessDetailsPanel />} />
<Route path="prefix" element={<AccessRulePanel />} /> <Route path="prefix" element={<AccessRulePanel />} />
<Route <Route

View File

@@ -1,396 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { Fragment, useEffect, useState } from "react";
import get from "lodash/get";
import {
AddIcon,
Button,
DataTable,
Grid,
HelpBox,
SectionTitle,
TiersIcon,
HelpTip,
} from "mds";
import { useSelector } from "react-redux";
import { api } from "api";
import { ObjectBucketLifecycle } from "api/consoleApi";
import { LifeCycleItem } from "../types";
import {
hasPermission,
SecureComponent,
} from "../../../../common/SecureComponent";
import { IAM_SCOPES } from "../../../../common/SecureComponent/permissions";
import { selBucketDetailsLoading } from "./bucketDetailsSlice";
import { useParams } from "react-router-dom";
import { setHelpName } from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
import DeleteBucketLifecycleRule from "./DeleteBucketLifecycleRule";
import EditLifecycleConfiguration from "./EditLifecycleConfiguration";
import AddLifecycleModal from "./AddLifecycleModal";
import TooltipWrapper from "../../Common/TooltipWrapper/TooltipWrapper";
const BucketLifecyclePanel = () => {
const loadingBucket = useSelector(selBucketDetailsLoading);
const params = useParams();
const [loadingLifecycle, setLoadingLifecycle] = useState<boolean>(true);
const [lifecycleRecords, setLifecycleRecords] = useState<
ObjectBucketLifecycle[]
>([]);
const [addLifecycleOpen, setAddLifecycleOpen] = useState<boolean>(false);
const [editLifecycleOpen, setEditLifecycleOpen] = useState<boolean>(false);
const [selectedLifecycleRule, setSelectedLifecycleRule] =
useState<LifeCycleItem | null>(null);
const [deleteLifecycleOpen, setDeleteLifecycleOpen] =
useState<boolean>(false);
const [selectedID, setSelectedID] = useState<string | null>(null);
const dispatch = useAppDispatch();
const bucketName = params.bucketName || "";
const displayLifeCycleRules = hasPermission(bucketName, [
IAM_SCOPES.S3_GET_LIFECYCLE_CONFIGURATION,
IAM_SCOPES.S3_GET_ACTIONS,
]);
useEffect(() => {
if (loadingBucket) {
setLoadingLifecycle(true);
}
}, [loadingBucket, setLoadingLifecycle]);
useEffect(() => {
dispatch(setHelpName("bucket_detail_lifecycle"));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (loadingLifecycle) {
if (displayLifeCycleRules) {
api.buckets
.getBucketLifecycle(bucketName)
.then((res) => {
const records = get(res.data, "lifecycle", []);
setLifecycleRecords(records || []);
setLoadingLifecycle(false);
})
.catch((err) => {
console.error(err.error);
setLifecycleRecords([]);
setLoadingLifecycle(false);
});
} else {
setLoadingLifecycle(false);
}
}
}, [
loadingLifecycle,
setLoadingLifecycle,
bucketName,
displayLifeCycleRules,
]);
const closeEditLCAndRefresh = (refresh: boolean) => {
setEditLifecycleOpen(false);
setSelectedLifecycleRule(null);
if (refresh) {
setLoadingLifecycle(true);
}
};
const closeAddLCAndRefresh = (refresh: boolean) => {
setAddLifecycleOpen(false);
if (refresh) {
setLoadingLifecycle(true);
}
};
const closeDelLCRefresh = (refresh: boolean) => {
setDeleteLifecycleOpen(false);
setSelectedID(null);
if (refresh) {
setLoadingLifecycle(true);
}
};
const renderStorageClass = (objectST: any) => {
let stClass = get(objectST, "transition.storage_class", "");
stClass = get(objectST, "transition.noncurrent_storage_class", stClass);
return stClass;
};
const lifecycleColumns = [
{
label: "Type",
renderFullObject: true,
renderFunction: (el: LifeCycleItem) => {
if (!el) {
return <Fragment />;
}
if (
el.expiration &&
(el.expiration.days > 0 ||
el.expiration.noncurrent_expiration_days ||
(el.expiration.newer_noncurrent_expiration_versions &&
el.expiration.newer_noncurrent_expiration_versions > 0))
) {
return <span>Expiry</span>;
}
if (
el.transition &&
(el.transition.days > 0 || el.transition.noncurrent_transition_days)
) {
return <span>Transition</span>;
}
return <Fragment />;
},
},
{
label: "Version",
renderFullObject: true,
renderFunction: (el: LifeCycleItem) => {
if (!el) {
return <Fragment />;
}
if (el.expiration) {
if (el.expiration.days > 0) {
return <span>Current</span>;
} else if (
el.expiration.noncurrent_expiration_days ||
el.expiration.newer_noncurrent_expiration_versions
) {
return <span>Non-Current</span>;
}
}
if (el.transition) {
if (el.transition.days > 0) {
return <span>Current</span>;
} else if (el.transition.noncurrent_transition_days) {
return <span>Non-Current</span>;
}
}
},
},
{
label: "Expire Delete Marker",
elementKey: "expire_delete_marker",
renderFunction: (el: LifeCycleItem) => {
if (!el) {
return <Fragment />;
}
if (el.expiration && el.expiration.delete_marker !== undefined) {
return <span>{el.expiration.delete_marker ? "true" : "false"}</span>;
} else {
return <Fragment />;
}
},
renderFullObject: true,
},
{
label: "Tier",
elementKey: "storage_class",
renderFunction: renderStorageClass,
renderFullObject: true,
},
{
label: "Prefix",
elementKey: "prefix",
},
{
label: "After",
renderFullObject: true,
renderFunction: (el: LifeCycleItem) => {
if (!el) {
return <Fragment />;
}
if (el.transition) {
if (el.transition.days > 0) {
return <span>{el.transition.days} days</span>;
} else if (el.transition.noncurrent_transition_days) {
return <span>{el.transition.noncurrent_transition_days} days</span>;
}
}
if (el.expiration) {
if (el.expiration.days > 0) {
return <span>{el.expiration.days} days</span>;
} else if (el.expiration.noncurrent_expiration_days) {
return <span>{el.expiration.noncurrent_expiration_days} days</span>;
} else {
return (
<span>
{el.expiration.newer_noncurrent_expiration_versions} versions
</span>
);
}
}
},
},
{
label: "Status",
elementKey: "status",
},
];
const lifecycleActions = [
{
type: "view",
onClick(valueToSend: any): any {
setSelectedLifecycleRule(valueToSend);
setEditLifecycleOpen(true);
},
},
{
type: "delete",
onClick(valueToDelete: string): any {
setSelectedID(valueToDelete);
setDeleteLifecycleOpen(true);
},
sendOnlyId: true,
},
];
return (
<Fragment>
{editLifecycleOpen && selectedLifecycleRule && (
<EditLifecycleConfiguration
open={editLifecycleOpen}
closeModalAndRefresh={closeEditLCAndRefresh}
selectedBucket={bucketName}
lifecycleRule={selectedLifecycleRule}
/>
)}
{addLifecycleOpen && (
<AddLifecycleModal
open={addLifecycleOpen}
bucketName={bucketName}
closeModalAndRefresh={closeAddLCAndRefresh}
/>
)}
{deleteLifecycleOpen && selectedID && (
<DeleteBucketLifecycleRule
id={selectedID}
bucket={bucketName}
deleteOpen={deleteLifecycleOpen}
onCloseAndRefresh={closeDelLCRefresh}
/>
)}
<SectionTitle
separator
sx={{ marginBottom: 15 }}
actions={
<SecureComponent
scopes={[
IAM_SCOPES.S3_PUT_LIFECYCLE_CONFIGURATION,
IAM_SCOPES.S3_PUT_ACTIONS,
]}
resource={bucketName}
matchAll
errorProps={{ disabled: true }}
>
<TooltipWrapper tooltip={"Add Lifecycle Rule"}>
<Button
id={"add-bucket-lifecycle-rule"}
onClick={() => {
setAddLifecycleOpen(true);
}}
label={"Add Lifecycle Rule"}
icon={<AddIcon />}
variant={"callAction"}
/>
</TooltipWrapper>
</SecureComponent>
}
>
<HelpTip
content={
<Fragment>
MinIO derives its behavior and syntax from{" "}
<a
target="blank"
href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html"
>
S3 lifecycle
</a>{" "}
for compatibility in migrating workloads and lifecycle rules from
S3 to MinIO.
</Fragment>
}
placement="right"
>
Lifecycle Rules
</HelpTip>
</SectionTitle>
<Grid container>
<Grid item xs={12}>
<SecureComponent
scopes={[
IAM_SCOPES.S3_GET_LIFECYCLE_CONFIGURATION,
IAM_SCOPES.S3_GET_ACTIONS,
]}
resource={bucketName}
errorProps={{ disabled: true }}
>
<DataTable
itemActions={lifecycleActions}
columns={lifecycleColumns}
isLoading={loadingLifecycle}
records={lifecycleRecords}
entityName="Lifecycle"
customEmptyMessage="There are no Lifecycle rules yet"
idField="id"
customPaperHeight={"400px"}
/>
</SecureComponent>
</Grid>
{!loadingLifecycle && (
<Grid item xs={12}>
<br />
<HelpBox
title={"Lifecycle Rules"}
iconComponent={<TiersIcon />}
help={
<Fragment>
MinIO Object Lifecycle Management allows creating rules for
time or date based automatic transition or expiry of objects.
For object transition, MinIO automatically moves the object to
a configured remote storage tier.
<br />
<br />
You can learn more at our{" "}
<a
href="https://min.io/docs/minio/linux/administration/object-management/object-lifecycle-management.html?ref=con"
target="_blank"
rel="noopener"
>
documentation
</a>
.
</Fragment>
}
/>
</Grid>
)}
</Grid>
</Fragment>
);
};
export default BucketLifecyclePanel;

View File

@@ -1,78 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2022 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { useEffect, useState, Fragment } from "react";
import { ConfirmDeleteIcon } from "mds";
import { api } from "api";
import { errorToHandler } from "api/errors";
import { setErrorSnackMessage } from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
import ConfirmDialog from "../../Common/ModalWrapper/ConfirmDialog";
interface IDeleteLifecycleRule {
deleteOpen: boolean;
onCloseAndRefresh: (refresh: boolean) => any;
bucket: string;
id: string;
}
const DeleteBucketLifecycleRule = ({
onCloseAndRefresh,
deleteOpen,
bucket,
id,
}: IDeleteLifecycleRule) => {
const dispatch = useAppDispatch();
const [deletingRule, setDeletingRule] = useState<boolean>(false);
useEffect(() => {
if (deletingRule) {
api.buckets
.deleteBucketLifecycleRule(bucket, id)
.then(() => {
setDeletingRule(false);
onCloseAndRefresh(true);
})
.catch((err) => {
setDeletingRule(false);
dispatch(setErrorSnackMessage(errorToHandler(err.error)));
});
}
}, [deletingRule, bucket, id, onCloseAndRefresh, dispatch]);
const onConfirmDelete = () => {
setDeletingRule(true);
};
return (
<ConfirmDialog
title={`Delete Lifecycle Rule`}
confirmText={"Delete"}
isOpen={deleteOpen}
isLoading={deletingRule}
onConfirm={onConfirmDelete}
titleIcon={<ConfirmDeleteIcon />}
onClose={() => onCloseAndRefresh(false)}
confirmationContent={
<Fragment>
Are you sure you want to delete the <strong>{id}</strong> rule?
</Fragment>
}
/>
);
};
export default DeleteBucketLifecycleRule;

View File

@@ -1,564 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { Fragment, useEffect, useState } from "react";
import get from "lodash/get";
import {
Accordion,
Button,
FormLayout,
Grid,
InputBox,
LifecycleConfigIcon,
Loader,
ProgressBar,
RadioGroup,
Select,
Switch,
} from "mds";
import { api } from "api";
import { ApiError } from "api/consoleApi";
import { modalStyleUtils } from "../../Common/FormComponents/common/styleLibrary";
import { ITiersDropDown, LifeCycleItem } from "../types";
import {
setErrorSnackMessage,
setModalErrorSnackMessage,
} from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
import ModalWrapper from "../../Common/ModalWrapper/ModalWrapper";
import QueryMultiSelector from "../../Common/FormComponents/QueryMultiSelector/QueryMultiSelector";
import { errorToHandler } from "../../../../api/errors";
interface IAddUserContentProps {
closeModalAndRefresh: (reload: boolean) => void;
selectedBucket: string;
lifecycleRule: LifeCycleItem;
open: boolean;
}
const EditLifecycleConfiguration = ({
closeModalAndRefresh,
selectedBucket,
lifecycleRule,
open,
}: IAddUserContentProps) => {
const dispatch = useAppDispatch();
const [loadingTiers, setLoadingTiers] = useState<boolean>(true);
const [addLoading, setAddLoading] = useState<boolean>(false);
const [tags, setTags] = useState<string>("");
const [enabled, setEnabled] = useState<boolean>(false);
const [tiersList, setTiersList] = useState<ITiersDropDown[]>([]);
const [prefix, setPrefix] = useState("");
const [storageClass, setStorageClass] = useState("");
const [NCTransitionSC, setNCTransitionSC] = useState("");
const [expiredObjectDM, setExpiredObjectDM] = useState<boolean>(false);
const [expiredAllVersionsDM, setExpiredAllVersionsDM] =
useState<boolean>(false);
const [NCExpirationDays, setNCExpirationDays] = useState<string>("0");
const [NCTransitionDays, setNCTransitionDays] = useState<string>("0");
const [ilmType, setIlmType] = useState<"transition" | "expiry">("expiry");
const [expiryDays, setExpiryDays] = useState<string>("0");
const [transitionDays, setTransitionDays] = useState<string>("0");
const [isFormValid, setIsFormValid] = useState<boolean>(false);
const [expandedAdv, setExpandedAdv] = useState<boolean>(false);
const [expanded, setExpanded] = useState<boolean>(false);
const ILM_TYPES = [
{ value: "expiry", label: "Expiry" },
{ value: "transition", label: "Transition" },
];
useEffect(() => {
if (loadingTiers) {
api.admin
.tiersListNames()
.then((res) => {
const tiersList: string[] | null = get(res.data, "items", []);
if (tiersList !== null && tiersList.length >= 1) {
const objList = tiersList.map((tierName: string) => {
return { label: tierName, value: tierName };
});
setTiersList(objList);
if (objList.length > 0) {
setStorageClass(lifecycleRule.transition?.storage_class || "");
}
}
setLoadingTiers(false);
})
.catch((err) => {
setLoadingTiers(false);
dispatch(setModalErrorSnackMessage(errorToHandler(err.error)));
});
}
}, [dispatch, loadingTiers, lifecycleRule.transition?.storage_class]);
useEffect(() => {
let valid = true;
if (ilmType !== "expiry") {
if (
(transitionDays !== "0" && storageClass === "") ||
(NCTransitionDays !== "0" && NCTransitionSC === "")
) {
valid = false;
}
}
setIsFormValid(valid);
}, [
ilmType,
expiryDays,
transitionDays,
storageClass,
NCTransitionDays,
NCTransitionSC,
]);
useEffect(() => {
if (lifecycleRule.status === "Enabled") {
setEnabled(true);
}
let transitionMode = false;
if (lifecycleRule.transition) {
if (
lifecycleRule.transition.days &&
lifecycleRule.transition.days !== 0
) {
setTransitionDays(lifecycleRule.transition.days.toString());
setIlmType("transition");
transitionMode = true;
}
if (
lifecycleRule.transition.noncurrent_transition_days &&
lifecycleRule.transition.noncurrent_transition_days !== 0
) {
setNCTransitionDays(
lifecycleRule.transition.noncurrent_transition_days.toString(),
);
setIlmType("transition");
transitionMode = true;
}
// Fallback to old rules by date
if (
lifecycleRule.transition.date &&
lifecycleRule.transition.date !== "0001-01-01T00:00:00Z"
) {
setIlmType("transition");
transitionMode = true;
}
}
if (lifecycleRule.expiration) {
if (
lifecycleRule.expiration.days &&
lifecycleRule.expiration.days !== 0
) {
setExpiryDays(lifecycleRule.expiration.days.toString());
setIlmType("expiry");
transitionMode = false;
}
if (
lifecycleRule.expiration.noncurrent_expiration_days &&
lifecycleRule.expiration.noncurrent_expiration_days !== 0
) {
setNCExpirationDays(
lifecycleRule.expiration.noncurrent_expiration_days.toString(),
);
setIlmType("expiry");
transitionMode = false;
}
// Fallback to old rules by date
if (
lifecycleRule.expiration.date &&
lifecycleRule.expiration.date !== "0001-01-01T00:00:00Z"
) {
setIlmType("expiry");
transitionMode = false;
}
}
// Transition fields
if (transitionMode) {
setStorageClass(lifecycleRule.transition?.storage_class || "");
setNCTransitionDays(
lifecycleRule.transition?.noncurrent_transition_days?.toString() || "0",
);
setNCTransitionSC(
lifecycleRule.transition?.noncurrent_storage_class || "",
);
} else {
// Expiry fields
setNCExpirationDays(
lifecycleRule.expiration?.noncurrent_expiration_days?.toString() || "0",
);
}
setExpiredObjectDM(!!lifecycleRule.expiration?.delete_marker);
setExpiredAllVersionsDM(!!lifecycleRule.expiration?.delete_all);
setPrefix(lifecycleRule.prefix || "");
if (lifecycleRule.tags) {
const tgs = lifecycleRule.tags.reduce(
(stringLab: string, currItem: any, index: number) => {
return `${stringLab}${index !== 0 ? "&" : ""}${currItem.key}=${
currItem.value
}`;
},
"",
);
setTags(tgs);
}
}, [lifecycleRule]);
const saveRecord = (event: React.FormEvent) => {
event.preventDefault();
if (addLoading) {
return;
}
setAddLoading(true);
if (selectedBucket !== null && lifecycleRule !== null) {
let rules = {};
if (ilmType === "expiry") {
let expiry: { [key: string]: number } = {};
if (
lifecycleRule.expiration?.days &&
lifecycleRule.expiration?.days > 0
) {
expiry["expiry_days"] = parseInt(expiryDays);
}
if (lifecycleRule.expiration?.noncurrent_expiration_days) {
expiry["noncurrentversion_expiration_days"] =
parseInt(NCExpirationDays);
}
rules = {
...expiry,
};
} else {
let transition: { [key: string]: number | string } = {};
if (
lifecycleRule.transition?.days &&
lifecycleRule.transition?.days > 0
) {
transition["transition_days"] = parseInt(transitionDays);
transition["storage_class"] = storageClass;
}
if (lifecycleRule.transition?.noncurrent_transition_days) {
transition["noncurrentversion_transition_days"] =
parseInt(NCTransitionDays);
transition["noncurrentversion_transition_storage_class"] =
NCTransitionSC;
}
rules = {
...transition,
};
}
const lifecycleUpdate = {
type: ilmType,
disable: !enabled,
prefix,
tags,
expired_object_delete_marker: expiredObjectDM,
expired_object_delete_all: expiredAllVersionsDM,
...rules,
};
api.buckets
.updateBucketLifecycle(
selectedBucket,
lifecycleRule.id,
lifecycleUpdate,
)
.then((res) => {
setAddLoading(false);
closeModalAndRefresh(true);
})
.catch(async (eRes) => {
setAddLoading(false);
const err = (await eRes.json()) as ApiError;
dispatch(setErrorSnackMessage(errorToHandler(err)));
});
}
};
let objectVersion = "";
if (lifecycleRule.expiration) {
if (lifecycleRule.expiration.days > 0) {
objectVersion = "Current Version";
} else if (lifecycleRule.expiration.noncurrent_expiration_days) {
objectVersion = "Non-Current Version";
}
}
if (lifecycleRule.transition) {
if (lifecycleRule.transition.days > 0) {
objectVersion = "Current Version";
} else if (lifecycleRule.transition.noncurrent_transition_days) {
objectVersion = "Non-Current Version";
}
}
return (
<ModalWrapper
onClose={() => {
closeModalAndRefresh(false);
}}
modalOpen={open}
title={"Edit Lifecycle Configuration"}
titleIcon={<LifecycleConfigIcon />}
>
{!loadingTiers ? (
<form
noValidate
autoComplete="off"
onSubmit={(e: React.FormEvent<HTMLFormElement>) => {
saveRecord(e);
}}
>
<FormLayout containerPadding={false} withBorders={false}>
<Switch
label="Status"
indicatorLabels={["Enabled", "Disabled"]}
checked={enabled}
value={"user_enabled"}
id="rule_status"
name="rule_status"
onChange={(e) => {
setEnabled(e.target.checked);
}}
/>
<InputBox
id="id"
name="id"
label="Id"
value={lifecycleRule.id}
onChange={() => {}}
disabled
/>
{ilmType ? (
<RadioGroup
currentValue={ilmType}
id="rule_type"
name="rule_type"
label="Rule Type"
selectorOptions={ILM_TYPES}
onChange={() => {}}
disableOptions
/>
) : null}
<InputBox
id="object-version"
name="object-version"
label="Object Version"
value={objectVersion}
onChange={() => {}}
disabled
/>
{ilmType === "expiry" && lifecycleRule.expiration?.days && (
<InputBox
type="number"
id="expiry_days"
name="expiry_days"
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setExpiryDays(e.target.value);
}}
label="Expiry Days"
value={expiryDays}
min="0"
/>
)}
{ilmType === "expiry" &&
lifecycleRule.expiration?.noncurrent_expiration_days && (
<InputBox
type="number"
id="noncurrentversion_expiration_days"
name="noncurrentversion_expiration_days"
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setNCExpirationDays(e.target.value);
}}
label="Non-current Expiration Days"
value={NCExpirationDays}
min="0"
/>
)}
{ilmType === "transition" && lifecycleRule.transition?.days && (
<Fragment>
<InputBox
type="number"
id="transition_days"
name="transition_days"
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setTransitionDays(e.target.value);
}}
label="Transition Days"
value={transitionDays}
min="0"
/>
<Select
label="Tier"
id="storage_class"
name="storage_class"
value={storageClass}
onChange={(value) => {
setStorageClass(value);
}}
options={tiersList}
/>
</Fragment>
)}
{ilmType === "transition" &&
lifecycleRule.transition?.noncurrent_transition_days && (
<Fragment>
<InputBox
type="number"
id="noncurrentversion_transition_days"
name="noncurrentversion_transition_days"
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setNCTransitionDays(e.target.value);
}}
label="Non-current Transition Days"
value={NCTransitionDays}
min="0"
/>
<Select
label="Non-current Version Transition Storage Class"
id="noncurrentversion_t_SC"
name="noncurrentversion_t_SC"
value={NCTransitionSC}
onChange={(value) => {
setNCTransitionSC(value);
}}
options={tiersList}
/>
</Fragment>
)}
<Grid item xs={12}>
<Accordion
title={"Filters"}
id={"lifecycle-filters"}
expanded={expanded}
onTitleClick={() => setExpanded(!expanded)}
>
<InputBox
id="prefix"
name="prefix"
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setPrefix(e.target.value);
}}
label="Prefix"
value={prefix}
/>
<QueryMultiSelector
name="tags"
label="Tags"
elements={tags}
onChange={(vl: string) => {
setTags(vl);
}}
keyPlaceholder="Tag Key"
valuePlaceholder="Tag Value"
withBorder
/>
</Accordion>
</Grid>
{ilmType === "expiry" &&
lifecycleRule.expiration?.noncurrent_expiration_days && (
<Grid item xs={12}>
<Accordion
title={"Advanced"}
id={"lifecycle-advanced-filters"}
expanded={expandedAdv}
onTitleClick={() => setExpandedAdv(!expandedAdv)}
sx={{ marginTop: 15 }}
>
<Switch
value="expired_delete_marker"
id="expired_delete_marker"
name="expired_delete_marker"
checked={expiredObjectDM}
onChange={(
event: React.ChangeEvent<HTMLInputElement>,
) => {
setExpiredObjectDM(event.target.checked);
}}
label={"Expired Object Delete Marker"}
/>
<Switch
value="expired_delete_all"
id="expired_delete_all"
name="expired_delete_all"
checked={expiredAllVersionsDM}
onChange={(
event: React.ChangeEvent<HTMLInputElement>,
) => {
setExpiredAllVersionsDM(event.target.checked);
}}
label={"Expired All Versions"}
/>
</Accordion>
</Grid>
)}
<Grid item xs={12} sx={modalStyleUtils.modalButtonBar}>
<Button
id={"cancel"}
type="button"
variant="regular"
disabled={addLoading}
onClick={() => {
closeModalAndRefresh(false);
}}
label={"Cancel"}
/>
<Button
id={"save"}
type="submit"
variant="callAction"
color="primary"
disabled={addLoading || !isFormValid}
label={"Save"}
/>
</Grid>
{addLoading && (
<Grid item xs={12}>
<ProgressBar />
</Grid>
)}
</FormLayout>
</form>
) : (
<Loader style={{ width: 16, height: 16 }} />
)}
</ModalWrapper>
);
};
export default EditLifecycleConfiguration;

View File

@@ -1,415 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2022 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { Fragment, useEffect, useState } from "react";
import {
Box,
CheckCircleIcon,
FormLayout,
Grid,
InputBox,
RadioGroup,
ReadBox,
Select,
Switch,
Tooltip,
WarnIcon,
Wizard,
} from "mds";
import get from "lodash/get";
import ModalWrapper from "../../Common/ModalWrapper/ModalWrapper";
import QueryMultiSelector from "../../Common/FormComponents/QueryMultiSelector/QueryMultiSelector";
import { ITiersDropDown } from "../types";
import { setModalErrorSnackMessage } from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
import { api } from "api";
import { MultiLifecycleResult } from "api/consoleApi";
import { errorToHandler } from "api/errors";
interface IBulkReplicationModal {
open: boolean;
closeModalAndRefresh: (clearSelection: boolean) => any;
buckets: string[];
}
const AddBulkReplicationModal = ({
open,
closeModalAndRefresh,
buckets,
}: IBulkReplicationModal) => {
const dispatch = useAppDispatch();
const [addLoading, setAddLoading] = useState<boolean>(false);
const [loadingTiers, setLoadingTiers] = useState<boolean>(true);
const [tiersList, setTiersList] = useState<ITiersDropDown[]>([]);
const [prefix, setPrefix] = useState("");
const [tags, setTags] = useState<string>("");
const [storageClass, setStorageClass] = useState("");
const [NCTransitionSC, setNCTransitionSC] = useState("");
const [expiredObjectDM, setExpiredObjectDM] = useState<boolean>(false);
const [expiredAllVersionsDM, setExpiredAllVersionsDM] =
useState<boolean>(false);
const [NCExpirationDays, setNCExpirationDays] = useState<string>("0");
const [NCTransitionDays, setNCTransitionDays] = useState<string>("0");
const [ilmType, setIlmType] = useState<"expiry" | "transition">("expiry");
const [expiryDays, setExpiryDays] = useState<string>("0");
const [transitionDays, setTransitionDays] = useState<string>("0");
const [isFormValid, setIsFormValid] = useState<boolean>(false);
const [results, setResults] = useState<MultiLifecycleResult | null>(null);
useEffect(() => {
if (loadingTiers) {
api.admin
.tiersListNames()
.then((res) => {
const tiersList: string[] | null = get(res.data, "items", []);
if (tiersList !== null && tiersList.length >= 1) {
const objList = tiersList.map((tierName: string) => {
return { label: tierName, value: tierName };
});
setTiersList(objList);
if (objList.length > 0) {
setStorageClass(objList[0].value);
}
}
setLoadingTiers(false);
})
.catch((err) => {
setLoadingTiers(false);
dispatch(setModalErrorSnackMessage(errorToHandler(err.error)));
});
}
}, [dispatch, loadingTiers]);
useEffect(() => {
let valid = true;
if (ilmType !== "expiry") {
if (storageClass === "") {
valid = false;
}
}
setIsFormValid(valid);
}, [ilmType, expiryDays, transitionDays, storageClass]);
const LogoToShow = ({ errString }: { errString: string }) => {
switch (errString) {
case "":
return (
<Box
sx={{
paddingTop: 5,
color: "#42C91A",
}}
>
<CheckCircleIcon />
</Box>
);
case "n/a":
return null;
default:
if (errString) {
return (
<Box
sx={{
paddingTop: 5,
color: "#C72C48",
}}
>
<Tooltip tooltip={errString} placement="top">
<WarnIcon />
</Tooltip>
</Box>
);
}
}
return null;
};
const createLifecycleRules = (to: any) => {
let rules = {};
if (ilmType === "expiry") {
let expiry = {
expiry_days: parseInt(expiryDays),
};
rules = {
...expiry,
noncurrentversion_expiration_days: parseInt(NCExpirationDays),
};
} else {
let transition = {
transition_days: parseInt(transitionDays),
};
rules = {
...transition,
noncurrentversion_transition_days: parseInt(NCTransitionDays),
noncurrentversion_transition_storage_class: NCTransitionSC,
storage_class: storageClass,
};
}
const lifecycleInsert = {
buckets,
type: ilmType,
prefix,
tags,
expired_object_delete_marker: expiredObjectDM,
expired_object_delete_all: expiredAllVersionsDM,
...rules,
};
api.buckets
.addMultiBucketLifecycle(lifecycleInsert)
.then((res) => {
setAddLoading(false);
setResults(res.data);
to("++");
})
.catch((err) => {
setAddLoading(false);
dispatch(setModalErrorSnackMessage(errorToHandler(err.error)));
});
};
return (
<ModalWrapper
modalOpen={open}
onClose={() => {
closeModalAndRefresh(false);
}}
title="Set Lifecycle to multiple buckets"
>
<Wizard
loadingStep={addLoading || loadingTiers}
wizardSteps={[
{
label: "Lifecycle Configuration",
componentRender: (
<Fragment>
<FormLayout withBorders={false} containerPadding={false}>
<Grid item xs={12}>
<ReadBox
label="Local Buckets to replicate"
sx={{ maxWidth: "440px", width: "100%" }}
>
{buckets.join(", ")}
</ReadBox>
</Grid>
<h4>Remote Endpoint Configuration</h4>
<fieldset className={"inputItem"}>
<legend>Lifecycle Configuration</legend>
<RadioGroup
currentValue={ilmType}
id="quota_type"
name="quota_type"
label="ILM Rule"
onChange={(e: React.ChangeEvent<{ value: unknown }>) => {
setIlmType(e.target.value as "expiry" | "transition");
}}
selectorOptions={[
{ value: "expiry", label: "Expiry" },
{ value: "transition", label: "Transition" },
]}
/>
{ilmType === "expiry" ? (
<Fragment>
<InputBox
type="number"
id="expiry_days"
name="expiry_days"
onChange={(
e: React.ChangeEvent<HTMLInputElement>,
) => {
setExpiryDays(e.target.value);
}}
label="Expiry Days"
value={expiryDays}
min="0"
/>
<InputBox
type="number"
id="noncurrentversion_expiration_days"
name="noncurrentversion_expiration_days"
onChange={(
e: React.ChangeEvent<HTMLInputElement>,
) => {
setNCExpirationDays(e.target.value);
}}
label="Non-current Expiration Days"
value={NCExpirationDays}
min="0"
/>
</Fragment>
) : (
<Fragment>
<InputBox
type="number"
id="transition_days"
name="transition_days"
onChange={(
e: React.ChangeEvent<HTMLInputElement>,
) => {
setTransitionDays(e.target.value);
}}
label="Transition Days"
value={transitionDays}
min="0"
/>
<InputBox
type="number"
id="noncurrentversion_transition_days"
name="noncurrentversion_transition_days"
onChange={(
e: React.ChangeEvent<HTMLInputElement>,
) => {
setNCTransitionDays(e.target.value);
}}
label="Non-current Transition Days"
value={NCTransitionDays}
min="0"
/>
<InputBox
id="noncurrentversion_t_SC"
name="noncurrentversion_t_SC"
onChange={(
e: React.ChangeEvent<HTMLInputElement>,
) => {
setNCTransitionSC(e.target.value);
}}
placeholder="Set Non-current Version Transition Storage Class"
label="Non-current Version Transition Storage Class"
value={NCTransitionSC}
/>
<Select
label="Storage Class"
id="storage_class"
name="storage_class"
value={storageClass}
onChange={(value) => {
setStorageClass(value);
}}
options={tiersList}
/>
</Fragment>
)}
</fieldset>
<fieldset className={"inputItem"}>
<legend>File Configuration</legend>
<InputBox
id="prefix"
name="prefix"
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setPrefix(e.target.value);
}}
label="Prefix"
value={prefix}
/>
<QueryMultiSelector
name="tags"
label="Tags"
elements={tags}
onChange={(vl: string) => {
setTags(vl);
}}
keyPlaceholder="Tag Key"
valuePlaceholder="Tag Value"
withBorder
/>
<Switch
value="expired_delete_marker"
id="expired_delete_marker"
name="expired_delete_marker"
checked={expiredObjectDM}
onChange={(
event: React.ChangeEvent<HTMLInputElement>,
) => {
setExpiredObjectDM(event.target.checked);
}}
label={"Expired Object Delete Marker"}
/>
<Switch
value="expired_delete_all"
id="expired_delete_all"
name="expired_delete_all"
checked={expiredAllVersionsDM}
onChange={(
event: React.ChangeEvent<HTMLInputElement>,
) => {
setExpiredAllVersionsDM(event.target.checked);
}}
label={"Expired All Versions"}
/>
</fieldset>
</FormLayout>
</Fragment>
),
buttons: [
{
type: "custom",
label: "Create Rules",
enabled: !loadingTiers && !addLoading && isFormValid,
action: createLifecycleRules,
},
],
},
{
label: "Results",
componentRender: (
<Fragment>
<h3>Multi Bucket lifecycle Assignments Results</h3>
<Grid container>
<Grid item xs={12}>
<h4>Buckets Results</h4>
{results?.results?.map((resultItem) => {
return (
<Box
sx={{
display: "grid",
gridTemplateColumns: "45px auto",
alignItems: "center",
justifyContent: "stretch",
}}
>
{LogoToShow({ errString: resultItem.error || "" })}
<span>{resultItem.bucketName}</span>
</Box>
);
})}
</Grid>
</Grid>
</Fragment>
),
buttons: [
{
type: "custom",
label: "Done",
enabled: !addLoading,
action: () => closeModalAndRefresh(true),
},
],
},
]}
forModal
/>
</ModalWrapper>
);
};
export default AddBulkReplicationModal;

View File

@@ -21,7 +21,6 @@ import {
BucketsIcon, BucketsIcon,
Button, Button,
HelpBox, HelpBox,
LifecycleConfigIcon,
MultipleBucketsIcon, MultipleBucketsIcon,
PageLayout, PageLayout,
RefreshIcon, RefreshIcon,
@@ -38,8 +37,6 @@ import { SecureComponent } from "../../../../common/SecureComponent";
import { import {
CONSOLE_UI_RESOURCE, CONSOLE_UI_RESOURCE,
IAM_PAGES, IAM_PAGES,
IAM_PERMISSIONS,
IAM_ROLES,
IAM_SCOPES, IAM_SCOPES,
permissionTooltipHelper, permissionTooltipHelper,
} from "../../../../common/SecureComponent/permissions"; } from "../../../../common/SecureComponent/permissions";
@@ -56,7 +53,6 @@ import AutoColorIcon from "../../Common/Components/AutoColorIcon";
import TooltipWrapper from "../../Common/TooltipWrapper/TooltipWrapper"; import TooltipWrapper from "../../Common/TooltipWrapper/TooltipWrapper";
import SearchBox from "../../Common/SearchBox"; import SearchBox from "../../Common/SearchBox";
import VirtualizedList from "../../Common/VirtualizedList/VirtualizedList"; import VirtualizedList from "../../Common/VirtualizedList/VirtualizedList";
import BulkLifecycleModal from "./BulkLifecycleModal";
import hasPermission from "../../../../common/SecureComponent/accessControl"; import hasPermission from "../../../../common/SecureComponent/accessControl";
import BucketListItem from "./BucketListItem"; import BucketListItem from "./BucketListItem";
import BulkReplicationModal from "./BulkReplicationModal"; import BulkReplicationModal from "./BulkReplicationModal";
@@ -71,8 +67,6 @@ const ListBuckets = () => {
const [selectedBuckets, setSelectedBuckets] = useState<string[]>([]); const [selectedBuckets, setSelectedBuckets] = useState<string[]>([]);
const [replicationModalOpen, setReplicationModalOpen] = const [replicationModalOpen, setReplicationModalOpen] =
useState<boolean>(false); useState<boolean>(false);
const [lifecycleModalOpen, setLifecycleModalOpen] = useState<boolean>(false);
const [canPutLifecycle, setCanPutLifecycle] = useState<boolean>(false);
const [bulkSelect, setBulkSelect] = useState<boolean>(false); const [bulkSelect, setBulkSelect] = useState<boolean>(false);
const features = useSelector(selFeatures); const features = useSelector(selFeatures);
@@ -137,24 +131,6 @@ const ListBuckets = () => {
} }
}; };
const closeBulkLifecycleModal = (unselectAll: boolean) => {
setLifecycleModalOpen(false);
if (unselectAll) {
setSelectedBuckets([]);
}
};
useEffect(() => {
var failLifecycle = false;
selectedBuckets.forEach((bucket: string) => {
hasPermission(bucket, IAM_PERMISSIONS[IAM_ROLES.BUCKET_LIFECYCLE], true)
? setCanPutLifecycle(true)
: (failLifecycle = true);
});
failLifecycle ? setCanPutLifecycle(false) : setCanPutLifecycle(true);
}, [selectedBuckets]);
const renderItemLine = (index: number) => { const renderItemLine = (index: number) => {
const bucket = filteredRecords[index] || null; const bucket = filteredRecords[index] || null;
if (bucket) { if (bucket) {
@@ -198,13 +174,6 @@ const ListBuckets = () => {
closeModalAndRefresh={closeBulkReplicationModal} closeModalAndRefresh={closeBulkReplicationModal}
/> />
)} )}
{lifecycleModalOpen && (
<BulkLifecycleModal
buckets={selectedBuckets}
closeModalAndRefresh={closeBulkLifecycleModal}
open={lifecycleModalOpen}
/>
)}
{!obOnly && ( {!obOnly && (
<PageHeaderWrapper label={"Buckets"} actions={<HelpMenu />} /> <PageHeaderWrapper label={"Buckets"} actions={<HelpMenu />} />
)} )}
@@ -282,33 +251,6 @@ const ListBuckets = () => {
</TooltipWrapper> </TooltipWrapper>
)} )}
<TooltipWrapper
tooltip={
!hasBuckets
? ""
: !canPutLifecycle
? permissionTooltipHelper(
IAM_PERMISSIONS[IAM_ROLES.BUCKET_LIFECYCLE],
"configure lifecycle for the selected buckets",
)
: selectedBuckets.length === 0
? bulkSelect
? "Please select at least one bucket on which to configure Lifecycle"
: "Use the Select Multiple Buckets button to choose buckets on which to configure Lifecycle"
: "Set Lifecycle"
}
>
<Button
id={"set-lifecycle"}
onClick={() => {
setLifecycleModalOpen(true);
}}
icon={<LifecycleConfigIcon />}
variant={"regular"}
disabled={selectedBuckets.length === 0 || !canPutLifecycle}
/>
</TooltipWrapper>
<TooltipWrapper <TooltipWrapper
tooltip={ tooltip={
!hasBuckets !hasBuckets

View File

@@ -36,43 +36,3 @@ export interface BucketReplicationRule {
export interface BucketReplication { export interface BucketReplication {
rules: BucketReplicationRule[]; rules: BucketReplicationRule[];
} }
interface IExpirationLifecycle {
days: number;
date: string;
delete_marker?: boolean;
delete_all?: boolean;
noncurrent_expiration_days?: number;
newer_noncurrent_expiration_versions?: number;
}
interface ITransitionLifecycle {
days: number;
date: string;
storage_class?: string;
noncurrent_transition_days?: number;
noncurrent_storage_class?: string;
}
export interface LifeCycleItem {
id: string;
prefix?: string;
expiration?: IExpirationLifecycle;
transition?: ITransitionLifecycle;
tags?: any;
status?: string;
}
interface MultiBucketResult {
bucketName: string;
error?: string;
}
interface MultiBucketResult {
results: MultiBucketResult[];
}
export interface ITiersDropDown {
label: string;
value: string;
}

View File

@@ -1,64 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React from "react";
import { HelpBox, Box, Grid, breakPoints } from "mds";
interface IDistributedOnly {
iconComponent: any;
entity: string;
}
const DistributedOnly = ({ iconComponent, entity }: IDistributedOnly) => {
return (
<Grid container>
<Grid item xs={12}>
<HelpBox
title={`${entity} not available`}
iconComponent={iconComponent}
help={
<Box
sx={{
fontSize: "14px",
[`@media (max-width: ${breakPoints.sm}px)`]: {
display: "flex",
flexFlow: "column",
},
}}
>
<span>
This feature is not available for a single-disk setup.&nbsp;
</span>
<span>
Please deploy a server in{" "}
<a
href="https://min.io/docs/minio/linux/operations/install-deploy-manage/deploy-minio-multi-node-multi-drive.html?ref=con"
target="_blank"
rel="noopener"
>
Distributed Mode
</a>{" "}
to use this feature.
</span>
</Box>
}
/>
</Grid>
</Grid>
);
};
export default DistributedOnly;

View File

@@ -660,12 +660,6 @@ const IconsScreen = () => {
LicenseIcon LicenseIcon
</Grid> </Grid>
<Grid item xs={3} sm={2} md={1}>
<cicons.LifecycleConfigIcon />
<br />
LifecycleConfigIcon
</Grid>
<Grid item xs={3} sm={2} md={1}> <Grid item xs={3} sm={2} md={1}>
<cicons.LinkIcon /> <cicons.LinkIcon />
<br /> <br />
@@ -1002,18 +996,6 @@ const IconsScreen = () => {
TenantsOutlineIcon TenantsOutlineIcon
</Grid> </Grid>
<Grid item xs={3} sm={2} md={1}>
<cicons.TiersIcon />
<br />
TiersIcon
</Grid>
<Grid item xs={3} sm={2} md={1}>
<cicons.TiersNotAvailableIcon />
<br />
TiersNotAvailableIcon
</Grid>
<Grid item xs={3} sm={2} md={1}> <Grid item xs={3} sm={2} md={1}>
<cicons.ToolsIcon /> <cicons.ToolsIcon />
<br /> <br />

View File

@@ -1,486 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { Fragment, useCallback, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import get from "lodash/get";
import {
BackLink,
breakPoints,
Button,
FileSelector,
Grid,
InputBox,
PageLayout,
SectionTitle,
} from "mds";
import { api } from "api";
import { errorToHandler } from "api/errors";
import { ApiError } from "api/consoleApi";
import { modalStyleUtils } from "../../Common/FormComponents/common/styleLibrary";
import {
azureServiceName,
gcsServiceName,
minioServiceName,
s3ServiceName,
tierTypes,
} from "./utils";
import { IAM_PAGES } from "../../../../common/SecureComponent/permissions";
import { setErrorSnackMessage, setHelpName } from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
import RegionSelectWrapper from "./RegionSelectWrapper";
import PageHeaderWrapper from "../../Common/PageHeaderWrapper/PageHeaderWrapper";
import HelpMenu from "../../HelpMenu";
const AddTierConfiguration = () => {
const dispatch = useAppDispatch();
const navigate = useNavigate();
const params = useParams();
//Local States
const [saving, setSaving] = useState<boolean>(false);
// Form Items
const [name, setName] = useState<string>("");
const [endpoint, setEndpoint] = useState<string>("");
const [bucket, setBucket] = useState<string>("");
const [prefix, setPrefix] = useState<string>("");
const [region, setRegion] = useState<string>("");
const [storageClass, setStorageClass] = useState<string>("");
const [accessKey, setAccessKey] = useState<string>("");
const [secretKey, setSecretKey] = useState<string>("");
const [creds, setCreds] = useState<string>("");
const [encodedCreds, setEncodedCreds] = useState<string>("");
const [accountName, setAccountName] = useState<string>("");
const [accountKey, setAccountKey] = useState<string>("");
const [titleSelection, setTitleSelection] = useState<string>("");
const type = get(params, "service", "s3");
// Validations
const [isFormValid, setIsFormValid] = useState<boolean>(true);
const [nameInputError, setNameInputError] = useState<string>("");
// Extra validation functions
const validName = useCallback(() => {
const patternAgainst = /^[A-Z0-9-_]+$/; // Only allow uppercase, numbers, dashes and underscores
if (patternAgainst.test(name)) {
setNameInputError("");
return true;
}
setNameInputError(
"Please verify that string is uppercase only and contains valid characters (numbers, dashes & underscores).",
);
return false;
}, [name]);
//Effects
useEffect(() => {
if (saving) {
let request = {};
let fields = {
name,
endpoint,
bucket,
prefix,
region,
};
let tierType = type;
switch (type) {
case "minio":
request = {
minio: {
...fields,
accesskey: accessKey,
secretkey: secretKey,
},
};
break;
case "s3":
request = {
s3: {
...fields,
accesskey: accessKey,
secretkey: secretKey,
storageclass: storageClass,
},
};
break;
case "gcs":
request = {
gcs: {
...fields,
creds: encodedCreds,
},
};
break;
case "azure":
request = {
azure: {
...fields,
accountname: accountName,
accountkey: accountKey,
},
};
}
let payload = {
type: tierType as
| "azure"
| "s3"
| "minio"
| "gcs"
| "unsupported"
| undefined,
...request,
};
api.admin
.addTier(payload)
.then(() => {
setSaving(false);
navigate(IAM_PAGES.TIERS);
})
.catch(async (res) => {
const err = (await res.json()) as ApiError;
setSaving(false);
dispatch(setErrorSnackMessage(errorToHandler(err)));
});
}
}, [
accessKey,
accountKey,
accountName,
bucket,
encodedCreds,
endpoint,
name,
prefix,
region,
saving,
secretKey,
dispatch,
storageClass,
type,
navigate,
]);
useEffect(() => {
let valid = true;
if (type === "") {
valid = false;
}
if (name === "" || !validName()) {
valid = false;
}
if (endpoint === "") {
valid = false;
}
if (bucket === "") {
valid = false;
}
if (region === "" && type !== "minio") {
valid = false;
}
if (type === "s3" || type === "minio") {
if (accessKey === "") {
valid = false;
}
if (secretKey === "") {
valid = false;
}
}
if (type === "gcs") {
if (encodedCreds === "") {
valid = false;
}
}
if (type === "azure") {
if (accountName === "") {
valid = false;
}
if (accountKey === "") {
valid = false;
}
}
setIsFormValid(valid);
}, [
accessKey,
accountKey,
accountName,
bucket,
encodedCreds,
endpoint,
isFormValid,
name,
prefix,
region,
secretKey,
storageClass,
type,
validName,
]);
useEffect(() => {
switch (type) {
case "gcs":
setEndpoint("https://storage.googleapis.com");
setTitleSelection("Google Cloud");
break;
case "s3":
setEndpoint("https://s3.amazonaws.com");
setTitleSelection("Amazon S3");
break;
case "azure":
setEndpoint("http://blob.core.windows.net");
setTitleSelection("Azure");
break;
case "minio":
setEndpoint("");
setTitleSelection("MinIO");
}
}, [type]);
//Fetch Actions
const submitForm = (event: React.FormEvent) => {
event.preventDefault();
setSaving(true);
};
// Input actions
const updateTierName = (e: React.ChangeEvent<HTMLInputElement>) => {
setName(e.target.value.toUpperCase());
};
const targetElement = tierTypes.find((item) => item.serviceName === type);
useEffect(() => {
dispatch(setHelpName("add-tier-configuration"));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<Fragment>
<PageHeaderWrapper
label={
<Fragment>
<BackLink
label={"Add Tier"}
onClick={() => navigate(IAM_PAGES.TIERS_ADD)}
/>
</Fragment>
}
actions={<HelpMenu />}
/>
<PageLayout>
<Grid
item
xs={12}
sx={{
border: "1px solid #eaeaea",
padding: "25px",
}}
>
<form noValidate onSubmit={submitForm}>
{type !== "" && targetElement ? (
<SectionTitle icon={targetElement.logo} sx={{ marginBottom: 20 }}>
{titleSelection ? titleSelection : ""} - Add Tier Configuration
</SectionTitle>
) : null}
<Grid
item
xs={12}
sx={{
display: "grid",
gridTemplateColumns: "1fr 1fr",
gridAutoFlow: "row",
gridRowGap: 20,
gridColumnGap: 50,
[`@media (max-width: ${breakPoints.sm}px)`]: {
gridTemplateColumns: "1fr",
gridAutoFlow: "dense",
},
}}
>
{type !== "" && (
<Fragment>
<InputBox
id="name"
name="name"
label="Name"
placeholder="Enter Name (Eg. REMOTE-TIER)"
value={name}
onChange={updateTierName}
error={nameInputError}
required
/>
<InputBox
id="endpoint"
name="endpoint"
label="Endpoint"
placeholder="Enter Endpoint"
value={endpoint}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setEndpoint(e.target.value);
}}
required
/>
{(type === s3ServiceName || type === minioServiceName) && (
<Fragment>
<InputBox
id="accessKey"
name="accessKey"
label="Access Key"
placeholder="Enter Access Key"
value={accessKey}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setAccessKey(e.target.value);
}}
required
/>
<InputBox
id="secretKey"
name="secretKey"
label="Secret Key"
placeholder="Enter Secret Key"
value={secretKey}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setSecretKey(e.target.value);
}}
required
/>
</Fragment>
)}
{type === gcsServiceName && (
<FileSelector
accept=".json"
id="creds"
label="Credentials"
name="creds"
returnEncodedData
onChange={(_, fileName, encodedValue) => {
if (encodedValue) {
setEncodedCreds(encodedValue);
setCreds(fileName);
}
}}
value={creds}
required
/>
)}
{type === azureServiceName && (
<Fragment>
<InputBox
id="accountName"
name="accountName"
label="Account Name"
placeholder="Enter Account Name"
value={accountName}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setAccountName(e.target.value);
}}
required
/>
<InputBox
id="accountKey"
name="accountKey"
label="Account Key"
placeholder="Enter Account Key"
value={accountKey}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setAccountKey(e.target.value);
}}
required
/>
</Fragment>
)}
<InputBox
id="bucket"
name="bucket"
label="Bucket"
placeholder="Enter Bucket"
value={bucket}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setBucket(e.target.value);
}}
required
/>
<InputBox
id="prefix"
name="prefix"
label="Prefix"
placeholder="Enter Prefix"
value={prefix}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setPrefix(e.target.value);
}}
/>
<RegionSelectWrapper
onChange={(value) => {
setRegion(value);
}}
required={type !== "minio"}
label={"Region"}
id="region"
type={type as "azure" | "s3" | "minio" | "gcs"}
/>
{type === s3ServiceName && (
<InputBox
id="storageClass"
name="storageClass"
label="Storage Class"
placeholder="Enter Storage Class"
value={storageClass}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setStorageClass(e.target.value);
}}
/>
)}
</Fragment>
)}
</Grid>
<Grid item xs={12} sx={modalStyleUtils.modalButtonBar}>
<Button
id={"save-tier-configuration"}
type="submit"
variant="callAction"
disabled={saving || !isFormValid}
label={"Save Tier Configuration"}
/>
</Grid>
</form>
</Grid>
</PageLayout>
</Fragment>
);
};
export default AddTierConfiguration;

View File

@@ -1,86 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2024 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React from "react";
import { ConfirmModalIcon } from "mds";
import { api } from "api";
import { setErrorSnackMessage } from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
import ConfirmDialog from "screens/Console/Common/ModalWrapper/ConfirmDialog";
interface ITierDeleteModal {
open: boolean;
closeModalAndRefresh: (refresh: boolean) => any;
tierName: string;
}
const DeleteTierConfirmModal = ({
open,
closeModalAndRefresh,
tierName,
}: ITierDeleteModal) => {
const dispatch = useAppDispatch();
const deleteTier = () => {
if (tierName !== "") {
api.admin
.removeTier(tierName)
.then(() => {
closeModalAndRefresh(true);
})
.catch((err) => {
err.json().then((body: any) => {
dispatch(
setErrorSnackMessage({
errorMessage: body.message,
detailedError: body.detailedMessage,
}),
);
});
closeModalAndRefresh(false);
});
} else {
setErrorSnackMessage({
errorMessage: "There was an error deleting the tier",
detailedError: "",
});
}
};
return (
<ConfirmDialog
title={`Delete Tier`}
confirmText={"Delete"}
isOpen={open}
titleIcon={<ConfirmModalIcon />}
isLoading={false}
onConfirm={() => deleteTier()}
onClose={() => closeModalAndRefresh(false)}
confirmationContent={
<React.Fragment>
Are you sure you want to delete the tier <strong>{tierName}</strong>?
<br />
<br />
<strong> Please note</strong>
<br /> Only empty tiers can be deleted. If the tier has had objects
transitioned into it, it cannot be removed.
</React.Fragment>
}
/>
);
};
export default DeleteTierConfirmModal;

View File

@@ -1,536 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { Fragment, useEffect, useState } from "react";
import get from "lodash/get";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import {
ActionLink,
AddIcon,
Box,
Button,
DataTable,
Grid,
HelpBox,
PageLayout,
ProgressBar,
RefreshIcon,
TierOfflineIcon,
TierOnlineIcon,
TiersIcon,
TiersNotAvailableIcon,
} from "mds";
import { api } from "api";
import { errorToHandler } from "api/errors";
import { Tier } from "api/consoleApi";
import { actionsTray } from "../../Common/FormComponents/common/styleLibrary";
import {
CONSOLE_UI_RESOURCE,
IAM_PAGES,
IAM_PERMISSIONS,
IAM_ROLES,
IAM_SCOPES,
} from "../../../../common/SecureComponent/permissions";
import {
hasPermission,
SecureComponent,
} from "../../../../common/SecureComponent";
import { tierTypes } from "./utils";
import {
selDistSet,
setErrorSnackMessage,
setHelpName,
} from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
import SearchBox from "../../Common/SearchBox";
import withSuspense from "../../Common/Components/withSuspense";
import DistributedOnly from "../../Common/DistributedOnly/DistributedOnly";
import TooltipWrapper from "../../Common/TooltipWrapper/TooltipWrapper";
import PageHeaderWrapper from "../../Common/PageHeaderWrapper/PageHeaderWrapper";
import HelpMenu from "../../HelpMenu";
import DeleteTierConfirmModal from "./DeleteTierConfirmModal";
const UpdateTierCredentialsModal = withSuspense(
React.lazy(() => import("./UpdateTierCredentialsModal")),
);
const ListTiersConfiguration = () => {
const dispatch = useAppDispatch();
const navigate = useNavigate();
const distributedSetup = useSelector(selDistSet);
const [records, setRecords] = useState<Tier[]>([]);
const [filter, setFilter] = useState<string>("");
const [isLoading, setIsLoading] = useState<boolean>(true);
const [updateCredentialsOpen, setUpdateCredentialsOpen] =
useState<boolean>(false);
const [deleteTierModalOpen, setDeleteTierModalOpen] =
useState<boolean>(false);
const [selectedTier, setSelectedTier] = useState<Tier>({
type: "unsupported",
status: false,
});
const hasSetTier = hasPermission(CONSOLE_UI_RESOURCE, [
IAM_SCOPES.ADMIN_SET_TIER,
]);
useEffect(() => {
if (isLoading) {
if (distributedSetup) {
const fetchRecords = () => {
api.admin
.tiersList()
.then((res) => {
setRecords(res.data.items || []);
setIsLoading(false);
})
.catch((err) => {
dispatch(setErrorSnackMessage(errorToHandler(err.error)));
setIsLoading(false);
});
};
fetchRecords();
} else {
setIsLoading(false);
}
}
}, [isLoading, dispatch, distributedSetup]);
const filteredRecords = records.filter((b: Tier) => {
if (filter === "") {
return true;
}
const getItemName = get(b, `${b.type}.name`, "");
const getItemType = get(b, `type`, "");
return getItemName.indexOf(filter) >= 0 || getItemType.indexOf(filter) >= 0;
});
const addTier = () => {
navigate(IAM_PAGES.TIERS_ADD);
};
const renderTierName = (item: Tier) => {
const name = get(item, `${item.type}.name`, "");
if (name !== null) {
return <b>{name}</b>;
}
return "";
};
const renderTierType = (item: string) => {
const { logoXs } =
tierTypes.find((tierConf) => tierConf.serviceName === item) || {};
if (item) {
return (
<Box
sx={{
display: "flex",
alignItems: "center",
"& .min-icon": {
width: "18px",
height: "22px",
},
}}
>
{logoXs}
</Box>
);
}
return "";
};
const renderTierStatus = (item: boolean) => {
if (item) {
return (
<Grid
container
sx={{
display: "flex",
alignItems: "center",
justifyItems: "start",
color: "#4CCB92",
fontSize: "8px",
flexDirection: "column",
}}
>
<TierOnlineIcon style={{ fill: "#4CCB92", width: 14, height: 14 }} />
ONLINE
</Grid>
);
}
return (
<Grid
container
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
color: "#C83B51",
fontSize: "8px",
}}
>
<TierOfflineIcon style={{ fill: "#C83B51", width: 14, height: 14 }} />
OFFLINE
</Grid>
);
};
const renderTierPrefix = (item: Tier) => {
const prefix = get(item, `${item.type}.prefix`, "");
if (prefix !== null) {
return prefix;
}
return "";
};
const renderTierEndpoint = (item: Tier) => {
const endpoint = get(item, `${item.type}.endpoint`, "");
if (endpoint !== null) {
return endpoint;
}
return "";
};
const renderTierBucket = (item: Tier) => {
const bucket = get(item, `${item.type}.bucket`, "");
if (bucket !== null) {
return bucket;
}
return "";
};
const renderTierRegion = (item: Tier) => {
const region = get(item, `${item.type}.region`, "");
if (region !== null) {
return region;
}
return "";
};
const renderTierUsage = (item: Tier) => {
const endpoint = get(item, `${item.type}.usage`, "");
if (endpoint !== null) {
return endpoint;
}
return "";
};
const renderTierObjects = (item: Tier) => {
const endpoint = get(item, `${item.type}.objects`, "");
if (endpoint !== null) {
return endpoint;
}
return "";
};
const renderTierVersions = (item: Tier) => {
const endpoint = get(item, `${item.type}.versions`, "");
if (endpoint !== null) {
return endpoint;
}
return "";
};
const closeTierCredentials = () => {
setUpdateCredentialsOpen(false);
};
const closeDeleteTier = () => {
setDeleteTierModalOpen(false);
setIsLoading(true);
};
useEffect(() => {
dispatch(setHelpName("list-tiers-configuration"));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<Fragment>
{updateCredentialsOpen && (
<UpdateTierCredentialsModal
open={updateCredentialsOpen}
tierData={selectedTier}
closeModalAndRefresh={closeTierCredentials}
/>
)}
{deleteTierModalOpen && (
<DeleteTierConfirmModal
open={deleteTierModalOpen}
tierName={get(selectedTier, `${selectedTier.type}.name`, "")}
closeModalAndRefresh={closeDeleteTier}
/>
)}
<PageHeaderWrapper label="Tiers" actions={<HelpMenu />} />
<PageLayout>
{!distributedSetup ? (
<DistributedOnly
entity={"Tiers"}
iconComponent={<TiersNotAvailableIcon />}
/>
) : (
<Fragment>
<Grid item xs={12} sx={actionsTray.actionsTray}>
<SearchBox
placeholder="Filter"
onChange={setFilter}
value={filter}
sx={{
marginRight: "auto",
maxWidth: 380,
}}
/>
<Box
sx={{
display: "flex",
flexWrap: "nowrap",
gap: 5,
}}
>
<Button
id={"refresh-list"}
icon={<RefreshIcon />}
label={`Refresh List`}
onClick={() => {
setIsLoading(true);
}}
/>
<TooltipWrapper
tooltip={
hasSetTier
? ""
: "You require additional permissions in order to create a new Tier. Please ask your MinIO administrator to grant you " +
IAM_SCOPES.ADMIN_SET_TIER +
" permission in order to create a Tier."
}
>
<SecureComponent
scopes={[IAM_SCOPES.ADMIN_SET_TIER]}
resource={CONSOLE_UI_RESOURCE}
errorProps={{ disabled: true }}
>
<Button
id={"add-tier"}
icon={<AddIcon />}
label={`Create Tier`}
onClick={addTier}
variant="callAction"
/>
</SecureComponent>
</TooltipWrapper>
</Box>
</Grid>
{isLoading && <ProgressBar />}
{!isLoading && (
<Fragment>
{records.length > 0 && (
<Fragment>
<Grid item xs={12}>
<SecureComponent
scopes={[IAM_SCOPES.ADMIN_LIST_TIERS]}
resource={CONSOLE_UI_RESOURCE}
errorProps={{ disabled: true }}
>
<DataTable
itemActions={[
{
type: "edit",
onClick: (tierData: Tier) => {
setSelectedTier(tierData);
setUpdateCredentialsOpen(true);
},
},
{
type: "delete",
isDisabled: !hasPermission(
"*",
IAM_PERMISSIONS[IAM_ROLES.BUCKET_LIFECYCLE],
true,
),
onClick: (tierData: Tier) => {
setSelectedTier(tierData);
setDeleteTierModalOpen(true);
},
},
]}
columns={[
{
label: "Tier Name",
elementKey: "type",
renderFunction: renderTierName,
renderFullObject: true,
},
{
label: "Status",
elementKey: "status",
renderFunction: renderTierStatus,
width: 50,
},
{
label: "Type",
elementKey: "type",
renderFunction: renderTierType,
width: 50,
},
{
label: "Endpoint",
elementKey: "type",
renderFunction: renderTierEndpoint,
renderFullObject: true,
},
{
label: "Bucket",
elementKey: "type",
renderFunction: renderTierBucket,
renderFullObject: true,
},
{
label: "Prefix",
elementKey: "type",
renderFunction: renderTierPrefix,
renderFullObject: true,
},
{
label: "Region",
elementKey: "type",
renderFunction: renderTierRegion,
renderFullObject: true,
},
{
label: "Usage",
elementKey: "type",
renderFunction: renderTierUsage,
renderFullObject: true,
},
{
label: "Objects",
elementKey: "type",
renderFunction: renderTierObjects,
renderFullObject: true,
},
{
label: "Versions",
elementKey: "type",
renderFunction: renderTierVersions,
renderFullObject: true,
},
]}
isLoading={isLoading}
records={filteredRecords}
entityName="Tiers"
idField="service_name"
customPaperHeight={"400px"}
/>
</SecureComponent>
</Grid>
<Grid
item
xs={12}
sx={{
marginTop: "15px",
}}
>
<HelpBox
title={"Learn more about TIERS"}
iconComponent={<TiersIcon />}
help={
<Fragment>
Tiers are used by the MinIO Object Lifecycle
Management which allows creating rules for time or
date based automatic transition or expiry of
objects. For object transition, MinIO automatically
moves the object to a configured remote storage
tier.
<br />
<br />
You can learn more at our{" "}
<a
href="https://min.io/docs/minio/linux/administration/object-management/object-lifecycle-management.html?ref=con"
target="_blank"
rel="noopener"
>
documentation
</a>
.
</Fragment>
}
/>
</Grid>
</Fragment>
)}
{records.length === 0 && (
<HelpBox
title={"Tiers"}
iconComponent={<TiersIcon />}
help={
<Fragment>
Tiers are used by the MinIO Object Lifecycle Management
which allows creating rules for time or date based
automatic transition or expiry of objects. For object
transition, MinIO automatically moves the object to a
configured remote storage tier.
<br />
<br />
{hasSetTier ? (
<div>
To get started,{" "}
<ActionLink
isLoading={false}
label={""}
onClick={addTier}
>
Create Tier
</ActionLink>
.
</div>
) : (
""
)}
</Fragment>
}
/>
)}
</Fragment>
)}
</Fragment>
)}
</PageLayout>
</Fragment>
);
};
export default ListTiersConfiguration;

View File

@@ -1,103 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2022 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { useState } from "react";
import { Autocomplete, InputBox, SelectorType } from "mds";
import s3Regions from "./s3-regions";
import gcsRegions from "./gcs-regions";
import azRegions from "./azure-regions";
const getRegions = (type: string): any => {
let regions: SelectorType[] = [];
if (type === "s3") {
regions = s3Regions;
}
if (type === "gcs") {
regions = gcsRegions;
}
if (type === "azure") {
regions = azRegions;
}
return regions.map((item) => ({
value: item.value,
label: `${item.label} - ${item.value}`,
}));
};
interface RegionSelectBoxProps {
label: string;
onChange: (value: string) => void;
value?: string | boolean;
id: string;
disabled?: boolean;
type: "minio" | "s3" | "gcs" | "azure";
tooltip?: string;
required?: boolean;
placeholder?: string;
}
const RegionSelectWrapper = ({
label,
onChange,
type,
tooltip = "",
required = false,
disabled,
placeholder,
}: RegionSelectBoxProps) => {
const regionList = getRegions(type);
const [value, setValue] = useState<string>("");
if (type === "minio") {
return (
<InputBox
label={label}
disabled={disabled}
required={required}
tooltip={tooltip}
value={value}
placeholder={placeholder}
id={"region-list"}
onChange={(e) => {
setValue(e.target.value);
onChange(e.target.value);
}}
/>
);
}
return (
<Autocomplete
label={label}
disabled={disabled}
required={required}
tooltip={tooltip}
options={regionList}
value={value}
placeholder={placeholder}
id={"region-list"}
onChange={(newValue) => {
setValue(newValue);
onChange(newValue);
}}
/>
);
};
export default RegionSelectWrapper;

View File

@@ -1,70 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2022 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React from "react";
import styled from "styled-components";
import get from "lodash/get";
const TierButtonBase = styled.button(({ theme }) => ({
background: get(theme, "boxBackground", "#FFF"),
border: `${get(theme, "borderColor", "#E2E2E2")} 1px solid`,
borderRadius: 5,
height: 80,
display: "flex",
alignItems: "center",
justifyContent: "start",
marginBottom: 16,
marginRight: 8,
cursor: "pointer",
overflow: "hidden",
"&:hover": {
backgroundColor: get(theme, "buttons.regular.hover.background", "#ebebeb"),
},
"& .imageContainer": {
width: 80,
"& .min-icon": {
maxWidth: 46,
maxHeight: 46,
},
},
"& .tierNotifTitle": {
color: get(theme, "buttons.callAction.enabled.background", "#07193E"),
fontSize: 16,
fontFamily: "Inter,sans-serif",
paddingLeft: 18,
fontWeight: "bold",
},
}));
type TierTypeCardProps = {
onClick: (name: string) => void;
icon?: any;
name: string;
};
const TierTypeCard = ({ onClick, icon, name }: TierTypeCardProps) => {
return (
<TierButtonBase
onClick={() => {
onClick(name);
}}
>
<span className={"imageContainer"}>{icon}</span>
<span className={"tierNotifTitle"}>{name}</span>
</TierButtonBase>
);
};
export default TierTypeCard;

View File

@@ -1,150 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { Fragment, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { tierTypes } from "./utils";
import { IAM_PAGES } from "../../../../common/SecureComponent/permissions";
import TierTypeCard from "./TierTypeCard";
import {
BackLink,
Box,
breakPoints,
FormLayout,
HelpBox,
PageLayout,
TiersIcon,
} from "mds";
import PageHeaderWrapper from "../../Common/PageHeaderWrapper/PageHeaderWrapper";
import HelpMenu from "../../HelpMenu";
import { setHelpName } from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
const TierTypeSelector = () => {
const navigate = useNavigate();
const typeSelect = (selectName: string) => {
navigate(`${IAM_PAGES.TIERS_ADD}/${selectName}`);
};
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(setHelpName("tier-type-selector"));
}, [dispatch]);
return (
<Fragment>
<PageHeaderWrapper
label={
<Fragment>
<BackLink
label="Tier Types"
onClick={() => navigate(IAM_PAGES.TIERS)}
/>
</Fragment>
}
actions={<HelpMenu />}
/>
<PageLayout>
<FormLayout
title={"Select Tier Type"}
icon={<TiersIcon />}
helpBox={
<HelpBox
iconComponent={<TiersIcon />}
title={"Tier Types"}
help={
<Fragment>
MinIO supports creating object transition lifecycle management
rules, where MinIO can automatically move an object to a
remote storage tier.
<br />
<br />
MinIO supports the following Tier types:
<br />
<ul>
<li>
<a
href="https://min.io/docs/minio/kubernetes/upstream/administration/object-management/transition-objects-to-s3.html#minio-lifecycle-management-transition-to-s3?ref=con"
target="_blank"
rel="noopener"
>
MinIO or other S3-compatible storage
</a>
</li>
<li>
<a
href="https://min.io/docs/minio/kubernetes/upstream/administration/object-management/transition-objects-to-s3.html#minio-lifecycle-management-transition-to-s3?ref=con"
target="_blank"
rel="noopener"
>
Amazon S3
</a>
</li>
<li>
<a
href="https://min.io/docs/minio/kubernetes/upstream/administration/object-management/transition-objects-to-gcs.html#minio-lifecycle-management-transition-to-gcs?ref=con"
target="_blank"
rel="noopener"
>
Google Cloud Storage
</a>
</li>
<li>
<a
href="https://min.io/docs/minio/kubernetes/upstream/administration/object-management/transition-objects-to-azure.html#minio-lifecycle-management-transition-to-azure?ref=con"
target="_blank"
rel="noopener"
>
Microsoft Azure Blob Storage
</a>
</li>
</ul>
</Fragment>
}
/>
}
>
<Box
sx={{
margin: "15px",
display: "grid",
gridGap: "20px",
gridTemplateColumns: "repeat(2, 1fr)",
[`@media (max-width: ${breakPoints.md}px)`]: {
gridTemplateColumns: "repeat(1, 1fr)",
},
}}
>
{tierTypes.map((tierType, index) => (
<TierTypeCard
key={`tierOpt-${index.toString}-${tierType.targetTitle}`}
name={tierType.targetTitle}
onClick={() => {
typeSelect(tierType.serviceName);
}}
icon={tierType.logo}
/>
))}
</Box>
</FormLayout>
</PageLayout>
</Fragment>
);
};
export default TierTypeSelector;

View File

@@ -1,217 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { Fragment, useEffect, useState } from "react";
import get from "lodash/get";
import {
Button,
FileSelector,
FormLayout,
Grid,
InputBox,
LockIcon,
ProgressBar,
} from "mds";
import { Tier } from "api/consoleApi";
import { api } from "api";
import { errorToHandler } from "api/errors";
import { modalStyleUtils } from "../../Common/FormComponents/common/styleLibrary";
import { setModalErrorSnackMessage } from "../../../../systemSlice";
import { useAppDispatch } from "../../../../store";
import ModalWrapper from "../../Common/ModalWrapper/ModalWrapper";
interface ITierCredentialsModal {
open: boolean;
closeModalAndRefresh: (refresh: boolean) => any;
tierData: Tier;
}
const UpdateTierCredentialsModal = ({
open,
closeModalAndRefresh,
tierData,
}: ITierCredentialsModal) => {
const dispatch = useAppDispatch();
const [savingTiers, setSavingTiers] = useState<boolean>(false);
const [creds, setCreds] = useState<string>("");
const [encodedCreds, setEncodedCreds] = useState<string>("");
const [accountName, setAccountName] = useState<string>("");
const [accountKey, setAccountKey] = useState<string>("");
// Validations
const [isFormValid, setIsFormValid] = useState<boolean>(true);
const type = get(tierData, "type", "");
const name = get(tierData, `${type}.name`, "");
useEffect(() => {
let valid = true;
if (type === "s3" || type === "azure" || type === "minio") {
if (accountName === "" || accountKey === "") {
valid = false;
}
} else if (type === "gcs") {
if (encodedCreds === "") {
valid = false;
}
}
setIsFormValid(valid);
}, [accountKey, accountName, encodedCreds, type]);
const addRecord = () => {
let rules = {};
if (type === "s3" || type === "azure" || type === "minio") {
rules = {
access_key: accountName,
secret_key: accountKey,
};
} else if (type === "gcs") {
rules = {
creds: encodedCreds,
};
}
if (name !== "") {
api.admin
.editTierCredentials(
type as "azure" | "s3" | "minio" | "gcs",
name,
rules,
)
.then(() => {
setSavingTiers(false);
closeModalAndRefresh(true);
})
.catch((err) => {
setSavingTiers(false);
dispatch(setModalErrorSnackMessage(errorToHandler(err.error)));
});
} else {
setModalErrorSnackMessage({
errorMessage: "There was an error retrieving tier information",
detailedError: "",
});
}
};
return (
<ModalWrapper
modalOpen={open}
titleIcon={<LockIcon />}
onClose={() => {
closeModalAndRefresh(false);
}}
title={`Update Credentials - ${type} / ${name}`}
>
<form
noValidate
autoComplete="off"
onSubmit={(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setSavingTiers(true);
addRecord();
}}
>
<FormLayout withBorders={false} containerPadding={false}>
{(type === "s3" || type === "minio") && (
<Fragment>
<InputBox
id="accessKey"
name="accessKey"
label="Access Key"
placeholder="Enter Access Key"
value={accountName}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setAccountName(e.target.value);
}}
/>
<InputBox
id="secretKey"
name="secretKey"
label="Secret Key"
placeholder="Enter Secret Key"
value={accountKey}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setAccountKey(e.target.value);
}}
/>
</Fragment>
)}
{type === "gcs" && (
<Fragment>
<FileSelector
accept=".json"
id="creds"
label="Credentials"
name="creds"
returnEncodedData
onChange={(_, fileName, encodedValue) => {
if (encodedValue) {
setEncodedCreds(encodedValue);
setCreds(fileName);
}
}}
value={creds}
/>
</Fragment>
)}
{type === "azure" && (
<Fragment>
<InputBox
id="accountName"
name="accountName"
label="Account Name"
placeholder="Enter Account Name"
value={accountName}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setAccountName(e.target.value);
}}
/>
<InputBox
id="accountKey"
name="accountKey"
label="Account Key"
placeholder="Enter Account Key"
value={accountKey}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setAccountKey(e.target.value);
}}
/>
</Fragment>
)}
</FormLayout>
{savingTiers && (
<Grid item xs={12}>
<ProgressBar />
</Grid>
)}
<Grid item xs={12} sx={modalStyleUtils.modalButtonBar}>
<Button
id={"save-credentials"}
type="submit"
variant="callAction"
disabled={savingTiers || !isFormValid}
label={"Save"}
/>
</Grid>
</form>
</ModalWrapper>
);
};
export default UpdateTierCredentialsModal;

View File

@@ -1,321 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2022 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { SelectorType } from "mds";
const azureRegions: SelectorType[] = [
{
label: "Asia",
value: "asia",
},
{
label: "Asia Pacific",
value: "asiapacific",
},
{
label: "Australia",
value: "australia",
},
{
label: "Australia Central",
value: "australiacentral",
},
{
label: "Australia Central 2",
value: "australiacentral2",
},
{
label: "Australia East",
value: "australiaeast",
},
{
label: "Australia Southeast",
value: "australiasoutheast",
},
{
label: "Brazil",
value: "brazil",
},
{
label: "Brazil South",
value: "brazilsouth",
},
{
label: "Brazil Southeast",
value: "brazilsoutheast",
},
{
label: "Canada",
value: "canada",
},
{
label: "Canada Central",
value: "canadacentral",
},
{
label: "Canada East",
value: "canadaeast",
},
{
label: "Central India",
value: "centralindia",
},
{
label: "Central US",
value: "centralus",
},
{
label: "Central US (Stage)",
value: "centralusstage",
},
{
label: "Central US EUAP",
value: "centraluseuap",
},
{
label: "East Asia",
value: "eastasia",
},
{
label: "East Asia (Stage)",
value: "eastasiastage",
},
{
label: "East US",
value: "eastus",
},
{
label: "East US (Stage)",
value: "eastusstage",
},
{
label: "East US 2",
value: "eastus2",
},
{
label: "East US 2 (Stage)",
value: "eastus2stage",
},
{
label: "East US 2 EUAP",
value: "eastus2euap",
},
{
label: "Europe",
value: "europe",
},
{
label: "France",
value: "france",
},
{
label: "France Central",
value: "francecentral",
},
{
label: "France South",
value: "francesouth",
},
{
label: "Germany",
value: "germany",
},
{
label: "Germany North",
value: "germanynorth",
},
{
label: "Germany West Central",
value: "germanywestcentral",
},
{
label: "Global",
value: "global",
},
{
label: "India",
value: "india",
},
{
label: "Japan",
value: "japan",
},
{
label: "Japan East",
value: "japaneast",
},
{
label: "Japan West",
value: "japanwest",
},
{
label: "Jio India Central",
value: "jioindiacentral",
},
{
label: "Jio India West",
value: "jioindiawest",
},
{
label: "Korea",
value: "korea",
},
{
label: "Korea Central",
value: "koreacentral",
},
{
label: "Korea South",
value: "koreasouth",
},
{
label: "North Central US",
value: "northcentralus",
},
{
label: "North Central US (Stage)",
value: "northcentralusstage",
},
{
label: "North Europe",
value: "northeurope",
},
{
label: "Norway",
value: "norway",
},
{
label: "Norway East",
value: "norwayeast",
},
{
label: "Norway West",
value: "norwaywest",
},
{
label: "South Africa",
value: "southafrica",
},
{
label: "South Africa North",
value: "southafricanorth",
},
{
label: "South Africa West",
value: "southafricawest",
},
{
label: "South Central US",
value: "southcentralus",
},
{
label: "South Central US (Stage)",
value: "southcentralusstage",
},
{
label: "South India",
value: "southindia",
},
{
label: "Southeast Asia",
value: "southeastasia",
},
{
label: "Southeast Asia (Stage)",
value: "southeastasiastage",
},
{
label: "Sweden Central",
value: "swedencentral",
},
{
label: "Switzerland",
value: "switzerland",
},
{
label: "Switzerland North",
value: "switzerlandnorth",
},
{
label: "Switzerland West",
value: "switzerlandwest",
},
{
label: "UAE Central",
value: "uaecentral",
},
{
label: "UAE North",
value: "uaenorth",
},
{
label: "UK South",
value: "uksouth",
},
{
label: "UK West",
value: "ukwest",
},
{
label: "United Arab Emirates",
value: "uae",
},
{
label: "United Kingdom",
value: "uk",
},
{
label: "United States",
value: "unitedstates",
},
{
label: "United States EUAP",
value: "unitedstateseuap",
},
{
label: "West Central US",
value: "westcentralus",
},
{
label: "West Europe",
value: "westeurope",
},
{
label: "West India",
value: "westindia",
},
{
label: "West US",
value: "westus",
},
{
label: "West US (Stage)",
value: "westusstage",
},
{
label: "West US 2",
value: "westus2",
},
{
label: "West US 2 (Stage)",
value: "westus2stage",
},
{
label: "West US 3",
value: "westus3",
},
];
export default azureRegions;

View File

@@ -1,51 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2022 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { SelectorType } from "mds";
const gcsRegions: SelectorType[] = [
{ label: "Montréal", value: "NORTHAMERICA-NORTHEAST1" },
{ label: "Toronto", value: "NORTHAMERICA-NORTHEAST2" },
{ label: "Iowa", value: "US-CENTRAL1" },
{ label: "South Carolina", value: "US-EAST1" },
{ label: "Northern Virginia", value: "US-EAST4" },
{ label: "Oregon", value: "US-WEST1" },
{ label: "Los Angeles", value: "US-WEST2" },
{ label: "Salt Lake City", value: "US-WEST3" },
{ label: "Las Vegas", value: "US-WEST4" },
{ label: "São Paulo", value: "SOUTHAMERICA-EAST1" },
{ label: "Santiago", value: "SOUTHAMERICA-WEST1" },
{ label: "Warsaw", value: "EUROPE-CENTRAL2" },
{ label: "Finland", value: "EUROPE-NORTH1" },
{ label: "Belgium", value: "EUROPE-WEST1" },
{ label: "London", value: "EUROPE-WEST2" },
{ label: "Frankfurt", value: "EUROPE-WEST3" },
{ label: "Netherlands", value: "EUROPE-WEST4" },
{ label: "Zürich", value: "EUROPE-WEST6" },
{ label: "Taiwan", value: "ASIA-EAST1" },
{ label: "Hong Kong", value: "ASIA-EAST2" },
{ label: "Tokyo", value: "ASIA-NORTHEAST1" },
{ label: "Osaka", value: "ASIA-NORTHEAST2" },
{ label: "Seoul", value: "ASIA-NORTHEAST3" },
{ label: "Mumbai", value: "ASIA-SOUTH1" },
{ label: "Delhi", value: "ASIA-SOUTH2" },
{ label: "Singapore", value: "ASIA-SOUTHEAST1" },
{ label: "Jakarta", value: "ASIA-SOUTHEAST2" },
{ label: "Sydney", value: "AUSTRALIA-SOUTHEAST1" },
{ label: "Melbourne", value: "AUSTRALIA-SOUTHEAST2" },
];
export default gcsRegions;

View File

@@ -1,48 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2022 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import { SelectorType } from "mds";
const s3Regions: SelectorType[] = [
{ label: "US East (Ohio)", value: "us-east-2" },
{ label: "US East (N. Virginia)", value: "us-east-1" },
{ label: "US West (N. California)", value: "us-west-1" },
{ label: "US West (Oregon)", value: "us-west-2" },
{ label: "Africa (Cape Town)", value: "af-south-1" },
{ label: "Asia Pacific (Hong Kong)***", value: "ap-east-1" },
{ label: "Asia Pacific (Jakarta)", value: "ap-southeast-3" },
{ label: "Asia Pacific (Mumbai)", value: "ap-south-1" },
{ label: "Asia Pacific (Osaka)", value: "ap-northeast-3" },
{ label: "Asia Pacific (Seoul)", value: "ap-northeast-2" },
{ label: "Asia Pacific (Singapore)", value: "ap-southeast-1" },
{ label: "Asia Pacific (Sydney)", value: "ap-southeast-2" },
{ label: "Asia Pacific (Tokyo)", value: "ap-northeast-1" },
{ label: "Canada (Central)", value: "ca-central-1" },
{ label: "China (Beijing)", value: "cn-north-1" },
{ label: "China (Ningxia)", value: "cn-northwest-1" },
{ label: "Europe (Frankfurt)", value: "eu-central-1" },
{ label: "Europe (Ireland)", value: "eu-west-1" },
{ label: "Europe (London)", value: "eu-west-2" },
{ label: "Europe (Milan)", value: "eu-south-1" },
{ label: "Europe (Paris)", value: "eu-west-3" },
{ label: "Europe (Stockholm)", value: "eu-north-1" },
{ label: "South America (São Paulo)", value: "sa-east-1" },
{ label: "Middle East (Bahrain)", value: "me-south-1" },
{ label: "AWS GovCloud (US-East)", value: "us-gov-east-1" },
{ label: "AWS GovCloud (US-West)", value: "us-gov-west-1" },
];
export default s3Regions;

View File

@@ -1,58 +0,0 @@
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import {
AzureTierIcon,
AzureTierIconXs,
GoogleTierIcon,
GoogleTierIconXs,
MinIOTierIcon,
MinIOTierIconXs,
S3TierIcon,
S3TierIconXs,
} from "mds";
export const minioServiceName = "minio";
export const gcsServiceName = "gcs";
export const s3ServiceName = "s3";
export const azureServiceName = "azure";
export const tierTypes = [
{
serviceName: minioServiceName,
targetTitle: "MinIO",
logo: <MinIOTierIcon />,
logoXs: <MinIOTierIconXs />,
},
{
serviceName: gcsServiceName,
targetTitle: "Google Cloud Storage",
logo: <GoogleTierIcon />,
logoXs: <GoogleTierIconXs />,
},
{
serviceName: s3ServiceName,
targetTitle: "AWS S3",
logo: <S3TierIcon />,
logoXs: <S3TierIconXs />,
},
{
serviceName: azureServiceName,
targetTitle: "Azure",
logo: <AzureTierIcon />,
logoXs: <AzureTierIconXs />,
},
];

Some files were not shown because too many files have changed in this diff Show More