Skip to content

Commit

Permalink
feat: added changes to run keploy docker from binary (#1480)
Browse files Browse the repository at this point in the history
* feat: added changes to run keploy docker from binary

Signed-off-by: Pranshu Srivastava <iampranshu24@gmail.com>

* fix: made changes according to the comments

Signed-off-by: Pranshu Srivastava <iampranshu24@gmail.com>

* fix: made changes according to comments

Signed-off-by: Pranshu Srivastava <iampranshu24@gmail.com>

* fix: removed unnecessary log

Signed-off-by: Pranshu Srivastava <iampranshu24@gmail.com>

---------

Signed-off-by: Pranshu Srivastava <iampranshu24@gmail.com>
  • Loading branch information
PranshuSrivastava committed Feb 2, 2024
1 parent e286945 commit 2a76ef7
Show file tree
Hide file tree
Showing 8 changed files with 296 additions and 59 deletions.
24 changes: 23 additions & 1 deletion cmd/record.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,28 @@ func (r *Record) GetCmd() *cobra.Command {
}
}
}
//Check if app command starts with docker or sudo docker.
dockerRelatedCmd, dockerCmd := utils.IsDockerRelatedCmd(appCmd)
if !isDockerCmd && dockerRelatedCmd {
isDockerCompose := false
if dockerCmd == "docker-compose" {
isDockerCompose = true
}
recordCfg := utils.RecordFlags{
Path: path,
Command: appCmd,
ContainerName: appContainer,
Proxyport: proxyPort,
NetworkName: networkName,
Delay: delay,
BuildDelay: buildDelay,
PassThroughPorts: ports,
ConfigPath: configPath,
EnableTele: enableTele,
}
utils.UpdateKeployToDocker("record", isDockerCompose, recordCfg, r.logger)
return nil
}

//if user provides relative path
if len(path) > 0 && path[0] != '/' {
Expand Down Expand Up @@ -303,4 +325,4 @@ func (r *Record) GetCmd() *cobra.Command {
recordCmd.SilenceErrors = true

return recordCmd
}
}
29 changes: 27 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,31 @@ func setupLogger() *zap.Logger {
"./keploy-logs.txt",
}

// Check if keploy-log.txt exists, if not create it.
_, err := os.Stat("keploy-logs.txt")
if os.IsNotExist(err) {
_, err := os.Create("keploy-logs.txt")
if err != nil {
log.Println(Emoji, "failed to create log file", err)
return nil
}
}

// Check if the permission of the log file is 777, if not set it to 777.
fileInfo, err := os.Stat("keploy-logs.txt")
if err != nil {
log.Println(Emoji, "failed to get the log file info", err)
return nil
}
if fileInfo.Mode().Perm() != 0777 {
// Set the permissions of the log file to 777.
err = os.Chmod("keploy-logs.txt", 0777)
if err != nil {
log.Println(Emoji, "failed to set permissions of log file", err)
return nil
}
}

