From 5fd82ca6e9301c7cc62b5aea1d967677ae946df4 Mon Sep 17 00:00:00 2001 From: Alex <33497058+bexsoft@users.noreply.github.com> Date: Thu, 10 Feb 2022 17:25:59 -0700 Subject: [PATCH] Added delete bucket lifecycle rule capability (#1547) Signed-off-by: Benjamin Perez Co-authored-by: Benjamin Perez --- models/lifecycle_rule_type.go | 95 -------------- .../BucketDetails/BucketLifecyclePanel.tsx | 30 +++++ .../DeleteBucketLifecycleRule.tsx | 93 +++++++++++++ .../EditLifecycleConfiguration.tsx | 1 - restapi/embedded_spec.go | 64 +++++++++ restapi/operations/console_api.go | 12 ++ .../user_api/delete_bucket_lifecycle_rule.go | 88 +++++++++++++ ...delete_bucket_lifecycle_rule_parameters.go | 112 ++++++++++++++++ .../delete_bucket_lifecycle_rule_responses.go | 113 ++++++++++++++++ ...delete_bucket_lifecycle_rule_urlbuilder.go | 124 ++++++++++++++++++ restapi/user_buckets_lifecycle.go | 64 ++++++++- restapi/user_buckets_lifecycle_test.go | 72 ++++++++++ swagger-console.yml | 22 ++++ 13 files changed, 793 insertions(+), 97 deletions(-) delete mode 100644 models/lifecycle_rule_type.go create mode 100644 portal-ui/src/screens/Console/Buckets/BucketDetails/DeleteBucketLifecycleRule.tsx create mode 100644 restapi/operations/user_api/delete_bucket_lifecycle_rule.go create mode 100644 restapi/operations/user_api/delete_bucket_lifecycle_rule_parameters.go create mode 100644 restapi/operations/user_api/delete_bucket_lifecycle_rule_responses.go create mode 100644 restapi/operations/user_api/delete_bucket_lifecycle_rule_urlbuilder.go diff --git a/models/lifecycle_rule_type.go b/models/lifecycle_rule_type.go deleted file mode 100644 index d37ce7d19..000000000 --- a/models/lifecycle_rule_type.go +++ /dev/null @@ -1,95 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// 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 . -// - -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/validate" -) - -// LifecycleRuleType lifecycle rule type -// -// swagger:model lifecycleRuleType -type LifecycleRuleType string - -func NewLifecycleRuleType(value LifecycleRuleType) *LifecycleRuleType { - return &value -} - -// Pointer returns a pointer to a freshly-allocated LifecycleRuleType. -func (m LifecycleRuleType) Pointer() *LifecycleRuleType { - return &m -} - -const ( - - // LifecycleRuleTypeExpiry captures enum value "expiry" - LifecycleRuleTypeExpiry LifecycleRuleType = "expiry" - - // LifecycleRuleTypeTransition captures enum value "transition" - LifecycleRuleTypeTransition LifecycleRuleType = "transition" -) - -// for schema -var lifecycleRuleTypeEnum []interface{} - -func init() { - var res []LifecycleRuleType - if err := json.Unmarshal([]byte(`["expiry","transition"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - lifecycleRuleTypeEnum = append(lifecycleRuleTypeEnum, v) - } -} - -func (m LifecycleRuleType) validateLifecycleRuleTypeEnum(path, location string, value LifecycleRuleType) error { - if err := validate.EnumCase(path, location, value, lifecycleRuleTypeEnum, true); err != nil { - return err - } - return nil -} - -// Validate validates this lifecycle rule type -func (m LifecycleRuleType) Validate(formats strfmt.Registry) error { - var res []error - - // value enum - if err := m.validateLifecycleRuleTypeEnum("", "body", m); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContextValidate validates this lifecycle rule type based on context it is used -func (m LifecycleRuleType) ContextValidate(ctx context.Context, formats strfmt.Registry) error { - return nil -} diff --git a/portal-ui/src/screens/Console/Buckets/BucketDetails/BucketLifecyclePanel.tsx b/portal-ui/src/screens/Console/Buckets/BucketDetails/BucketLifecyclePanel.tsx index 48b0b350a..f00b8fca1 100644 --- a/portal-ui/src/screens/Console/Buckets/BucketDetails/BucketLifecyclePanel.tsx +++ b/portal-ui/src/screens/Console/Buckets/BucketDetails/BucketLifecyclePanel.tsx @@ -42,6 +42,7 @@ import SecureComponent, { } from "../../../../common/SecureComponent/SecureComponent"; import { IAM_SCOPES } from "../../../../common/SecureComponent/permissions"; import RBIconButton from "./SummaryItems/RBIconButton"; +import DeleteBucketLifecycleRule from "./DeleteBucketLifecycleRule"; const styles = (theme: Theme) => createStyles({ @@ -73,6 +74,9 @@ const BucketLifecyclePanel = ({ const [editLifecycleOpen, setEditLifecycleOpen] = useState(false); const [selectedLifecycleRule, setSelectedLifecycleRule] = useState(null); + const [deleteLifecycleOpen, setDeleteLifecycleOpen] = + useState(false); + const [selectedID, setSelectedID] = useState(null); const bucketName = match.params["bucketName"]; @@ -99,6 +103,7 @@ const BucketLifecyclePanel = ({ }) .catch((err: ErrorResponseHandler) => { console.error(err); + setLifecycleRecords([]); setLoadingLifecycle(false); }); } else { @@ -127,6 +132,15 @@ const BucketLifecyclePanel = ({ } }; + const closeDelLCRefresh = (refresh: boolean) => { + setDeleteLifecycleOpen(false); + setSelectedID(null); + + if (refresh) { + setLoadingLifecycle(true); + } + }; + const expirationRender = (expiration: any) => { if (expiration.days) { return `${expiration.days} day${expiration.days > 1 ? "s" : ""}`; @@ -194,6 +208,14 @@ const BucketLifecyclePanel = ({ setEditLifecycleOpen(true); }, }, + { + type: "delete", + onClick(valueToDelete: string): any { + setSelectedID(valueToDelete); + setDeleteLifecycleOpen(true); + }, + sendOnlyId: true, + }, ]; return ( @@ -213,6 +235,14 @@ const BucketLifecyclePanel = ({ closeModalAndRefresh={closeAddLCAndRefresh} /> )} + {deleteLifecycleOpen && selectedID && ( + + )} Lifecycle Rules diff --git a/portal-ui/src/screens/Console/Buckets/BucketDetails/DeleteBucketLifecycleRule.tsx b/portal-ui/src/screens/Console/Buckets/BucketDetails/DeleteBucketLifecycleRule.tsx new file mode 100644 index 000000000..ecb8a42a0 --- /dev/null +++ b/portal-ui/src/screens/Console/Buckets/BucketDetails/DeleteBucketLifecycleRule.tsx @@ -0,0 +1,93 @@ +// 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 . + +import React, { useState, useEffect } from "react"; +import { connect } from "react-redux"; +import { DialogContentText } from "@mui/material"; +import { Theme } from "@mui/material/styles"; +import createStyles from "@mui/styles/createStyles"; +import withStyles from "@mui/styles/withStyles"; +import { modalBasic } from "../../Common/FormComponents/common/styleLibrary"; +import { ErrorResponseHandler } from "../../../../common/types"; +import { setErrorSnackMessage } from "../../../../actions"; +import { ConfirmDeleteIcon } from "../../../../icons"; +import ConfirmDialog from "../../Common/ModalWrapper/ConfirmDialog"; +import api from "../../../../common/api"; + +interface IDeleteLifecycleRule { + deleteOpen: boolean; + onCloseAndRefresh: (refresh: boolean) => any; + bucket: string; + id: string; + setErrorSnackMessage: typeof setErrorSnackMessage; +} + +const styles = (theme: Theme) => + createStyles({ + ...modalBasic, + }); + +const DeleteBucketLifecycleRule = ({ + onCloseAndRefresh, + deleteOpen, + bucket, + id, + setErrorSnackMessage, +}: IDeleteLifecycleRule) => { + const [deletingRule, setDeletingRule] = useState(false); + + useEffect(() => { + if (deletingRule) { + api + .invoke("DELETE", `/api/v1/buckets/${bucket}/lifecycle/${id}`) + .then((res) => { + setDeletingRule(false); + onCloseAndRefresh(true); + }) + .catch((err: ErrorResponseHandler) => { + setDeletingRule(false); + setErrorSnackMessage(err); + }); + } + }, [deletingRule, bucket, id, onCloseAndRefresh, setErrorSnackMessage]); + + const onConfirmDelete = () => { + setDeletingRule(true); + }; + + return ( + } + onClose={() => onCloseAndRefresh(false)} + confirmationContent={ + + Are you sure you want to delete the {id} rule? + + } + /> + ); +}; + +const connector = connect(null, { + setErrorSnackMessage, +}); + +export default withStyles(styles)(connector(DeleteBucketLifecycleRule)); diff --git a/portal-ui/src/screens/Console/Buckets/BucketDetails/EditLifecycleConfiguration.tsx b/portal-ui/src/screens/Console/Buckets/BucketDetails/EditLifecycleConfiguration.tsx index b4cbc42ef..64d8178ed 100644 --- a/portal-ui/src/screens/Console/Buckets/BucketDetails/EditLifecycleConfiguration.tsx +++ b/portal-ui/src/screens/Console/Buckets/BucketDetails/EditLifecycleConfiguration.tsx @@ -141,7 +141,6 @@ const EditLifecycleConfiguration = ({ }, [ilmType, expiryDays, transitionDays, storageClass]); useEffect(() => { - console.log("lifecycle::", lifecycle); if (lifecycle.status === "Enabled") { setEnabled(true); } diff --git a/restapi/embedded_spec.go b/restapi/embedded_spec.go index e43e0c3f0..d605d691e 100644 --- a/restapi/embedded_spec.go +++ b/restapi/embedded_spec.go @@ -1061,6 +1061,38 @@ func init() { } } } + }, + "delete": { + "tags": [ + "UserAPI" + ], + "summary": "Delete Lifecycle rule", + "operationId": "DeleteBucketLifecycleRule", + "parameters": [ + { + "type": "string", + "name": "bucket_name", + "in": "path", + "required": true + }, + { + "type": "string", + "name": "lifecycle_id", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "A successful response." + }, + "default": { + "description": "Generic error response.", + "schema": { + "$ref": "#/definitions/error" + } + } + } } }, "/buckets/{bucket_name}/object-locking": { @@ -7234,6 +7266,38 @@ func init() { } } } + }, + "delete": { + "tags": [ + "UserAPI" + ], + "summary": "Delete Lifecycle rule", + "operationId": "DeleteBucketLifecycleRule", + "parameters": [ + { + "type": "string", + "name": "bucket_name", + "in": "path", + "required": true + }, + { + "type": "string", + "name": "lifecycle_id", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "A successful response." + }, + "default": { + "description": "Generic error response.", + "schema": { + "$ref": "#/definitions/error" + } + } + } } }, "/buckets/{bucket_name}/object-locking": { diff --git a/restapi/operations/console_api.go b/restapi/operations/console_api.go index 7a6427731..7f42e873e 100644 --- a/restapi/operations/console_api.go +++ b/restapi/operations/console_api.go @@ -137,6 +137,9 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI { UserAPIDeleteBucketEventHandler: user_api.DeleteBucketEventHandlerFunc(func(params user_api.DeleteBucketEventParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation user_api.DeleteBucketEvent has not yet been implemented") }), + UserAPIDeleteBucketLifecycleRuleHandler: user_api.DeleteBucketLifecycleRuleHandlerFunc(func(params user_api.DeleteBucketLifecycleRuleParams, principal *models.Principal) middleware.Responder { + return middleware.NotImplemented("operation user_api.DeleteBucketLifecycleRule has not yet been implemented") + }), UserAPIDeleteBucketReplicationRuleHandler: user_api.DeleteBucketReplicationRuleHandlerFunc(func(params user_api.DeleteBucketReplicationRuleParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation user_api.DeleteBucketReplicationRule has not yet been implemented") }), @@ -492,6 +495,8 @@ type ConsoleAPI struct { UserAPIDeleteBucketHandler user_api.DeleteBucketHandler // UserAPIDeleteBucketEventHandler sets the operation handler for the delete bucket event operation UserAPIDeleteBucketEventHandler user_api.DeleteBucketEventHandler + // UserAPIDeleteBucketLifecycleRuleHandler sets the operation handler for the delete bucket lifecycle rule operation + UserAPIDeleteBucketLifecycleRuleHandler user_api.DeleteBucketLifecycleRuleHandler // UserAPIDeleteBucketReplicationRuleHandler sets the operation handler for the delete bucket replication rule operation UserAPIDeleteBucketReplicationRuleHandler user_api.DeleteBucketReplicationRuleHandler // UserAPIDeleteMultipleObjectsHandler sets the operation handler for the delete multiple objects operation @@ -819,6 +824,9 @@ func (o *ConsoleAPI) Validate() error { if o.UserAPIDeleteBucketEventHandler == nil { unregistered = append(unregistered, "user_api.DeleteBucketEventHandler") } + if o.UserAPIDeleteBucketLifecycleRuleHandler == nil { + unregistered = append(unregistered, "user_api.DeleteBucketLifecycleRuleHandler") + } if o.UserAPIDeleteBucketReplicationRuleHandler == nil { unregistered = append(unregistered, "user_api.DeleteBucketReplicationRuleHandler") } @@ -1272,6 +1280,10 @@ func (o *ConsoleAPI) initHandlerCache() { if o.handlers["DELETE"] == nil { o.handlers["DELETE"] = make(map[string]http.Handler) } + o.handlers["DELETE"]["/buckets/{bucket_name}/lifecycle/{lifecycle_id}"] = user_api.NewDeleteBucketLifecycleRule(o.context, o.UserAPIDeleteBucketLifecycleRuleHandler) + if o.handlers["DELETE"] == nil { + o.handlers["DELETE"] = make(map[string]http.Handler) + } o.handlers["DELETE"]["/buckets/{bucket_name}/replication/{rule_id}"] = user_api.NewDeleteBucketReplicationRule(o.context, o.UserAPIDeleteBucketReplicationRuleHandler) if o.handlers["POST"] == nil { o.handlers["POST"] = make(map[string]http.Handler) diff --git a/restapi/operations/user_api/delete_bucket_lifecycle_rule.go b/restapi/operations/user_api/delete_bucket_lifecycle_rule.go new file mode 100644 index 000000000..4060921ef --- /dev/null +++ b/restapi/operations/user_api/delete_bucket_lifecycle_rule.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// 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 . +// + +package user_api + +// 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} UserAPI 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) + +} diff --git a/restapi/operations/user_api/delete_bucket_lifecycle_rule_parameters.go b/restapi/operations/user_api/delete_bucket_lifecycle_rule_parameters.go new file mode 100644 index 000000000..686e54f9b --- /dev/null +++ b/restapi/operations/user_api/delete_bucket_lifecycle_rule_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// 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 . +// + +package user_api + +// 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 +} diff --git a/restapi/operations/user_api/delete_bucket_lifecycle_rule_responses.go b/restapi/operations/user_api/delete_bucket_lifecycle_rule_responses.go new file mode 100644 index 000000000..09f73d918 --- /dev/null +++ b/restapi/operations/user_api/delete_bucket_lifecycle_rule_responses.go @@ -0,0 +1,113 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// 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 . +// + +package user_api + +// 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.Error `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.Error) *DeleteBucketLifecycleRuleDefault { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the delete bucket lifecycle rule default response +func (o *DeleteBucketLifecycleRuleDefault) SetPayload(payload *models.Error) { + 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 + } + } +} diff --git a/restapi/operations/user_api/delete_bucket_lifecycle_rule_urlbuilder.go b/restapi/operations/user_api/delete_bucket_lifecycle_rule_urlbuilder.go new file mode 100644 index 000000000..6634a031a --- /dev/null +++ b/restapi/operations/user_api/delete_bucket_lifecycle_rule_urlbuilder.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// 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 . +// + +package user_api + +// 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() +} diff --git a/restapi/user_buckets_lifecycle.go b/restapi/user_buckets_lifecycle.go index e43aeb2c7..465bbd58f 100644 --- a/restapi/user_buckets_lifecycle.go +++ b/restapi/user_buckets_lifecycle.go @@ -19,6 +19,7 @@ package restapi import ( "context" "errors" + "fmt" "strconv" "strings" "time" @@ -61,6 +62,14 @@ func registerBucketsLifecycleHandlers(api *operations.ConsoleAPI) { return user_api.NewUpdateBucketLifecycleOK() }) + api.UserAPIDeleteBucketLifecycleRuleHandler = user_api.DeleteBucketLifecycleRuleHandlerFunc(func(params user_api.DeleteBucketLifecycleRuleParams, session *models.Principal) middleware.Responder { + err := getDeleteBucketLifecycleRule(session, params) + if err != nil { + return user_api.NewDeleteBucketLifecycleRuleDefault(int(err.Code)).WithPayload(err) + } + + return user_api.NewDeleteBucketLifecycleRuleNoContent() + }) } // getBucketLifecycle() gets lifecycle lists for a bucket from MinIO API and returns their implementations @@ -338,7 +347,7 @@ func editBucketLifecycle(ctx context.Context, client MinioClient, params user_ap return client.setBucketLifecycle(ctx, params.BucketName, lfcCfg) } -// getEditBucketLifecycleRule returns the response of bucket lyfecycle tier edit +// getEditBucketLifecycleRule returns the response of bucket lifecycle tier edit func getEditBucketLifecycleRule(session *models.Principal, params user_api.UpdateBucketLifecycleParams) *models.Error { ctx := context.Background() mClient, err := newMinioClient(session) @@ -356,3 +365,56 @@ func getEditBucketLifecycleRule(session *models.Principal, params user_api.Updat return nil } + +// deleteBucketLifecycle deletes lifecycle rule by passing an empty rule to a selected ID +func deleteBucketLifecycle(ctx context.Context, client MinioClient, params user_api.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 user_api.DeleteBucketLifecycleRuleParams) *models.Error { + ctx := context.Background() + mClient, err := newMinioClient(session) + if err != nil { + return prepareError(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 prepareError(err) + } + + return nil +} diff --git a/restapi/user_buckets_lifecycle_test.go b/restapi/user_buckets_lifecycle_test.go index c07f8ea99..429b96558 100644 --- a/restapi/user_buckets_lifecycle_test.go +++ b/restapi/user_buckets_lifecycle_test.go @@ -290,3 +290,75 @@ func TestUpdateLifecycleRule(t *testing.T) { 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 := context.Background() + + minioSetBucketLifecycleMock = func(ctx context.Context, bucketName string, config *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(ctx context.Context, bucketName string) (lifecycle *lifecycle.Configuration, err error) { + return &mockLifecycle, nil + } + + // Test-2 : deleteBucketLifecycle() try to delete an available rule + + availableParams := user_api.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 := user_api.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(ctx context.Context, bucketName 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)) +} diff --git a/swagger-console.yml b/swagger-console.yml index 0450273c3..61db47cb0 100644 --- a/swagger-console.yml +++ b/swagger-console.yml @@ -1143,6 +1143,28 @@ paths: tags: - UserAPI + 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/error" + tags: + - UserAPI + /buckets/{bucket_name}/rewind/{date}: get: summary: Get objects in a bucket for a rewind date