8000 feat: implement AutoDown functionality with tests by jLopezbarb · Pull Request #4732 · okteto/okteto · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: implement AutoDown functionality with tests #4732

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

Merged
merged 5 commits into from
Jun 23, 2025
Merged
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
97 changes: 97 additions & 0 deletions cmd/up/autodown.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright 2023 The Okteto Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package up

import (
"context"

"github.com/okteto/okteto/cmd/utils"
"github.com/okteto/okteto/pkg/cmd/down"
"github.com/okteto/okteto/pkg/env"
oktetoErrors "github.com/okteto/okteto/pkg/errors"
"github.com/okteto/okteto/pkg/k8s/apps"
"github.com/okteto/okteto/pkg/k8s/deployments"
"github.com/okteto/okteto/pkg/log/io"
"github.com/okteto/okteto/pkg/model"
"github.com/okteto/okteto/pkg/okteto"
"github.com/spf13/afero"
"k8s.io/client-go/kubernetes"
)

const (
autoDownEnvVar = "OKTETO_AUTO_DOWN_ENABLED"
)

// autoDownRunner is the struct that runs the AutoDown logic if enabled
// based on the env var OKTETO_AUTO_DOWN_ENABLED, defaulting to false
// if enabled, it will run the AutoDown logic
type autoDownRunner struct {
autoDown bool

ioCtrl *io.Controller
k8sLogger *io.K8sLogger
analyticsTracker analyticsTrackerInterface
downCmd downCmdRunner
}

type downCmdRunner interface {
Run(app apps.App, dev *model.Dev, namespace string, trMap map[string]*apps.Translation, wait bool) error
}

// newAutoDown creates a new AutoDown instance
func newAutoDown(ioCtrl *io.Controller, k8sLogger *io.K8sLogger, at analyticsTrackerInterface) *autoDownRunner {
enabled := env.LoadBooleanOrDefault(autoDownEnvVar, false)
downCmd := down.New(afero.NewOsFs(), okteto.NewK8sClientProviderWithLogger(k8sLogger), at)
return &autoDownRunner{
autoDown: enabled,
ioCtrl: ioCtrl,
k8sLogger: k8sLogger,
analyticsTracker: at,
downCmd: downCmd,
}
}

// run is the main function that runs the AutoDown logic if enabled
func (a *autoDownRunner) run(ctx context.Context, dev *model.Dev, namespace string, k8sClient kubernetes.Interface) error {
if !a.autoDown {
a.ioCtrl.Logger().Infof("AutoDown is disabled, skipping AutoDown logic")
return nil
}
a.ioCtrl.Logger().Infof("AutoDown is enabled, running AutoDown logic")
sp := a.ioCtrl.Out().Spinner("Running okteto down...")
sp.Start()
defer sp.Stop()
app, _, err := utils.GetApp(ctx, dev, namespace, k8sClient, false)
if err != nil {
if !oktetoErrors.IsNotFound(err) {
return err
}
app = apps.NewDeploymentApp(deployments.Sandbox(dev, namespace))
}
if dev.Autocreate {
app = apps.NewDeploymentApp(deployments.Sandbox(dev, namespace))
}

trMap, err := apps.GetTranslations(ctx, namespace, dev, app, false, k8sClient)
if err != nil {
return err
}

err = a.downCmd.Run(app, dev, namespace, trMap, true)
if err != nil {
return err
}
a.ioCtrl.Out().Success("okteto down completed")
return nil
}
202 changes: 202 additions & 0 deletions cmd/up/autodown_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
// Copyright 2023 The Okteto Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package up

import (
"context"
"testing"

"github.com/okteto/okteto/pkg/analytics"
"github.com/okteto/okteto/pkg/k8s/apps"
"github.com/okteto/okteto/pkg/log/io"
"github.com/okteto/okteto/pkg/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"k8s.io/client-go/kubern 10000 etes/fake"
)

type mockAnalyticsTracker struct {
mock.Mock
}

