Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ROX-22360: E2E Test for expiration manager #1644

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions internal/dinosaur/pkg/workers/dinosaurmgrs/expiration_date_mgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,30 +104,36 @@ func (k *ExpirationDateManager) reconcileCentralExpiredAt(centrals dbapi.Central
quotaCostCache[key] = active
}

if err := k.updateExpiredAtBasedOnQuotaEntitlement(central, active); err != nil {
svcErrors = append(svcErrors, errors.Wrapf(err, "failed to update expired_at value based on quota entitlement for central instance %q", central.ID))
if timestamp, needsChange := k.expiredAtNeedsUpdate(central, active); needsChange {
central.ExpiredAt = timestamp
if err := k.updateExpiredAtInDB(central); err != nil {
svcErrors = append(svcErrors, errors.Wrapf(err,
"failed to update expired_at value based on quota entitlement for central instance %q", central.ID))
}
}
}

return svcErrors
}

// Updates expired_at field of the given Central instance based on the user/organisation's quota entitlement status
func (k *ExpirationDateManager) updateExpiredAtBasedOnQuotaEntitlement(central *dbapi.CentralRequest, isQuotaEntitlementActive bool) *serviceErr.ServiceError {
func (k *ExpirationDateManager) updateExpiredAtInDB(central *dbapi.CentralRequest) *serviceErr.ServiceError {
glog.Infof("updating expired_at of central %q to %q", central.ID, central.ExpiredAt)
return k.centralService.Updates(&dbapi.CentralRequest{Meta: api.Meta{ID: central.ID}},
map[string]interface{}{"expired_at": central.ExpiredAt})
}

// Returns whether the expired_at field of the given Central instance needs to be updated.
func (k *ExpirationDateManager) expiredAtNeedsUpdate(central *dbapi.CentralRequest, isQuotaEntitlementActive bool) (*time.Time, bool) {
// if quota entitlement is active, ensure expired_at is set to null.
if isQuotaEntitlementActive && central.ExpiredAt != nil {
central.ExpiredAt = nil
glog.Infof("updating expiration date of central instance %q to NULL", central.ID)
return k.centralService.Update(central)
return nil, true
}

// if quota entitlement is not active and expired_at is not already set, set
// its value to the current time.
if !isQuotaEntitlementActive && central.ExpiredAt == nil {
now := time.Now()
central.ExpiredAt = &now
glog.Infof("quota entitlement for central instance %q is no longer active, updating expired_at to %q", central.ID, now.Format(time.RFC1123Z))
return k.centralService.Update(central)
return &now, true
}
return nil
return nil, false
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ func TestExpirationDateManager(t *testing.T) {
ListByStatusFunc: func(status ...constants.CentralStatus) ([]*dbapi.CentralRequest, *errors.ServiceError) {
return centrals, nil
},
UpdateFunc: func(centralRequest *dbapi.CentralRequest) *errors.ServiceError {
UpdatesFunc: func(centralRequest *dbapi.CentralRequest, fields map[string]any) *errors.ServiceError {
if _, ok := fields["expired_at"]; !ok {
return errors.GeneralError("bad fields")
}
return nil
},
}
Expand All @@ -50,7 +53,7 @@ func TestExpirationDateManager(t *testing.T) {
errs := mgr.Reconcile()
require.Empty(t, errs)
assert.Len(t, centralService.ListByStatusCalls(), 1)
assert.Empty(t, centralService.UpdateCalls())
assert.Empty(t, centralService.UpdatesCalls())
assert.Empty(t, quotaSvc.HasQuotaAllowanceCalls())
assert.Len(t, quotaFactory.GetQuotaServiceCalls(), 1)
})
Expand All @@ -66,7 +69,7 @@ func TestExpirationDateManager(t *testing.T) {
assert.Nil(t, central.ExpiredAt)
assert.Len(t, centralService.ListByStatusCalls(), 1)
assert.Len(t, quotaSvc.HasQuotaAllowanceCalls(), 1)
assert.Len(t, centralService.UpdateCalls(), 1)
assert.Len(t, centralService.UpdatesCalls(), 1)
assert.Len(t, quotaFactory.GetQuotaServiceCalls(), 1)
})

Expand All @@ -82,7 +85,7 @@ func TestExpirationDateManager(t *testing.T) {
assert.Less(t, now, *central.ExpiredAt)
assert.Len(t, centralService.ListByStatusCalls(), 1)
assert.Len(t, quotaSvc.HasQuotaAllowanceCalls(), 1)
assert.Len(t, centralService.UpdateCalls(), 1)
assert.Len(t, centralService.UpdatesCalls(), 1)
assert.Len(t, quotaFactory.GetQuotaServiceCalls(), 1)
})

Expand All @@ -105,7 +108,7 @@ func TestExpirationDateManager(t *testing.T) {
assert.Nil(t, centralE.ExpiredAt)
assert.Len(t, centralService.ListByStatusCalls(), 1)
assert.Len(t, quotaSvc.HasQuotaAllowanceCalls(), 3)
assert.Len(t, centralService.UpdateCalls(), 5)
assert.Len(t, centralService.UpdatesCalls(), 5)
assert.Len(t, quotaFactory.GetQuotaServiceCalls(), 1)
})
}
117 changes: 117 additions & 0 deletions internal/dinosaur/test/integration/expiration_date_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package integration

