node-api/tools.go

97 lines
1.7 KiB
Go
Raw Normal View History

2021-04-25 22:57:05 +00:00
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"time"
"github.com/nats-io/nats.go"
"github.com/rosti-cz/node-api/apps"
"github.com/rosti-cz/node-api/common"
docker "github.com/rosti-cz/node-api/containers"
2021-04-25 22:57:05 +00:00
)
func errorReplyFormater(m *nats.Msg, message string, err error) error {
reply := ReplyMessage{
Error: true,
Payload: message,
}
log.Println("ERROR:", err.Error())
data, err := json.Marshal(reply)
if err != nil {
log.Println("ERROR:", err.Error())
return err
}
err = m.Respond(data)
if err != nil {
log.Println("ERROR:", err.Error())
return err
}
return err
}
func publish(appName string, state string, isErr bool) {
stateMessage := StateMessage{
AppName: appName,
Error: isErr,
Message: state,
}
data, err := stateMessage.JSON()
if err != nil {
log.Println("ERROR: publish:", err.Error())
}
subjectEvents := fmt.Sprintf("admin.apps.%s.states", config.NATSAlias)
err = nc.Publish(subjectEvents, data)
if err != nil {
log.Println("ERROR: publish:", err.Error())
}
}
// waitForApp waits until app is ready or timeout is reached.
// It's used in some async calls that need at least part of the
// environment prepared.
func waitForApp(appName string) error {
processor := apps.AppsProcessor{
DB: common.GetDBConnection(),
}
2021-04-25 22:57:05 +00:00
sleepFor := 5 * time.Second
loops := 6
for i := 0; i < loops; i++ {
err := updateState(appName)
if err != nil {
time.Sleep(sleepFor)
continue
}
app, err := processor.Get(appName)
2021-04-25 22:57:05 +00:00
if err != nil {
return err
}
container := docker.Container{
App: app,
}
status, err := container.Status()
if status == "running" {
return nil
}
time.Sleep(sleepFor)
continue
}
return errors.New("timeout reached")
}