feat: use docker client

This commit is contained in:
Wanjohi Ryan
2024-06-27 03:16:52 +03:00
parent 84b916973a
commit a4e0a70181
3 changed files with 410 additions and 149 deletions

View File

@@ -4,23 +4,20 @@ Copyright © 2024 Nestri <>
package cmd
import (
"context"
_ "embed"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/nestriness/cli/pkg/specs"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/lipgloss/table"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/muesli/termenv"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
//go:embed nestri.ascii
@@ -93,22 +90,65 @@ var runCmd = &cobra.Command{
return nil
}
var game string
if len(args) > 0 {
game = args[0]
viper.Set("game", game)
viper.WriteConfig()
} else {
game = viper.GetString("game")
if filepath.Ext(game) != ".exe" {
return fmt.Errorf("Make sure the game is a .exe")
}
if game == "" {
return fmt.Errorf("no game specified and no previous game selected")
}
// var game string
// if len(args) > 0 {
// game = args[0]
// viper.Set("game", game)
// viper.WriteConfig()
// } else {
// game = viper.GetString("game")
// if filepath.Ext(game) != ".exe" {
// return fmt.Errorf("Make sure the game is a .exe")
// }
// if game == "" {
// return fmt.Errorf("no game specified and no previous game selected")
// }
// }
// fmt.Printf("Running game: %s\n\n", game)
cli, err := client.NewClientWithOpts()
if err != nil {
panic(err)
}
fmt.Printf("Running game: %s\n\n", game)
ctx := context.Background()
resp, err := cli.ContainerCreate(ctx, &container.Config{
Image: "hello-world",
}, nil, nil, nil, "hello-world")
if err != nil {
panic(err)
}
if err := cli.ContainerStart(ctx, resp.ID, container.StartOptions{}); err != nil {
panic(err)
}
// Attach to the container to get logs
out, err := cli.ContainerLogs(ctx, resp.ID, container.LogsOptions{ShowStdout: true, ShowStderr: true, Follow: true})
if err != nil {
fmt.Printf("Error attaching to container logs: %s\n", err)
}
defer out.Close()
// Copy the logs to stdout and stderr
stdcopy.StdCopy(os.Stdout, os.Stderr, out)
// Wait for the container to finish
statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
if err != nil {
fmt.Printf("Error waiting for container: %s\n", err)
}
case <-statusCh:
fmt.Println("Container finished")
}
// Clean up the container
if err := cli.ContainerRemove(ctx, resp.ID, container.RemoveOptions{}); err != nil {
fmt.Printf("Error removing container: %s\n", err)
}
// if gpu > 0 {
// fmt.Print("Using gpu %s\n", gpu)
// }
@@ -117,131 +157,131 @@ var runCmd = &cobra.Command{
// }
//get linux version
versionCmd := exec.Command("grep", "VERSION", "/etc/os-release")
versionOutput, err := versionCmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error getting linux version:")
}
fmt.Printf("Linux version:\n%s\n", string(versionOutput))
// versionCmd := exec.Command("grep", "VERSION", "/etc/os-release")
// versionOutput, err := versionCmd.CombinedOutput()
// if err != nil {
// return fmt.Errorf("error getting linux version:")
// }
// fmt.Printf("Linux version:\n%s\n", string(versionOutput))
//Step 1: change to games dir
fmt.Println("changing to game dir.") //this is a temp command for debug as well as leads to a hardcoded dir
// //Step 1: change to games dir
// fmt.Println("changing to game dir.") //this is a temp command for debug as well as leads to a hardcoded dir
HomeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error getting home directory %v\n", err)
}
// HomeDir, err := os.UserHomeDir()
// if err != nil {
// return fmt.Errorf("error getting home directory %v\n", err)
// }
err = os.Chdir(fmt.Sprintf("%s/game", HomeDir))
if err != nil {
return fmt.Errorf("error changing directory: %v\n", err)
}
//verify we are in game dir
dir, err := os.Getwd()
if err != nil {
return fmt.Errorf("error getting current directory: %v\n", err)
}
fmt.Printf("Current directory: %s\n\n", dir)
// err = os.Chdir(fmt.Sprintf("%s/game", HomeDir))
// if err != nil {
// return fmt.Errorf("error changing directory: %v\n", err)
// }
// //verify we are in game dir
// dir, err := os.Getwd()
// if err != nil {
// return fmt.Errorf("error getting current directory: %v\n", err)
// }
// fmt.Printf("Current directory: %s\n\n", dir)
//list games dir
listDir := exec.Command("ls", "-la", ".")
listDirOutput, err := listDir.CombinedOutput()
if err != nil {
fmt.Errorf("error listing games: %v\n")
}
fmt.Printf("List of Games: \n%s\n", listDirOutput)
// //list games dir
// listDir := exec.Command("ls", "-la", ".")
// listDirOutput, err := listDir.CombinedOutput()
// if err != nil {
// fmt.Errorf("error listing games: %v\n")
// }
// fmt.Printf("List of Games: \n%s\n", listDirOutput)
//step 2: Generate a Session ID
//generate id
SID := exec.Command("bash", "-c", "head /dev/urandom | LC_ALL=C tr -dc 'a-zA-Z0-9' | head -c 16")
// //step 2: Generate a Session ID
// //generate id
// SID := exec.Command("bash", "-c", "head /dev/urandom | LC_ALL=C tr -dc 'a-zA-Z0-9' | head -c 16")
//save output to variable
output, err := SID.Output()
if err != nil {
fmt.Errorf("Error generating Session ID: %v\n", err)
}
sessionID := strings.TrimSpace(string(output))
fmt.Printf("Your Session ID is: %s\n\n", sessionID)
// //save output to variable
// output, err := SID.Output()
// if err != nil {
// fmt.Errorf("Error generating Session ID: %v\n", err)
// }
// sessionID := strings.TrimSpace(string(output))
// fmt.Printf("Your Session ID is: %s\n\n", sessionID)
//step 3: Launch netris server
fmt.Println("Installing Netris/Launching Netris Server\n")
checkRunning := exec.Command("sudo", "docker", "ps", "-q", "-f", "name=netris")
containerId, err := checkRunning.Output()
if err != nil {
return fmt.Errorf("error checking running Docker container: %v", err)
}
// //step 3: Launch netris server
// fmt.Println("Installing Netris/Launching Netris Server")
// checkRunning := exec.Command("sudo", "docker", "ps", "-q", "-f", "name=netris")
// containerId, err := checkRunning.Output()
// if err != nil {
// return fmt.Errorf("error checking running Docker container: %v", err)
// }
if len(containerId) == 0 {
checkExisting := exec.Command("sudo", "docker", "ps", "-aq", "-f", "name=netris")
containerId, err = checkExisting.Output()
if err != nil {
return fmt.Errorf("error checking for existing docker container: %v", err)
}
// if len(containerId) == 0 {
// checkExisting := exec.Command("sudo", "docker", "ps", "-aq", "-f", "name=netris")
// containerId, err = checkExisting.Output()
// if err != nil {
// return fmt.Errorf("error checking for existing docker container: %v", err)
// }
if len(containerId) == 0 {
installCmd := exec.Command(
"sudo", "docker", "run", "-d", "--gpus", "all", "--device=/dev/dri",
"--name", "netris", "-it", "--entrypoint", "/bin/bash",
"-e", fmt.Sprintf("SESSION_ID=%s", sessionID),
"-v", fmt.Sprintf("%s:/game", dir), "-p", "8080:8080/udp",
"--cap-add=SYS_NICE", "--cap-add=SYS_ADMIN", "ghcr.io/netrisdotme/netris/server:nightly",
)
installCmd.Stdout = os.Stdout
installCmd.Stderr = os.Stderr
// if len(containerId) == 0 {
// installCmd := exec.Command(
// "sudo", "docker", "run", "-d", "--gpus", "all", "--device=/dev/dri",
// "--name", "netris", "-it", "--entrypoint", "/bin/bash",
// "-e", fmt.Sprintf("SESSION_ID=%s", sessionID),
// "-v", fmt.Sprintf("%s:/game", dir), "-p", "8080:8080/udp",
// "--cap-add=SYS_NICE", "--cap-add=SYS_ADMIN", "ghcr.io/netrisdotme/netris/server:nightly",
// )
// installCmd.Stdout = os.Stdout
// installCmd.Stderr = os.Stderr
if err := installCmd.Run(); err != nil {
return fmt.Errorf("error running docker command: %v", err)
}
} else {
startContainer := exec.Command("sudo", "docker", "start", "netris")
startContainer.Stdout = os.Stdout
startContainer.Stderr = os.Stderr
// if err := installCmd.Run(); err != nil {
// return fmt.Errorf("error running docker command: %v", err)
// }
// } else {
// startContainer := exec.Command("sudo", "docker", "start", "netris")
// startContainer.Stdout = os.Stdout
// startContainer.Stderr = os.Stderr
if err := startContainer.Run(); err != nil {
return fmt.Errorf("error starting existing Docker container: %v", err)
}
}
}
// if err := startContainer.Run(); err != nil {
// return fmt.Errorf("error starting existing Docker container: %v", err)
// }
// }
// }
//main part of step 4:
//start netris server
// //main part of step 4:
// //start netris server
fmt.Println("starting netris server\n\n")
checkFileCmd := exec.Command("sudo", "docker", "exec", "netris", "ls", "-la", "/tmp")
output, err = checkFileCmd.Output()
if err != nil {
return fmt.Errorf("error checking /tmp dir in docker container: %v\n", err)
}
// fmt.Println("starting netris server\n\n")
// checkFileCmd := exec.Command("sudo", "docker", "exec", "netris", "ls", "-la", "/tmp")
// output, err = checkFileCmd.Output()
// if err != nil {
// return fmt.Errorf("error checking /tmp dir in docker container: %v\n", err)
// }
if !strings.Contains(string(output), ".X11-unix") {
startupCmd := exec.Command("sudo", "docker", "exec", "netris", "/etc/startup.sh", ">", "/dev/null", "&")
startupCmd.Stdout = os.Stdout
startupCmd.Stderr = os.Stderr
// if !strings.Contains(string(output), ".X11-unix") {
// startupCmd := exec.Command("sudo", "docker", "exec", "netris", "/etc/startup.sh", ">", "/dev/null", "&")
// startupCmd.Stdout = os.Stdout
// startupCmd.Stderr = os.Stderr
if err := startupCmd.Run(); err != nil {
return fmt.Errorf("error running startup command: %v\n", err)
}
// if err := startupCmd.Run(); err != nil {
// return fmt.Errorf("error running startup command: %v\n", err)
// }
for {
time.Sleep(7 * time.Minute)
output, err := checkFileCmd.Output()
if err != nil {
return fmt.Errorf("error checking /tmp directory in container: %v\n", err)
}
if strings.Contains(string(output), ".X11-unix") {
break
}
}
}
// for {
// time.Sleep(7 * time.Minute)
// output, err := checkFileCmd.Output()
// if err != nil {
// return fmt.Errorf("error checking /tmp directory in container: %v\n", err)
// }
// if strings.Contains(string(output), ".X11-unix") {
// break
// }
// }
// }
gameCmd := fmt.Sprintf("netris-proton -pr %s", game)
execCmd := exec.Command("sudo", "docker", "exec", "netris", gameCmd)
execCmd.Stdout = os.Stdout
execCmd.Stderr = os.Stderr
// gameCmd := fmt.Sprintf("netris-proton -pr %s", game)
// execCmd := exec.Command("sudo", "docker", "exec", "netris", gameCmd)
// execCmd.Stdout = os.Stdout
// execCmd.Stderr = os.Stderr
if err := execCmd.Run(); err != nil {
return fmt.Errorf("error executing game command in docker container: %v\n", err)
}
// if err := execCmd.Run(); err != nil {
// return fmt.Errorf("error executing game command in docker container: %v\n", err)
// }
return nil
},
@@ -261,6 +301,7 @@ func init() {
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
rootCmd.AddCommand(neoFetchCmd)
rootCmd.AddCommand(runCmd)
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cli.yaml)")
@@ -294,18 +335,18 @@ func max(a, b int) int {
return b
}
func getSpecs(info *specs.Specs, infoChan chan specs.Specs, wg *sync.WaitGroup) {
defer wg.Done()
sys := specs.New()
// info.Userhost = getUserHostname()
// info.OS = getOSName()
// info.Kernel = getKernelVersion()
// info.Uptime = getUptime()
// info.Shell = getShell()
// info.CPU = getCPUName()
// info.RAM = getMemStats()
info.GPU, _ = sys.GetGPUInfo()
// info.SystemArch, _ = getSystemArch()
// info.DiskUsage, _ = getDiskUsage()
infoChan <- *info
}
// func getSpecs(info *specs.Specs, infoChan chan specs.Specs, wg *sync.WaitGroup) {
// defer wg.Done()
// sys := specs.New()
// // info.Userhost = getUserHostname()
// // info.OS = getOSName()
// // info.Kernel = getKernelVersion()
// // info.Uptime = getUptime()
// // info.Shell = getShell()
// // info.CPU = getCPUName()
// // info.RAM = getMemStats()
// info.GPU, _ = sys.GetGPUInfo()
// // info.SystemArch, _ = getSystemArch()
// // info.DiskUsage, _ = getDiskUsage()
// infoChan <- *info
// }