Skip to content

Commit

Permalink
feat: implement dive context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
shreyasbhat0 committed Dec 4, 2023
1 parent eac1065 commit 8e88421
Show file tree
Hide file tree
Showing 7 changed files with 264 additions and 282 deletions.
67 changes: 67 additions & 0 deletions cli/common/cli.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package common

import (
"path/filepath"
"sync"
)

var (
CliContext *Cli

initOnce sync.Once
)

type Cli struct {
log Logger
spinner Spinner
context Context
fileHandler FileHandler
}

func initCli() (*Cli, error) {
fileHandler := NewDiveFileHandler()

pwd, err := fileHandler.GetPwd()

if err != nil {
return nil, WrapMessageToError(err, "Failed To Initialize CLi")
}
errorLogFilePath := filepath.Join(pwd, DiveLogDirectory, DiveErrorLogFile)
infoLogFilePath := filepath.Join(pwd, DiveLogDirectory, DiveDitLogFile)

return &Cli{
log: NewDiveLogger(infoLogFilePath, errorLogFilePath),
spinner: NewDiveSpinner(),
context: NewDiveContext1(),
fileHandler: fileHandler,
}, nil
}

func GetCli() (*Cli, error) {
var err error
initOnce.Do(func() {
CliContext, err = initCli()
})

if err != nil {
return nil, WrapMessageToError(err, "Failed To Retrieve Cli")
}

return CliContext, nil
}

func (c *Cli) Logger() Logger {
return c.log
}

func (c *Cli) Spinner() Spinner {
return c.spinner
}

func (c *Cli) Context() Context {
return c.context
}