func (m *mockAnalyticsTracker) TrackEvent(event string, properties map[string]interface{}) {
m.Called(event, properties)
}

func (m *mockAnalyticsTracker) TrackDeploy(metadata analytics.DeployMetadata) {
m.Called(metadata)
}

func (m *mockAnalyticsTracker) TrackUp(metadata *analytics.UpMetricsMetadata) {
m.Called(metadata)
}

func (m *mockAnalyticsTracker) TrackDown(success bool) {
m.Called(success)
}

func (m *mockAnalyticsTracker) TrackDownVolumes(success bool) {
m.Called(success)
}

func (m *mockAnalyticsTracker) TrackImageBuild(ctx context.Context, meta *analytics.ImageBuildMetadata) {
m.Called(ctx, meta)
}

type mockDownCmdRunner struct {
mock.Mock
}

func (m *mockDownCmdRunner) Run(app apps.App, dev *model.Dev, namespace string, trMap map[string]*apps.Translation, wait bool) error {
args := m.Called(app, dev, namespace, trMap, wait)
return args.Error(0)
}

func TestNewAutoDown(t *testing.T) {
tests := []struct {
name string
envValue string
expectedResult bool
}{
{
name: "AutoDown disabled by default",
envValue: "",
expectedResult: false,
},
{
name: "AutoDown enabled",
envValue: "true",
expectedResult: true,
},
{
name: "AutoDown disabled explicitly",
envValue: "false",
expectedResult: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Set environment variable
if tt.envValue != "" {
t.Setenv(autoDownEnvVar, tt.envValue)
}

ioCtrl := io.NewIOController()
k8sLogger := io.NewK8sLogger()
at := &mockAnalyticsTracker{}

ad := newAutoDown(ioCtrl, k8sLogger, at)

assert.Equal(t, tt.expectedResult, ad.autoDown)
assert.NotNil(t, ad.ioCtrl)
assert.NotNil(t, ad.k8sLogger)
assert.NotNil(t, ad.analyticsTracker)
})
}
}

func TestAutoDownRunner_Run(t *testing.T) {
tests := []struct {
name string
autoDown bool
dev *model.Dev
namespace string
mockSetup func(*mockAnalyticsTracker, *mockDownCmdRunner)
expectedError bool
}{
{
name: "AutoDown disabled",
autoDown: false,
dev: &model.Dev{},
namespace: "test-namespace",
mockSetup: func(at *mockAnalyticsTracker, downCmd *mockDownCmdRunner) {
// No expectations needed as it should return early
},
expectedError: false,
},
{
name: "AutoDown enabled with sandbox deployment",
autoDown: true,
dev: &model.Dev{Autocreate: true},
namespace: "test-namespace",
mockSetup: func(at *mockAnalyticsTracker, downCmd *mockDownCmdRunner) {
downCmd.On("Run", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
},
expectedError: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Setup mocks
ioCtrl := io.NewIOController()
k8sLogger := io.NewK8sLogger()
8000 at := &mockAnalyticsTracker{}
downCmd := &mockDownCmdRunner{}

tt.mockSetup(at, downCmd)

ad := &autoDownRunner{
autoDown: tt.autoDown,
ioCtrl: ioCtrl,
k8sLogger: k8sLogger,
analyticsTracker: at,
downCmd: downCmd,
}

fakeK8sClient := fake.NewSimpleClientset()

err := ad.run(context.Background(), tt.dev, tt.namespace, fakeK8sClient)

if tt.expectedError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}

at.AssertExpectations(t)
})
}
}

