Skip to content

Commit

Permalink
feat: added support to trap os signals
Browse files Browse the repository at this point in the history
  • Loading branch information
Adriano Santos committed Jan 12, 2025
1 parent cb445b1 commit 04e7b71
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 6 deletions.
Binary file modified tools/sdk-init/bin/sdk-init
Binary file not shown.
38 changes: 34 additions & 4 deletions tools/sdk-init/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,55 @@ package main
import (
"log"
"os"
"os/signal"
"syscall"

"sdk-init/pkg/copier"
"sdk-init/pkg/runner"
)

func main() {
srcDir := "/protos"
destDir := "/shared/protos"
srcDir := getEnv("SRC_DIR", "/protos")
destDir := getEnv("DEST_DIR", "/shared/protos")

if err := copier.CopyDir(srcDir, destDir); err != nil {
log.Fatalf("Error copying files: %v", err)
}
log.Println("Files copied successfully.")

// Configure the channel to capture system signals
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

if len(os.Args) > 1 {
if err := runner.RunCommand(os.Args[1], os.Args[2:]...); err != nil {
log.Fatalf("Error executing command: %v", err)
cmd, err := runner.RunCommandAsync(os.Args[1], os.Args[2:]...)
if err != nil {
log.Fatalf("Error starting command: %v", err)
}

// Waits for signals and passes to subprocess
go func() {
sig := <-sigChan
log.Printf("Received signal: %v. Forwarding to subprocess...", sig)
if err := cmd.Process.Signal(sig); err != nil {
log.Printf("Error forwarding signal to subprocess: %v", err)
}
}()

// Wait for the subprocess to finish...
if err := cmd.Wait(); err != nil {
log.Fatalf("Subprocess terminated with error: %v", err)
} else {
log.Println("Subprocess terminated successfully.")
}
} else {
log.Println("No command specified. Finishing...")
}
}

func getEnv(key, defaultValue string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return defaultValue
}
Binary file added tools/sdk-init/example-app/sdk-init
Binary file not shown.
Empty file.
8 changes: 6 additions & 2 deletions tools/sdk-init/pkg/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ import (
"os/exec"
)

func RunCommand(cmd string, args ...string) error {
func RunCommandAsync(cmd string, args ...string) (*exec.Cmd, error) {
command := exec.Command(cmd, args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr

return command.Run()
if err := command.Start(); err != nil {
return nil, err
}

return command, nil
}

0 comments on commit 04e7b71

Please sign in to comment.