func (c *Cli) FileHandler() FileHandler {
return c.fileHandler
}
17 changes: 17 additions & 0 deletions cli/common/command_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,20 @@ func (dc *diveCommandBuilder) SetRunE(run func(cmd *cobra.Command, args []string

return dc
}

func (dc *diveCommandBuilder) MarkFlagsAsRequired(flags []string) CommandBuilder {

dc.cmd.MarkFlagsRequiredTogether(flags...)
return dc
}

func (dc *diveCommandBuilder) MarkFlagRequired(flag string) CommandBuilder {
dc.cmd.MarkFlagRequired(flag)
return dc
}

func (dc *diveCommandBuilder) AddBoolFlagP(name string, shorthand string, value bool, usage string) CommandBuilder {

dc.cmd.Flags().BoolP(name, shorthand, value, usage)
return dc
}
99 changes: 78 additions & 21 deletions cli/common/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package common

import (
"context"
"errors"
"fmt"
"strings"
"sync"

"github.com/kurtosis-tech/kurtosis/api/golang/core/kurtosis_core_rpc_api_bindings"
Expand All @@ -24,13 +26,14 @@ def run(plan, args):
)

var (
Once sync.Once
kurtosisContextErr error
)

type diveContext struct {
ctx context.Context
kurtosisContext *kurtosis_context.KurtosisContext
mu sync.Mutex
ctx context.Context
kurtosisContext *kurtosis_context.KurtosisContext
kurtosisInitDone bool
}

func NewDiveContext1() *diveContext {
Expand All @@ -42,14 +45,16 @@ func (dc *diveContext) GetContext() context.Context {
}

func (dc *diveContext) GetKurtosisContext() (*kurtosis_context.KurtosisContext, error) {
once.Do(func() {
err := dc.initKurtosisContext()
dc.mu.Lock()
defer dc.mu.Unlock()

if !dc.kurtosisInitDone {
kurtosisContext, err := dc.initKurtosisContext()
if err != nil {
kurtosisContextErr = err
return nil, err
}
})
if kurtosisContextErr != nil {
return nil, kurtosisContextErr
dc.kurtosisContext = kurtosisContext
dc.kurtosisInitDone = true
}
return dc.kurtosisContext, nil
}
Expand Down Expand Up @@ -116,8 +121,9 @@ func (dc *diveContext) CleanEnclaveByName(enclaveName string) error {
return nil
}

func (dc *diveContext) CheckSkippedInstructions() {
panic("not implemented") // TODO: Implement
func (dc *diveContext) CheckSkippedInstructions(instructions map[string]bool) bool {

return len(instructions) != 0
}

func (dc *diveContext) StopService(serviceName string, enclaveName string) error {
Expand Down Expand Up @@ -219,26 +225,24 @@ func (dc *diveContext) CreateEnclave(enclaveName string) (*enclaves.EnclaveConte
return enclaveContext, nil
}

func (dc *diveContext) GetSerializedData(response chan *kurtosis_core_rpc_api_bindings.StarlarkRunResponseLine) (string, map[string]string, map[string]bool, error) {
panic("not implemented") // TODO: Implement
}

func (dc *diveContext) initKurtosisContext() error {
func (dc *diveContext) initKurtosisContext() (*kurtosis_context.KurtosisContext, error) {

kurtosisContext, err := kurtosis_context.NewKurtosisContextFromLocalEngine()

if err != nil {
return WrapMessageToError(ErrKurtosisContext, err.Error())
return nil, WrapMessageToError(ErrKurtosisContext, err.Error())

}

dc.kurtosisContext = kurtosisContext

return nil
return kurtosisContext, nil
}
func (dc *diveContext) checkEnclaveExist(enclaveName string) (*EnclaveInfo, error) {

enclaveInfo, err := dc.kurtosisContext.GetEnclave(dc.ctx, enclaveName)
kurtosisContext, err := dc.GetKurtosisContext()
if err != nil {
return nil, Errorc(KurtosisContextError, err.Error())
}
enclaveInfo, err := kurtosisContext.GetEnclave(dc.ctx, enclaveName)
if err != nil {
return nil, Errorc(KurtosisContextError, err.Error())
}
Expand All @@ -262,3 +266,56 @@ func GetStarlarkRunConfig(params string, relativePathToMainFile string, mainFunc
}
return starlarkConfig
}

func GetSerializedData(cliContext *Cli, response chan *kurtosis_core_rpc_api_bindings.StarlarkRunResponseLine) (string, map[string]string, map[string]bool, error) {

var serializedOutputObj string
services := map[string]string{}

skippedInstruction := map[string]bool{}
for executionResponse := range response {

if strings.Contains(executionResponse.GetInstructionResult().GetSerializedInstructionResult(), "added with service") {
res1 := strings.Split(executionResponse.GetInstructionResult().GetSerializedInstructionResult(), " ")
serviceName := res1[1][1 : len(res1[1])-1]
serviceUUID := res1[len(res1)-1][1 : len(res1[len(res1)-1])-1]
services[serviceName] = serviceUUID
}

cliContext.log.Info(executionResponse.String())

if executionResponse.GetInstruction().GetIsSkipped() {
skippedInstruction[executionResponse.GetInstruction().GetExecutableInstruction()] = executionResponse.GetInstruction().GetIsSkipped()
break
}

if executionResponse.GetError() != nil {

return "", services, nil, errors.New(executionResponse.GetError().String())

}

runFinishedEvent := executionResponse.GetRunFinishedEvent()

if runFinishedEvent != nil {

if runFinishedEvent.GetIsRunSuccessful() {
serializedOutputObj = runFinishedEvent.GetSerializedOutput()

} else {
return "", services, nil, errors.New(executionResponse.GetError().String())
}

} else {
cliContext.spinner.SetColor("blue")
if executionResponse.GetProgressInfo() != nil {

cliContext.spinner.SetSuffixMessage(strings.ReplaceAll(executionResponse.GetProgressInfo().String(), "current_step_info:", " "), "fgGreen")

}
}

}

return serializedOutputObj, services, skippedInstruction, nil
}
30 changes: 23 additions & 7 deletions cli/common/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,36 @@ func NewDiveFileHandler() *diveFileHandler {
func (df *diveFileHandler) ReadFile(filePath string) ([]byte, error) {

fileData, err := os.ReadFile(filePath)
if err != nil {
if os.IsNotExist(err) {
_, err := df.OpenFile(filePath, "append|write|create", 0644)
if err != nil {
return nil, Errorcf(FileError, "Error While Creating File %s", err.Error())
}

return []byte{}, nil

} else if err != nil {
return nil, Errorcf(FileError, "Error While Reading File %s", err.Error())
}

return fileData, nil
}

func (df *diveFileHandler) ReadJson(fileName string, obj interface{}) error {
pwd, err := df.GetPwd()
if err != nil {
return WrapMessageToError(err, "Error While Reading File")
}

filePath := filepath.Join(pwd, fileName)
var filePath string

if filepath.IsAbs(fileName) {
filePath = fileName
} else {
pwd, err := df.GetPwd()
if err != nil {
return WrapMessageToError(err, "Error While Reading File")
}

filePath = filepath.Join(pwd, fileName)

}

data, err := df.ReadFile(filePath)
if err != nil {
Expand Down Expand Up @@ -102,7 +118,7 @@ func (df *diveFileHandler) WriteFile(fileName string, data []byte) error {
}
filePath := filepath.Join(pwd, fileName)

file, err := df.OpenFile(filePath, "write|append|create", 0644)
file, err := df.OpenFile(filePath, "write|append|create|truncate", 0644)

if err != nil {
return WrapMessageToError(err, "Failed")
Expand Down
9 changes: 5 additions & 4 deletions cli/common/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"io/fs"
"os"

"github.com/kurtosis-tech/kurtosis/api/golang/core/kurtosis_core_rpc_api_bindings"
"github.com/kurtosis-tech/kurtosis/api/golang/core/lib/enclaves"
"github.com/kurtosis-tech/kurtosis/api/golang/engine/lib/kurtosis_context"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -43,13 +42,12 @@ type Context interface {
GetEnclaveContext(enclaveName string) (*enclaves.EnclaveContext, error)
CleanEnclaves() ([]*EnclaveInfo, error)
CleanEnclaveByName(enclaveName string) error
CheckSkippedInstructions()
StopService(serviceName string) error
CheckSkippedInstructions(instructions map[string]bool) bool
StopService(serviceName string, enclaveName string) error
StopServices(enclaveName string) error
RemoveServices(enclaveName string) error
RemoveService(serviceName string, enclaveName string) error
CreateEnclave(enclaveName string) (*enclaves.EnclaveContext, error)
GetSerializedData(response chan *kurtosis_core_rpc_api_bindings.StarlarkRunResponseLine) (string, map[string]string, map[string]bool, error)
}

type FileHandler interface {
Expand Down Expand Up @@ -111,4 +109,7 @@ type CommandBuilder interface {
ToggleHelpCommand(enable bool) CommandBuilder

SetRunE(run func(cmd *cobra.Command, args []string) error) CommandBuilder
MarkFlagsAsRequired(flags []string) CommandBuilder
MarkFlagRequired(flag string) CommandBuilder
AddBoolFlagP(name string, shorthand string, value bool, usage string) CommandBuilder
}
Loading

0 comments on commit 8e88421

Please sign in to comment.