Compare commits

..

No commits in common. "master" and "v0.9-3" have entirely different histories.

7 changed files with 225 additions and 407 deletions

122
config.go
View File

@ -3,138 +3,80 @@ package main
import (
"errors"
"log"
lua "github.com/yuin/gopher-lua"
"github.com/yuin/gopher-lua"
)
// Configuration stores information retrieved from a configuration file
type Configuration struct {
port int64
sites_dir string
trusted_servers []string
matrix struct {
port int64
sites_dir string
matrix struct {
homeserver string
username string
password string
room_id string
disabled bool
}
}
// getStringFromTable retrieves a string from a table on the lua stack using the key passed in.
//
// If the value is nil, 'out' is unchanged.
func getStringFromTable(L *lua.LState, lobj lua.LValue, key string, out *string) (bool, error) {
func getStringFromTable(L *lua.LState, lobj lua.LValue, key string, out *string) error {
lv := L.GetTable(lobj, lua.LString(key))
if text, ok := lv.(lua.LString); ok { // Value is string
if text, ok := lv.(lua.LString); ok {
*out = string(text)
} else if _, ok := lv.(*lua.LNilType); !ok { // Value is not a string, and is not nil
return true, errors.New("'" + key + "' is not a string")
} else {
return errors.New("Failed to get string from table using key '" + key + "'")
}
return true, nil
return nil
}
// getIntFromTable retrieves an integer from a table on the Lua stack using the key passed in.
//
// If the value is nil, 'out' is unchanged.
func getIntFromTable(L *lua.LState, lobj lua.LValue, key string, out *int64) (bool, error) {
func getIntFromTable(L *lua.LState, lobj lua.LValue, key string, out *int64) error {
lv := L.GetTable(lobj, lua.LString(key))
if int, ok := lv.(lua.LNumber); ok { // Value is number
if int, ok := lv.(lua.LNumber); ok {
*out = int64(int)
} else if _, ok := lv.(*lua.LNilType); !ok { // Value is not a number, and is not nil
return true, errors.New("'" + key + "' is not a number")
} else {
return errors.New("Failed to get integer from table using key '" + key + "'")
}
return true, nil
}
// getBoolFromTable retrieves a bool from a table on the Lua stack using the key passed in.
//
// If the value is nil, 'out' is unchanged.
func getBoolFromTable(L *lua.LState, lobj lua.LValue, key string, out *bool) (bool, error) {
lv := L.GetTable(lobj, lua.LString(key))
if boolean, ok := lv.(lua.LBool); ok { // Value is boolean
*out = bool(boolean)
} else if _, ok := lv.(*lua.LNilType); !ok { // Value is not a bool, and is not nil
return true, errors.New("'" + key + "' is not a bool")
}
return true, nil
return nil
}
// getTableFromTable retrieves a nested table from the Lua stack using the key passed in.
func getTableFromTable(L *lua.LState, lobj lua.LValue, key string, out *lua.LValue) bool {
lv := L.GetTable(lobj, lua.LString(key))
*out = lv
if _, ok := lv.(*lua.LNilType); ok {
return false
}
return true
func getTableFromTable(L *lua.LState, lobj lua.LValue, key string, out *lua.LValue) {
*out = L.GetTable(lobj, lua.LString(key))
}
// parseConfig parses the JSON configuration file at 'path' and stores the contents in 'config'
func parseConfig(path string, config *Configuration) {
log.Printf("Loading config from : %s ...", path)
// Lua state setup
L := lua.NewState()
defer L.Close()
L.DoFile(path)
table := L.Get(-1) // Get the table returned by the config file
if table.Type().String() != "table" { // Make sure value returned is of type 'table'
log.Fatalf("config is of type : '%s', not 'table'", table.Type().String())
}
table := L.Get(-1) // Get the table returned by the config file
// Main config
if _, err := getStringFromTable(L, table, "sites_dir", &config.sites_dir); err != nil {
if err := getStringFromTable(L, table, "sites_dir", &config.sites_dir); err != nil {
panic(err)
}
if _, err := getIntFromTable(L, table, "port", &config.port); err != nil {
if err := getIntFromTable(L, table, "port", &config.port); err != nil {
panic(err)
}
// Trusted servers
var trusted_servers lua.LValue
getTableFromTable(L, table, "trusted_servers", &trusted_servers) // Get the 'trusted_servers' table
// Make sure 'config.trusted_servers' is of type 'table'
if trusted_servers_type := trusted_servers.Type().String(); trusted_servers_type != "table" &&
trusted_servers_type != "nil" {
log.Fatalf("config.trusted_servers is of type : '%s', not 'table'", trusted_servers_type)
} else if trusted_servers_type != "nil" { // If type is not nil (has to be table or it would've been caught already)
for i := 1; i <= L.ObjLen(trusted_servers); i++ { // Loop through every trusted server
lv := L.GetTable(trusted_servers, lua.LNumber(i))
if text, ok := lv.(lua.LString); ok { // Value is string
config.trusted_servers = append(config.trusted_servers, string(text))
} else if _, ok := lv.(*lua.LNilType); !ok { // Value is not a string, and is not nil
log.Fatalf("config.trusted_servers[%d] is of type : '%s', not 'string'", i, lv.Type().String())
}
}
}
// Matrix config
var matrix lua.LValue
getTableFromTable(L, table, "matrix", &matrix) // Get the 'matrix' table
// Make sure 'config.matrix' is of type 'table'
if matrix_type := matrix.Type().String(); matrix_type != "table" && matrix_type != "nil" {
log.Fatalf("config.matrix is of type : '%s', not 'table'", matrix_type)
} else if matrix_type != "nil" {
if _, err := getBoolFromTable(L, matrix, "disabled", &config.matrix.disabled); err != nil {
panic(err)
}
if !config.matrix.disabled { // Only load the rest of the matrix config if matrix isn't disabled
if _, err := getStringFromTable(L, matrix, "homeserver", &config.matrix.homeserver); err != nil {
panic(err)
}
if _, err := getStringFromTable(L, matrix, "username", &config.matrix.username); err != nil {
panic(err)
}
if _, err := getStringFromTable(L, matrix, "password", &config.matrix.password); err != nil {
panic(err)
}
if _, err := getStringFromTable(L, matrix, "room_id", &config.matrix.room_id); err != nil {
panic(err)
}
}
} else if matrix_type == "nil" { // Assume config.matrix.disabled is true if 'matrix' is missing from the config file
config.matrix.disabled = true
getTableFromTable(L, table, "matrix", &matrix)
if err := getStringFromTable(L, matrix, "homeserver", &config.matrix.homeserver); err != nil {
panic(err)
}
if err := getStringFromTable(L, matrix, "username", &config.matrix.username); err != nil {
panic(err)
}
if err := getStringFromTable(L, matrix, "password", &config.matrix.password); err != nil {
panic(err)
}
if err := getStringFromTable(L, matrix, "room_id", &config.matrix.room_id); err != nil {
panic(err)
}
}

View File

@ -1,13 +0,0 @@
return {
port = 7575,
sites_dir = "./sites",
trusted_servers = { -- IPs of servers that are allowed to send Gitea webhooks
},
matrix = {
homeserver = "https://matrix.org",
username = "bot:matrix.org",
password = "Sup@rS3cure",
room_id = "", -- Room ID can be found under "room settings" in most clients
disabled = false
}
}

27
deploy_error.go Normal file
View File

@ -0,0 +1,27 @@
// package main is the main package for the LapisDeploy program
package main
import (
"fmt"
)
// DeployError contains important information about an error if something went wrong.
type DeployError struct {
code int
where string
details string
command_output string
}
// SendOverMatrix provides an easy way to send the contents of a DeployError over Matrix
func (deploy_error *DeployError) SendOverMatrix() {
sendMessage(MatrixMessage{text: fmt.Sprintf("🔴 **Error in **`%s`**!**\n- *%s*\n- Code: %d",
deploy_error.where, deploy_error.details, deploy_error.code),
})
}
// newDeployError creates a DeployError
func newDeployError(code int, where string, details string, command_output string) DeployError {
return DeployError{ code: code, where: where, details: details, command_output: command_output }
}

96
main.go
View File

@ -3,24 +3,15 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/akamensky/argparse"
"log"
"net/http"
"os"
"strings"
"github.com/akamensky/argparse"
)
// Circle emoji
var Circles = map[string]string{
"white": "⚪️ ",
"green": "🟢 ",
"yellow": "🟡 ",
"red": "🔴 ",
"orange": "🟠 ",
}
// Create a configuration struct
var configuration = Configuration{}
// fileExists returns whether the given file or directory exists.
func fileExists(path string) (bool, error) {
@ -34,56 +25,50 @@ func fileExists(path string) (bool, error) {
return false, err
}
// Create a configuration struct
var configuration = Configuration{}
// handler is in charge of handling requests after the JSON has been parsed
func handler(data map[string]interface{}) {
repository := data["repository"].(map[string]interface{})
log.Default().Printf("Repo: %s", repository["full_name"])
sendInfo(fmt.Sprintf("Handling webhook for `%s`...", repository["full_name"]))
sendMessage(MatrixMessage{text: fmt.Sprintf("⚪️ Handling webhook for `%s`...", repository["full_name"])})
repo_name := repository["name"].(string)
site, exists, err := getSite(repo_name)
if err != nil {
sendError(errors.New(fmt.Sprintf("Failed to check if site '%s' exists: %s", repo_name, err)))
deploy_error := newDeployError(1, "handler", fmt.Sprintf("Failed to check if site '%s' exists", repo_name), fmt.Sprint(err))
deploy_error.SendOverMatrix()
return
}
if exists {
sendInfo("Updating repository...")
if err := site.Update(); err != nil {
sendError(err)
sendMessage(MatrixMessage{text: "⚪️ Updating repository..."})
if deploy_error := site.Update(); deploy_error.code != 0 {
deploy_error.SendOverMatrix()
return
}
new_site, exists, err := getSite(site.name)
if err != nil || !exists {
sendError(errors.New("Failed to update site data on a site we just updated: " + repo_name))
}
site = new_site
sendInfo("Restarting server...")
if error := site.Restart(); error != nil {
sendError(error)
sendMessage(MatrixMessage{text: "⚪️ Restarting server..."})
if deploy_error := site.Restart(); deploy_error.code != 0 {
deploy_error.SendOverMatrix()
return
}
} else {
sendInfo("Cloning repositiory...")
if error := CloneSite(repository["ssh_url"].(string), repo_name); error != nil {
sendError(error)
sendMessage(MatrixMessage{text: "⚪️ Cloning repository..."})
if deploy_error := CloneSite(repository["ssh_url"].(string), repo_name); deploy_error.code != 0 {
deploy_error.SendOverMatrix()
return
}
sendInfo("Starting server...")
sendMessage(MatrixMessage{text: "⚪️ Starting server..."})
if site, exists, err = getSite(repo_name); err != nil {
sendError(err)
return
deploy_error := newDeployError(1, "handler",
fmt.Sprintf("Failed to get site '%s' after creation!", repo_name), fmt.Sprint(err))
deploy_error.SendOverMatrix()
}
if error := site.Start(); error != nil {
sendError(err)
if deploy_error := site.Start(); deploy_error.code != 0 {
deploy_error.SendOverMatrix()
return
}
defer sendMessage(MatrixMessage{text: "🚀 Launched for the first time!"})
}
sendMessage(MatrixMessage{text: Circles["green"] + "Deployed successfully!"})
sendMessage(MatrixMessage{text: "🟢 Deployed successfully!"})
}
// main is the starting point of the program
@ -105,49 +90,22 @@ func main() {
}
parseConfig(*config_path, &configuration) // Parse JSON configuration file
// Disable Matrix if it's disabled in either the config or specified on CLI
configuration.matrix.disabled = *disable_matrix || configuration.matrix.disabled
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Webhook receiver
log.Print("Recieved request!")
var data map[string]interface{}
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
log.Panic(err)
return
}
check_ips := []string{ // IPs of client to check against trusted_servers
strings.Split(r.RemoteAddr, ":")[0],
r.Header.Get("x-forwarded-for"),
}
found_trusted_server := false
for _, server := range configuration.trusted_servers {
if found_trusted_server {
break
}
for _, ip := range check_ips {
if ip == server {
log.Printf("Request IP matches a trusted server (%s)", ip)
go handler(data) // Run the handler
fmt.Fprint(w, "Received!")
found_trusted_server = true
break
}
}
}
if !found_trusted_server {
log.Print("Request IP doesn't match a trusted server! Dropping...")
}
})
// Attempt to create sites_dir
if exists, _ := fileExists(configuration.sites_dir); !exists {
os.Mkdir(configuration.sites_dir, 640) // Permissions are 640 (Owner: rw, Group: r, All: none)
}
go handler(data) // Run the handler
fmt.Fprint(w, "Received!")
})
log.Printf("Starting Lapis Deploy on port %d...", configuration.port)
startAllSites() // Start all the servers
if !configuration.matrix.disabled { // Only start Matrix bot if --disable-matrix isn't passed
startAllSites() // Start all the servers
if !*disable_matrix { // Only start Matrix bot if --disable-matrix isn't passed
go initMatrix() // Start Matrix stuff in a goroutine
} else {
log.Print("Matrix bot is disabled!")

142
matrix.go
View File

@ -6,7 +6,6 @@ import (
"fmt"
"log"
"strings"
"sync"
"time"
"maunium.net/go/mautrix"
@ -17,8 +16,7 @@ import (
// MatrixMessage stores information about a matrix message.
type MatrixMessage struct {
text string
level int
text string
}
// MatrixCommandCallback is a function that gets called when the bot is issued a command over Matrix
@ -31,31 +29,23 @@ type MatrixCommand struct {
description string
}
// Output queue.
var MatrixOut struct {
queue []MatrixMessage
mux sync.Mutex
}
// Output queue
var MatrixOut []MatrixMessage
// sendMessage sends a message through Matrix.
// ChatCommands
var Chatcommands []MatrixCommand
// sendMessage sends a message through Matrix
func sendMessage(msg MatrixMessage) {
log.Print(msg.text)
MatrixOut.mux.Lock()
MatrixOut.queue = append(MatrixOut.queue, msg)
MatrixOut.mux.Unlock()
MatrixOut = append(MatrixOut, msg)
}
// sendError sends an error through Matrix.
func sendError(err error) {
sendMessage(MatrixMessage{
text: fmt.Sprintf("%s %s", Circles["red"], err),
})
}
// sendInfo sends a bit of info text through Matrix.
func sendInfo(text string) {
sendMessage(MatrixMessage{
text: fmt.Sprintf("%s %s", Circles["white"], text),
// registerChatCommand
func registerChatCommand(cmd string, description string, callback MatrixCommandCallback) {
Chatcommands = append(Chatcommands, MatrixCommand{
cmd: cmd,
callback: callback,
description: description,
})
}
@ -110,7 +100,7 @@ func initMatrix() {
}
}
if !found_command {
client.SendText(ctx, evt.RoomID, Circles["red"]+"Command not found")
client.SendText(ctx, evt.RoomID, "🔴 Command not found")
}
break
}
@ -118,31 +108,97 @@ func initMatrix() {
}
})
registerChatCommands() // Register all the chat commands defined inside matrix_commands.go
registerChatCommand("help", "Show the help dialouge", func(ctx context.Context, evt *event.Event, args []string) string {
text := ""
for _, cmd := range Chatcommands {
text = fmt.Sprintf("%s- %s\n %s\n", text, cmd.cmd, cmd.description)
}
return text
})
registerChatCommand("sites", "Display all available sites", func(ctx context.Context, evt *event.Event, args []string) string {
text := "⚪️ Getting sites...\n"
sites, err := getAllSites()
if err.code != 0 {
return text + "🔴 Failed to get sites!"
}
for _, site := range sites {
text = fmt.Sprintf("%s- %s\n", text, site.getName())
}
if len(sites) == 0 {
text = text + "*No sites found*"
}
return text
})
registerChatCommand("restart", "Restart a site.", func(ctx context.Context, evt *event.Event, args []string) string {
if len(args) < 2 {
return "🔴 Invalid site."
}
site, found, err := getSite(args[1])
if err != nil {
return "🔴 Failed to get site " + args[2] + "!"
} else if !found {
return "🔴 Invalid site."
}
text := "⚪️ Restarting server..."
derr := site.Restart()
if derr.code != 0 {
derr.SendOverMatrix()
return text + "\n🔴 Failed to restart site!"
}
return text + "\n🟢 Successfully restarted site."
})
registerChatCommand("start", "Start a site.", func(ctx context.Context, evt *event.Event, args []string) string {
if len(args) < 2 {
return "🔴 Invalid site."
}
site, found, err := getSite(args[1])
if err != nil {
return "🔴 Failed to get site " + args[2] + "!"
} else if !found {
return "🔴 Invalid site."
}
text := "⚪️ Starting server..."
if derr := site.Start(); derr.code != 0 {
derr.SendOverMatrix()
return text + "\n🔴 Failed to stop site!"
}
return text + "\n🟢 Successfully started site."
})
registerChatCommand("stop", "Stop a site.", func(ctx context.Context, evt *event.Event, args []string) string {
if len(args) < 2 {
return "🔴 Invalid site."
}
site, found, err := getSite(args[1])
if err != nil {
return "🔴 Failed to get site " + args[2] + "!"
} else if !found {
return "🔴 Invalid site."
}
text := "⚪️ Stopping server..."
if derr := site.Stop(); derr.code != 0 {
derr.SendOverMatrix()
return text + "\n🔴 Failed to stop site!"
}
return text + "\n🟢 Successfully stopped site."
})
go func() {
for range time.Tick(time.Second * 2) {
MatrixOut.mux.Lock()
if len(MatrixOut.queue) > 0 {
text := ""
for i, msg := range MatrixOut.queue {
text += msg.text
if i != len(MatrixOut.queue) {
text += "\n"
}
}
MatrixOut.queue = []MatrixMessage{}
_, err := client.SendMessageEvent(context.Background(),
id.RoomID(configuration.matrix.room_id),
event.EventMessage,
format.RenderMarkdown(text, true, false),
)
for range time.Tick(time.Second * 6) {
log.Printf("Scanning for queued messages...")
for _, msg := range MatrixOut {
_, err := client.SendMessageEvent(context.Background(), id.RoomID(configuration.matrix.room_id), event.EventMessage, format.RenderMarkdown(msg.text, true, false))
if err != nil {
log.Printf("[Matrix] ERROR : %s", err)
continue
}
log.Print("[Matrix] Sent queued message successfully.")
}
MatrixOut.mux.Unlock()
MatrixOut = []MatrixMessage{}
}
}()

View File

@ -1,140 +0,0 @@
package main
import (
"context"
"fmt"
"maunium.net/go/mautrix/event"
)
var Chatcommands = []MatrixCommand{}
// getSitesByString is a helper function for chat commands.
// If text is "all" it will get all sites. If text is a specific site name it will get that site.
// Returns a list of strings that are textual representations of errors.
func getSitesByString(text string) ([]Site, []string) {
errors := []string{} // errors holds any errors we encounter in this function
sites := []Site{} // sites holds every site we need
// Determine which sites to get
if text == "all" { // If we need to get all sites, (!restart all)
var err error
sites, err = getAllSites() // Get all sites
if err != nil { // Check for errors
errors = append(errors, "Failed to get all sites!")
}
} else { // If we need to get a specific site, (!restart LapisDeploy-TestApp)
site, found, err := getSite(text) // (Attempt to) get that site.
// Check if something went wrong (site doesn't exist, error occured)
if err != nil { // Error occured.
errors = append(errors, "Failed to get site "+text+"!")
} else if !found { // Site doesn't exist.
errors = append(errors, "Invalid site.")
}
sites = append(sites, site) // Add this site to the list of sites needed
}
return sites, errors
}
func registerChatCommands() {
Chatcommands = []MatrixCommand{
{
cmd: "help",
description: "Show the help dialouge",
callback: func(ctx context.Context, evt *event.Event, args []string) string {
text := ""
for _, cmd := range Chatcommands {
text = fmt.Sprintf("%s- %s\n %s\n", text, cmd.cmd, cmd.description)
}
return text
},
},
{
cmd: "sites",
description: "Display all available sites",
callback: func(ctx context.Context, evt *event.Event, args []string) string {
text := Circles["white"] + "Getting sites...\n"
sites, err := getAllSites()
if err != nil {
return text + Circles["red"] + "Failed to get sites!"
}
for _, site := range sites {
text = fmt.Sprintf("%s%s", text, site.getName())
if site.config.name != "" { // Only add technical name to sites with a configured name.
text += " (" + site.name + ")"
}
text += "\n"
}
if len(sites) == 0 {
text = text + "*No sites found*"
}
return text
},
},
{
cmd: "restart",
description: "Restart either a specific site, or all sites.",
callback: func(ctx context.Context, evt *event.Event, args []string) string {
if len(args) < 2 { // If no arguments were given
return Circles["red"] + "Invalid site."
}
sites, errors := getSitesByString(args[1])
text := "" // text contains the entire message that will be sent.
for _, error := range errors {
text += Circles["red"] + error + "\n"
}
for _, site := range sites { // For every site queued to be restarted,
if err := site.Restart(); err != nil { // Attempt to restart it
text += fmt.Sprintf("%sRestarting '%s'... failed!\n", Circles["red"], site.getName())
} else { // Otherwise, success.
text += fmt.Sprintf("%sRestarting '%s'... success", Circles["green"], site.getName())
}
}
return text // Return the message.
},
},
{
cmd: "start",
description: "Start a site.",
callback: func(ctx context.Context, evt *event.Event, args []string) string {
if len(args) < 2 {
return Circles["red"] + "Invalid site."
}
sites, errors := getSitesByString(args[1])
text := "" // text contains the entire message that will be sent.
for _, error := range errors {
text += Circles["red"] + error + "\n"
}
for _, site := range sites {
if err := site.Start(); err != nil {
text += fmt.Sprintf("%sStarting '%s'... failed!\n", Circles["red"], site.getName())
} else {
text += fmt.Sprintf("%sStarting '%s'... success!\n", Circles["green"], site.getName())
}
}
return text
},
},
{
cmd: "stop",
description: "Stop a site.",
callback: func(ctx context.Context, evt *event.Event, args []string) string {
if len(args) < 2 {
return Circles["red"] + "Invalid site."
}
sites, errors := getSitesByString(args[1])
text := "" // text contains the entire message that will be sent.
for _, error := range errors {
text += Circles["red"] + error + "\n"
}
for _, site := range sites {
if err := site.Stop(); err != nil {
text += fmt.Sprintf("%sStopping '%s'... failed: %s", Circles["red"], site.getName(), err)
} else {
text += fmt.Sprintf("%sStopping '%s'... success", Circles["green"], site.getName())
}
}
return text
},
},
}
}

92
site.go
View File

@ -24,9 +24,6 @@ type Site struct {
type SiteConfig struct {
port int64
name string
git struct {
branch string
}
}
// getSite gets a specific site and returns a Site struct and a bool indicating whether a site was found.
@ -48,41 +45,24 @@ func getSite(name string) (Site, bool, error) {
// getConfig parses a site's configuration file.
func (site *Site) getConfig() (bool, error) {
path := fmt.Sprintf("%s/%s/deploy_config.lua", configuration.sites_dir, site.name)
warning := fmt.Sprintf("%s%s : Site config warning : ", Circles["orange"], site.getName())
// Make sure config file exists
if exists, _ := fileExists(path); !exists {
return false, nil
}
log.Printf("Loading per-site config %s", path)
// Lua state setup
L := lua.NewState()
defer L.Close()
L.DoFile(path) // Load the config
table := L.Get(-1) // Get the table returned by the config file
if table.Type().String() != "table" { // Make sure 'config' is of type 'table'
err := fmt.Sprintf("Value returned by config is of type '%s', not 'table'", table.Type().String())
sendMessage(MatrixMessage{text: warning + err})
return false, errors.New(err)
}
L.DoFile(path) // Load the config
table := L.Get(-1) // Get the table returned by the config file
// Parse the config
config := SiteConfig{}
var config SiteConfig
log.Printf("Loading per-site config %s", path)
getStringFromTable(L, table, "name", &config.name)
getIntFromTable(L, table, "port", &config.port)
if _, err := getStringFromTable(L, table, "name", &config.name); err != nil { // name
sendMessage(MatrixMessage{text: warning + fmt.Sprint(err)})
}
if _, err := getIntFromTable(L, table, "port", &config.port); err != nil { // port
sendMessage(MatrixMessage{text: warning + fmt.Sprint(err)})
}
raw_gitt := L.GetTable(table, lua.LString("git")) // git
if gitt, ok := L.GetTable(table, lua.LString("git")).(*lua.LTable); ok {
if _, err := getStringFromTable(L, gitt, "branch", &config.git.branch); err != nil { // git.branch
sendMessage(MatrixMessage{text: warning + fmt.Sprint(err)})
}
} else if _, ok := raw_gitt.(*lua.LNilType); !ok { // If 'git' is neither a table or nil (undefined),
sendMessage(MatrixMessage{text: warning + "'git' is neither a table or nil!"})
}
site.config = config
return true, nil
@ -98,12 +78,13 @@ func (site *Site) getName() string {
}
// getAllSites gets every site installed.
func getAllSites() ([]Site, error) {
func getAllSites() ([]Site, DeployError) {
sites_dir := configuration.sites_dir
files, err := os.ReadDir(sites_dir)
var sites []Site
if err != nil {
return sites, errors.New(fmt.Sprintf("Failed to read sites: %s", err))
return sites, newDeployError(1, "startAllSites",
"Failed to read sites", fmt.Sprint(err))
}
for _, file := range files {
if !file.IsDir() {
@ -111,30 +92,30 @@ func getAllSites() ([]Site, error) {
}
site, exists, err := getSite(file.Name())
if err != nil || !exists {
return sites, errors.New(fmt.Sprintf("Failed to read sites: %s", err))
return sites, newDeployError(1, "getAllSites", "Failed to read sites", fmt.Sprint(err))
}
sites = append(sites, site)
}
return sites, nil
return sites, DeployError{}
}
// startAllSites attempts to start every site
func startAllSites() error {
func startAllSites() DeployError {
sites, err := getAllSites()
if err != nil {
if err.code != 0 {
return err
}
for _, site := range sites {
err = site.Start()
if err != nil {
if err.code != 0 {
return err
}
}
return nil
return DeployError{}
}
// Start attempts to start a Lapis server in the given repository.
func (site *Site) Start() error {
func (site *Site) Start() DeployError {
log.Printf("Starting Lapis server in %s...", site.getName())
old_cwd, _ := os.Getwd()
@ -143,17 +124,18 @@ func (site *Site) Start() error {
cmd := exec.Command("lapis", "serve")
if err := cmd.Start(); err != nil {
return errors.New(fmt.Sprintf("Failed to start Lapis server in '%s': %s", site.getName(), err))
return newDeployError(1, "startSite",
fmt.Sprintf("Failed to start Lapis server in '%s'", site.getName()), "")
}
go func() {
cmd.Wait()
}()
return nil
return DeployError{}
}
// Stop attempts to stop a Lapis server in the given repository.
func (site *Site) Stop() error {
func (site *Site) Stop() DeployError {
log.Printf("Stopping Lapis server %s...", site.getName())
old_cwd, _ := os.Getwd()
@ -162,16 +144,17 @@ func (site *Site) Stop() error {
cmd := exec.Command("lapis", "term")
if err := cmd.Start(); err != nil {
return errors.New(fmt.Sprintf("Failed to stop Lapis server in '%s': %s", site.getName(), err))
return newDeployError(1, "stopSite",
fmt.Sprintf("Failed to stop Lapis server in '%s'", site.getName()), "")
}
go func() {
cmd.Wait()
}()
return nil
return DeployError{}
}
// Restart attempts to restart the Lapis server in the given repository.
func (site *Site) Restart() error {
func (site *Site) Restart() DeployError {
log.Printf("Restarting Lapis server in %s...", site.getName())
old_cwd, _ := os.Getwd()
@ -180,33 +163,38 @@ func (site *Site) Restart() error {
out, err := exec.Command("lapis", "build").CombinedOutput()
if err != nil {
return errors.New(fmt.Sprintf("Failed to run 'lapis build' in '%s': %s", site.getName(), err))
return newDeployError(1, "restartSite",
fmt.Sprintf("Failed to run 'lapis build' in '%s'", site.getName()), string(out))
}
log.Printf("[lapis build] %s", out)
if !strings.Contains(string(out), "HUP") {
return errors.New(fmt.Sprintf("Failed to restart Lapis server! (Lapis not running?): %s", string(out)))
return newDeployError(1, "restartSite",
"Failed to restart Lapis server! (Lapis not running?)", string(out))
}
return nil
return DeployError{}
}
// Update attempts to pull or clone a repository using the given name and url
func (site *Site) Update() error {
func (site *Site) Update() DeployError {
log.Printf("Pulling down repository %s...", site.getName())
repo, err := git.Open(configuration.sites_dir + "/" + site.name)
if err != nil {
return errors.New(fmt.Sprintf("Failed to open git repository '%s': %s", site.name, err))
return newDeployError(1, "updateSite",
fmt.Sprintf("Failed to open git repository '%s'", site.name), fmt.Sprint(err))
}
if err = repo.Pull(); err != nil {
return errors.New(fmt.Sprintf("Failed to pull down git repository '%s': %s", site.getName(), err))
return newDeployError(1, "updateSite",
fmt.Sprintf("Failed to pull down git repository '%s'", site.getName()), fmt.Sprint(err))
}
return nil
return DeployError{}
}
// CloneSite will clone a site and put it in the configured 'sites_dir'
func CloneSite(url string, name string) error {
func CloneSite(url string, name string) DeployError {
log.Printf("Cloning repository %s...", name)
if err := git.Clone(url, configuration.sites_dir+"/"+name); err != nil {
return errors.New(fmt.Sprintf("Failed to pull down repository '%s': %s", name, err))
return newDeployError(1, "cloneSite",
fmt.Sprintf("Failed to pull down repository '%s'", name), fmt.Sprint(err))
}
return nil
return DeployError{}
}