if debugMode {
go func() {
defer utils.HandlePanic()
Expand All @@ -104,7 +129,7 @@ func setupLogger() *zap.Logger {

logger, err := logCfg.Build()
if err != nil {
log.Panic(Emoji, "failed to start the logger for the CLI")
log.Panic(Emoji, "failed to start the logger for the CLI", err)
return nil
}
return logger
Expand Down Expand Up @@ -280,4 +305,4 @@ type Plugins interface {
// RegisterPlugin registers a plugin by appending it to the list of subCommands.
func (r *Root) RegisterPlugin(p Plugins) {
r.subCommands = append(r.subCommands, p)
}
}
46 changes: 37 additions & 9 deletions cmd/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,41 @@ func (t *Test) GetCmd() *cobra.Command {
}
}

mongoPassword, err := cmd.Flags().GetString("mongoPassword")
if err != nil {
t.logger.Error("failed to read the mongo password")
return err
}

t.logger.Debug("the configuration for mocking mongo connection", zap.Any("password", mongoPassword))
//Check if app command starts with docker or docker-compose.
dockerRelatedCmd, dockerCmd := utils.IsDockerRelatedCmd(appCmd)
if !isDockerCmd && dockerRelatedCmd {
isDockerCompose := false
if dockerCmd == "docker-compose" {
isDockerCompose = true
}
testCfg := utils.TestFlags{
Path: path,
Proxyport: proxyPort,
Command: appCmd,
Testsets: testsets,
ContainerName: appContainer,
NetworkName: networkName,
Delay: delay,
BuildDelay: buildDelay,
ApiTimeout: apiTimeout,
PassThroughPorts: ports,
ConfigPath: configPath,
MongoPassword: mongoPassword,
CoverageReportPath: coverageReportPath,
EnableTele: enableTele,
WithCoverage: withCoverage,
}
utils.UpdateKeployToDocker("test", isDockerCompose, testCfg, t.logger)
return nil
}

//if user provides relative path
if len(path) > 0 && path[0] != '/' {
absPath, err := filepath.Abs(path)
Expand All @@ -351,6 +386,7 @@ func (t *Test) GetCmd() *cobra.Command {
path += "/keploy"

testReportPath := path + "/testReports"

testReportPath, err = pkg.GetNextTestReportDir(testReportPath, models.TestRunTemplateName)
if err != nil {
t.logger.Error("failed to get the next test report directory", zap.Error(err))
Expand All @@ -376,14 +412,6 @@ func (t *Test) GetCmd() *cobra.Command {

t.logger.Debug("the ports are", zap.Any("ports", ports))

mongoPassword, err := cmd.Flags().GetString("mongoPassword")
if err != nil {
t.logger.Error("failed to read the ports of outgoing calls to be ignored")
return err
}

t.logger.Debug("the configuration for mocking mongo connection", zap.Any("password", mongoPassword))

if coverage {
g := graph.NewGraph(t.logger)
g.Serve(path, proxyPort, mongoPassword, testReportPath, delay, pid, port, lang, ports, apiTimeout, appCmd, enableTele)
Expand Down Expand Up @@ -458,4 +486,4 @@ func (t *Test) GetCmd() *cobra.Command {
testCmd.SilenceErrors = true

return testCmd
}
}
11 changes: 8 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"os"
_ "net/http/pprof"
"time"

Expand Down Expand Up @@ -34,8 +35,12 @@ func main() {
version = "2-dev"
}
utils.Version = version
fmt.Println(logo, " ")
fmt.Printf("version: %v\n\n", version)
if binaryToDocker := os.Getenv("BINARY_TO_DOCKER");binaryToDocker != "true" {
fmt.Println(logo, " ")
fmt.Printf("version: %v\n\n", version)
}else{
fmt.Println("Starting keploy in docker environment.")
}
//Initialise sentry.
err := sentry.Init(sentry.ClientOptions{
Dsn: dsn,
Expand All @@ -48,4 +53,4 @@ func main() {
defer utils.HandlePanic()
defer sentry.Flush(2 * time.Second)
cmd.Execute()
}
}
36 changes: 3 additions & 33 deletions pkg/hooks/launch.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"go.uber.org/zap"

"go.keploy.io/server/pkg"
"go.keploy.io/server/utils"
"go.keploy.io/server/pkg/models"
)

Expand Down Expand Up @@ -62,7 +63,7 @@ func (h *Hook) LaunchUserApplication(appCmd, appContainer, appNetwork string, De
}
return nil
} else {
ok, cmd := h.IsDockerRelatedCmd(appCmd)
ok, cmd := utils.IsDockerRelatedCmd(appCmd)
if ok {

h.logger.Debug("Running user application on Docker", zap.Any("Docker env", cmd))
Expand Down Expand Up @@ -595,37 +596,6 @@ func (h *Hook) injectNetworkToKeploy(appNetwork string) error {
return nil
}

// It checks if the cmd is related to docker or not, it also returns if its a docker compose file
func (h *Hook) IsDockerRelatedCmd(cmd string) (bool, string) {
// Check for Docker command patterns
dockerCommandPatterns := []string{
"docker-compose ",
"sudo docker-compose ",
"docker compose ",
"sudo docker compose ",
"docker ",
"sudo docker ",
}

for _, pattern := range dockerCommandPatterns {
if strings.HasPrefix(strings.ToLower(cmd), pattern) {
if strings.Contains(pattern, "compose") {
return true, "docker-compose"
}
return true, "docker"
}
}

// Check for Docker Compose file extension
dockerComposeFileExtensions := []string{".yaml", ".yml"}
for _, extension := range dockerComposeFileExtensions {
if strings.HasSuffix(strings.ToLower(cmd), extension) {
return true, "docker-compose"
}
}

return false, ""
}

func parseDockerCommand(dockerCmd string) (string, string, error) {
// Regular expression patterns
Expand Down Expand Up @@ -718,4 +688,4 @@ func modifyDockerComposeCommand(appCmd, newComposeFile string) string {
}

return fmt.Sprintf("%s -f %s", appCmd, newComposeFile)
}
}
2 changes: 1 addition & 1 deletion pkg/service/record/record.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,4 @@ func (r *recorder) CaptureTraffic(path string, proxyPort uint32, appCmd, appCont
}

<-exitCmd
}
}
6 changes: 3 additions & 3 deletions pkg/service/test/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ func (t *tester) InitialiseRunTestSet(cfg *RunTestSetConfig) InitialiseRunTestSe
//check if the user application is running docker container using IDE
returnVal.DockerID = (cfg.AppCmd == "" && len(cfg.AppContainer) != 0)

ok, _ := cfg.LoadedHooks.IsDockerRelatedCmd(cfg.AppCmd)
ok, _ := utils.IsDockerRelatedCmd(cfg.AppCmd)
if ok || returnVal.DockerID {
returnVal.UserIP = cfg.LoadedHooks.GetUserIP()
t.logger.Debug("the userip of the user docker container", zap.Any("", returnVal.UserIP))
Expand All @@ -428,7 +428,7 @@ func (t *tester) SimulateRequest(cfg *SimulateRequestConfig) {
started := time.Now().UTC()
t.logger.Debug("Before simulating the request", zap.Any("Test case", cfg.Tc))

ok, _ := cfg.LoadedHooks.IsDockerRelatedCmd(cfg.AppCmd)
ok, _ := utils.IsDockerRelatedCmd(cfg.AppCmd)
if ok || cfg.DockerID {
var err error
cfg.Tc.HttpReq.URL, err = replaceHostToIP(cfg.Tc.HttpReq.URL, cfg.UserIP)
Expand Down Expand Up @@ -890,4 +890,4 @@ func replaceHostToIP(currentURL string, ipAddress string) (string, error) {
parsedURL.Host = strings.Replace(parsedURL.Host, parsedURL.Hostname(), ipAddress, 1)
// Return the modified URL
return parsedURL.String(), nil
}
}
Loading

0 comments on commit 2a76ef7

Please sign in to comment.