func TestAutoDownRunner_Run_WithAppNotFound(t *testing.T) {
// Setup
ioCtrl := io.NewIOController()
k8sLogger := io.NewK8sLogger()
at := &mockAnalyticsTracker{}
downCmd := &mockDownCmdRunner{}
downCmd.On("Run", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(assert.AnError)

ad := &autoDownRunner{
autoDown: true,
ioCtrl: ioCtrl,
k8sLogger: k8sLogger,
analyticsTracker: at,
downCmd: downCmd,
}

dev := &model.Dev{
Name: "test-dev",
}
namespace := "test-namespace"

fakeK8sClient := fake.NewSimpleClientset()

err := ad.run(context.Background(), dev, namespace, fakeK8sClient)

// Should not error as not found is handled gracefully
assert.ErrorIs(t, err, assert.AnError)
at.AssertExpectations(t)
}
2 changes: 1 addition & 1 deletion cmd/up/pid.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func (pc pidController) notifyIfPIDFileChange(notifyCh chan error) {
}
if strconv.Itoa(pid) != filePID {
notifyCh <- oktetoErrors.UserError{
E: fmt.Errorf("development container has been deactivated by another 'okteto up' command"),
E: errAnotherUpCommandStarted,
Hint: "Use 'okteto exec' to open another terminal to your development container",
}
return
Expand Down
3 changes: 3 additions & 0 deletions cmd/up/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ type analyticsTrackerInterface interface {
buildTrackerInterface
TrackDeploy(analytics.DeployMetadata)
TrackUp(*analytics.UpMetricsMetadata)
TrackDown(bool)
TrackDownVolumes(bool)
}

type buildTrackerInterface interface {
Expand All @@ -65,6 +67,7 @@ type buildDeployTrackerInterface interface {
// upContext is the common context of all operations performed during the up command
type upContext struct {
Namespace string
autoDown *autoDownRunner
StartTime time.Time
Forwarder forwarder
tokenUpdater tokenUpdater
Expand Down
18 changes: 16 additions & 2 deletions cmd/up/up.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ const (
)

var (
errConfigNotConfigured = fmt.Errorf("kubeconfig not found")
errConfigNotConfigured = fmt.Errorf("kubeconfig not found")
errAnotherUpCommandStarted = errors.New("development container has been deactivated by another 'okteto up' command")
)

// Options represents the options available on up command
Expand Down Expand Up @@ -236,6 +237,7 @@ okteto up api -- echo this is a test
K8sClientProvider: okteto.NewK8sClientProviderWithLogger(k8sLogger),
tokenUpdater: newTokenUpdaterController(),
builder: buildv2.NewBuilderFromScratch(ioCtrl, onBuildFinish),
autoDown: newAutoDown(ioCtrl, k8sLogger, at),
}
up.inFd, up.isTerm = term.GetFdInfo(os.Stdin)
if up.isTerm {
Expand Down Expand Up @@ -493,20 +495,32 @@ func (up *upContext) start() error {

go up.pidController.notifyIfPIDFileChange(pidFileCh)

k8sClient, _, err := up.K8sClientProvider.Provide(okteto.GetContext().Cfg)
if err != nil {
return err
}
select {
case <-stop:
oktetoLog.Infof("CTRL+C received, starting shutdown sequence")
up.interruptReceived = true
up.shutdown()

if err := up.autoDown.run(context.Background(), up.Dev, up.Namespace, k8sClient); err != nil {
return err
}
oktetoLog.Println()
case err := <-up.Exit:
if up.Dev.IsHybridModeEnabled() {
up.shutdownHybridMode()
}
if err != nil {
oktetoLog.Warning("Exited without running okteto down. Your dev environment is still active. Run okteto down to clean it up and free resources.")
oktetoLog.Infof("exit signal received due to error: %s", err)
return err
}
if err := up.autoDown.run(context.Background(), up.Dev, up.Namespace, k8sClient); err != nil {
return err
}
case err := <-pidFileCh:
if up.Dev.IsHybridModeEnabled() {
up.shutdownHybridMode()
Expand Down Expand Up @@ -542,7 +556,7 @@ func (up *upContext) activateLoop() {
up.shutdownHybridMode()
}
up.Exit <- oktetoErrors.UserError{
E: fmt.Errorf("development container has been deactivated by another 'okteto up' command"),
E: errAnotherUpCommandStarted,
Hint: "Use 'okteto exec' to open another terminal to your development container",
}
return
Expand Down
0