Skip to content

Commit e51a909

Browse files
Merge pull request #21 from Corentin-cott/CobraCommandCLI
Cobra command cli
2 parents d18fd80 + 297fcb7 commit e51a909

File tree

6 files changed

+357
-140
lines changed

6 files changed

+357
-140
lines changed

cmd/daemon/main.go

Lines changed: 156 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,101 @@ package main
33
import (
44
"fmt"
55
"log"
6+
"os"
7+
"strconv"
68
"time"
79

810
"github.com/Corentin-cott/ServeurSentinel/config"
911
"github.com/Corentin-cott/ServeurSentinel/internal/console"
1012
"github.com/Corentin-cott/ServeurSentinel/internal/db"
1113
periodic "github.com/Corentin-cott/ServeurSentinel/internal/events"
14+
"github.com/Corentin-cott/ServeurSentinel/internal/tmux"
1215
"github.com/Corentin-cott/ServeurSentinel/internal/triggers"
16+
"github.com/spf13/cobra"
1317
)
1418

1519
func main() {
16-
fmt.Println(time.Now().Location())
20+
var rootCmd = &cobra.Command{
21+
Use: "serversentinel",
22+
Short: "ServerSentinel manages Minecraft and Palworld servers in tmux sessions.",
23+
}
24+
25+
// Command: serversentinel start-server [id]
26+
var startServerCmd = &cobra.Command{
27+
Use: "start-server [id]",
28+
Short: "Starts a game server by its ID",
29+
Args: cobra.ExactArgs(1),
30+
Run: func(cmd *cobra.Command, args []string) {
31+
serverID := args[0]
32+
fmt.Printf("Starting server with ID: %s\n", serverID)
33+
commandStartStopServerWithID(serverID, "start")
34+
},
35+
}
36+
37+
// Command: serversentinel stop-server [id]
38+
var stopServerCmd = &cobra.Command{
39+
Use: "stop-server [id]",
40+
Short: "Stops a game server by its ID",
41+
Args: cobra.ExactArgs(1),
42+
Run: func(cmd *cobra.Command, args []string) {
43+
serverID := args[0]
44+
fmt.Printf("Stopping server with ID: %s\n", serverID)
45+
commandStartStopServerWithID(serverID, "stop")
46+
},
47+
}
48+
49+
// Command: serversentinel check-server
50+
var checkServerCmd = &cobra.Command{
51+
Use: "check-server",
52+
Short: "Check and start servers that are supposed to be running",
53+
Args: cobra.NoArgs,
54+
Run: func(cmd *cobra.Command, args []string) {
55+
// Because it's a CLI command, we need to load the configuration file
56+
err := config.LoadConfig("/opt/serversentinel/config.json")
57+
if err != nil {
58+
log.Fatalf("FATAL ERROR LOADING CONFIG JSON FILE: %v", err)
59+
return
60+
}
61+
62+
// Initialize the connection to the database
63+
err = db.ConnectToDatabase()
64+
if err != nil {
65+
log.Fatalf("FATAL ERROR TESTING DATABASE CONNECTION: %v", err)
66+
return
67+
}
68+
69+
// Check if the right tmux servers are running
70+
fmt.Printf("Checking and starting servers that are supposed to be running\n")
71+
message, err := tmux.CheckRunningServers()
72+
if err != nil {
73+
log.Fatalf("FATAL ERROR CHECKING RUNNING SERVERS: %v", err)
74+
return
75+
}
76+
fmt.Println(message)
77+
},
78+
}
79+
80+
// Command: serversentinel daemon
81+
var daemonCmd = &cobra.Command{
82+
Use: "daemon",
83+
Short: "Runs ServerSentinel in daemon mode",
84+
Run: runDaemon,
85+
}
86+
87+
// Add commands to root
88+
rootCmd.AddCommand(daemonCmd)
89+
rootCmd.AddCommand(startServerCmd)
90+
rootCmd.AddCommand(stopServerCmd)
91+
rootCmd.AddCommand(checkServerCmd)
92+
93+
// Execute CLI
94+
if err := rootCmd.Execute(); err != nil {
95+
fmt.Println(err)
96+
os.Exit(1)
97+
}
98+
}
99+
100+
func runDaemon(cmd *cobra.Command, args []string) {
17101
fmt.Println("Starting the Server Sentinel daemon (" + time.Now().Format("02/01/2006 15:04:05") + ") ...")
18102

19103
// Load the configuration file
@@ -64,3 +148,74 @@ func main() {
64148

65149
fmt.Println("♦ Server Sentinel daemon stopped.")
66150
}
151+
152+
// Function to start a server by its ID. This function is use in the CLI command "start-server"
153+
func commandStartStopServerWithID(serverID string, action string) {
154+
// Action can only be "start" or "stop"
155+
if action != "start" && action != "stop" {
156+
log.Fatalf("FATAL ERROR: INVALID ACTION: %s", action)
157+
return
158+
}
159+
160+
// Check if the server ID is a number, and if so, convert it to an integer
161+
serverIDInt, err := strconv.Atoi(serverID)
162+
if err != nil {
163+
log.Fatalf("FATAL ERROR: SERVER ID IS NOT A NUMBER: %v", err)
164+
return
165+
}
166+
167+
// Because it's a CLI command, we need to load the configuration file
168+
err = config.LoadConfig("/opt/serversentinel/config.json")
169+
if err != nil {
170+
log.Fatalf("FATAL ERROR LOADING CONFIG JSON FILE: %v", err)
171+
return
172+
}
173+
174+
// Initialize the connection to the database
175+
err = db.ConnectToDatabase()
176+
if err != nil {
177+
log.Fatalf("FATAL ERROR TESTING DATABASE CONNECTION: %v", err)
178+
}
179+
180+
// Now we check if the server exists in the database
181+
server, err := db.GetServerById(serverIDInt)
182+
if err != nil {
183+
log.Fatalf("FATAL ERROR GETTING SERVER BY ID: %v", err)
184+
return
185+
}
186+
187+
// If the action is "stop", we stop the server
188+
if action == "stop" {
189+
// Stop the server
190+
err = tmux.StopServerTmux(server.Nom)
191+
if err != nil {
192+
log.Fatalf("FATAL ERROR STOPPING SERVER: %v", err)
193+
return
194+
}
195+
return
196+
}
197+
198+
// If the action is "start", we first check if the server is primary or not
199+
if server.ID == 1 {
200+
err = db.SetPrimaryServerId(server.ID)
201+
if err != nil {
202+
log.Fatalf("FATAL ERROR SETTING PRIMARY SERVER ID: %v", err)
203+
return
204+
}
205+
} else {
206+
err = db.SetSecondaryServerId(server.ID)
207+
if err != nil {
208+
log.Fatalf("FATAL ERROR SETTING SECONDARY SERVER ID: %v", err)
209+
return
210+
}
211+
}
212+
213+
// Start the server
214+
message, err := tmux.CheckRunningServers()
215+
if err != nil {
216+
log.Fatalf("FATAL ERROR CHECKING RUNNING SERVERS: %v", err)
217+
return
218+
}
219+
220+
fmt.Println(message)
221+
}

go.mod

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,9 @@ go 1.22.2
44

55
require github.com/go-sql-driver/mysql v1.8.1
66

7-
require filippo.io/edwards25519 v1.1.0 // indirect
7+
require (
8+
filippo.io/edwards25519 v1.1.0 // indirect
9+
github.com/inconshreveable/mousetrap v1.1.0 // indirect
10+
github.com/spf13/cobra v1.9.1 // direct
11+
github.com/spf13/pflag v1.0.6 // indirect
12+
)

go.sum

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,14 @@
11
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
22
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
3+
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
34
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
45
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
6+
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
7+
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
8+
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
9+
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
10+
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
11+
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
12+
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
13+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
14+
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

internal/db/db_controller.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,28 @@ func GetSecondaryServerId() int {
130130
return serverID
131131
}
132132

133+
// Setter to set the primary server
134+
func SetPrimaryServerId(serverID int) error {
135+
query := "UPDATE serveurs_parameters SET id_serv_primaire = ?"
136+
_, err := db.Exec(query, serverID)
137+
if err != nil {
138+
return fmt.Errorf("FAILED TO SET PRIMARY SERVER: %v", err)
139+
}
140+
141+
return nil
142+
}
143+
144+
// Setter to set the secondary server
145+
func SetSecondaryServerId(serverID int) error {
146+
query := "UPDATE serveurs_parameters SET id_serv_secondaire = ?"
147+
_, err := db.Exec(query, serverID)
148+
if err != nil {
149+
return fmt.Errorf("FAILED TO SET SECONDARY SERVER: %v", err)
150+
}
151+
152+
return nil
153+
}
154+
133155
// Getter to get all the server informations
134156
func GetServerById(serverID int) (models.Server, error) {
135157
query := "SELECT * FROM serveurs WHERE id = ?"

0 commit comments

Comments
 (0)