import (
"fmt"
"testing"
"time"

// TODO(ROX-10709) "github.com/stackrox/acs-fleet-manager/pkg/quotamanagement"

"github.com/antihax/optional"
"github.com/golang-jwt/jwt/v4"
"github.com/stackrox/acs-fleet-manager/internal/dinosaur/pkg/api/admin/private"
"github.com/stackrox/acs-fleet-manager/internal/dinosaur/pkg/api/dbapi"
"github.com/stackrox/acs-fleet-manager/internal/dinosaur/pkg/config"
"github.com/stackrox/acs-fleet-manager/internal/dinosaur/pkg/dinosaurs/types"
"github.com/stackrox/acs-fleet-manager/internal/dinosaur/pkg/services"
"github.com/stackrox/acs-fleet-manager/internal/dinosaur/pkg/services/quota"
"github.com/stackrox/acs-fleet-manager/internal/dinosaur/pkg/workers/dinosaurmgrs"
"github.com/stackrox/acs-fleet-manager/internal/dinosaur/test"
"github.com/stackrox/acs-fleet-manager/pkg/api"
"github.com/stackrox/acs-fleet-manager/pkg/errors"
"github.com/stackrox/acs-fleet-manager/pkg/quotamanagement"
"github.com/stackrox/acs-fleet-manager/test/mocks"

// TODO(ROX-10709) "github.com/bxcodec/faker/v3"
. "github.com/onsi/gomega"
)

// TestDinosaurExpiredAt validates the changing of the expired_at field.
func TestDinosaurExpirationManager(t *testing.T) {

// create a mock ocm api server, keep all endpoints as defaults
// see the mocks package for more information on the configurable mock server
ocmServer := mocks.NewMockConfigurableServerBuilder().Build()
defer ocmServer.Close()

// setup the test environment, if OCM_ENV=integration then the ocmServer provided will be used instead of actual
// ocm
h, _, teardown := test.NewDinosaurHelperWithHooks(t, ocmServer, func(c *config.DataplaneClusterConfig) {
c.ClusterConfig = config.NewClusterConfig([]config.ManualCluster{test.NewMockDataplaneCluster("expiration-test-cluster", 1)})
})
defer teardown()

// setup pre-requisites to performing requests
account := h.NewAllowedServiceAccount()
claims := jwt.MapClaims{
"iss": issuerURL,
"org_id": orgID,
}
ctx := h.NewAuthenticatedContext(account, claims)
token := h.CreateJWTStringWithClaim(account, claims)
privateConfig := private.NewConfiguration()
privateConfig.BasePath = fmt.Sprintf("http://%s", test.TestServices.ServerConfig.BindAddress)
privateConfig.DefaultHeader = map[string]string{
"Authorization": "Bearer " + token,
}
adminAPI := private.NewAPIClient(privateConfig).DefaultApi
request, _, err := adminAPI.CreateCentral(ctx, false, private.CentralRequestPayload{
CloudProvider: "dummy",
MultiAz: false,
Name: "dummy-dinosaur",
Region: mocks.MockCluster.Region().ID(),
})
Expect(err).NotTo(HaveOccurred(), "Error creating central: %v", err)

id := request.Id
defer adminAPI.DeleteCentralById(ctx, id, false)

getCentral := func() private.Central {
central, _, err := adminAPI.GetCentralById(ctx, id)
Expect(err).NotTo(HaveOccurred(), "Error getting central: %v", err)
return central
}

Expect(getCentral().ExpiredAt).To(BeNil())

// Set expired_at.
then := time.Now().Add(time.Hour)
adminAPI.UpdateCentralExpiredAtById(ctx, id, "test",
&private.UpdateCentralExpiredAtByIdOpts{
Timestamp: optional.NewString(then.Format(time.RFC3339)),
})

Expect(getCentral().ExpiredAt).To(Equal(then))

qmlc := quotamanagement.NewQuotaManagementListConfig()

quotaServiceFactory := quota.NewDefaultQuotaServiceFactory(test.TestServices.OCMClient, test.TestServices.DBFactory, qmlc)

// Reset expired_at via expiration date manager.
var centralConfig *config.CentralConfig
h.Env.ServiceContainer.Resolve(&centralConfig)
mgr := dinosaurmgrs.NewExpirationDateManager(test.TestServices.DinosaurService, quotaServiceFactory, centralConfig)
svcErrs := mgr.Reconcile()
Expect(svcErrs).To(BeEmpty())

// Check it is reset.
Expect(getCentral().ExpiredAt).To(BeNil())

quotaMock := &services.QuotaServiceFactoryMock{
GetQuotaServiceFunc: func(quotaType api.QuotaType) (services.QuotaService, *errors.ServiceError) {
return &services.QuotaServiceMock{
HasQuotaAllowanceFunc: func(dinosaur *dbapi.CentralRequest, instanceType types.DinosaurInstanceType) (bool, *errors.ServiceError) {
return false, nil
},
}, nil
},
}

// Disable quota.
mgr = dinosaurmgrs.NewExpirationDateManager(test.TestServices.DinosaurService, quotaMock, centralConfig)
svcErrs = mgr.Reconcile()
Expect(svcErrs).To(BeEmpty())

// Check the central is expired.
Expect(getCentral().ExpiredAt).ToNot(BeNil())
}
Loading