Skip to content

Commit

Permalink
sentry impl
Browse files Browse the repository at this point in the history
  • Loading branch information
joshspicer authored Dec 24, 2023
1 parent 53d1c95 commit 2221b12
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 8 deletions.
2 changes: 1 addition & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"ghcr.io/devcontainers/features/azure-cli:1": {},
"ghcr.io/devcontainers/features/docker-in-docker:2": {},
"ghcr.io/devcontainers/features/github-cli:1": {},
"ghcr.io/devcontainers/features/kubectl-helm-minikube:1": {}
"ghcr.io/devcontainers/features/kubectl-helm-minikube:1": {},
},
"customizations": {
"vscode": {
Expand Down
7 changes: 3 additions & 4 deletions example.env
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
# VALID_TELEGRAM_GROUPS=
# VALID_TELEGRAM_SENDERS=

# JARVIS_CLOUD_BASE_ADDR

# TRUSTED_ACTORS=

# GIN_MODE=release
# RELEASE=

# AUGUST_API_KEY=
# AUGUST_INSTALLID=
Expand All @@ -15,6 +17,3 @@
# AUGUST_ID=
# AUGUST_LOCK_ID=

# DOMAIN=
# PROTOCOL=

31 changes: 31 additions & 0 deletions server/cloudRouter.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ func CloudRouter(bot *tgbotapi.BotAPI) *gin.Engine {
router.GET("/health", health)
router.GET("/whoami", Auth(), whoami)

router.POST("/heartbeat", Auth(), sentryHeartbeatHandler)

// Knocks
// router.POST("/welcome/:invite_code", welcome)
// router.POST("/trustedknock", Auth(), trustedKnock)
Expand Down Expand Up @@ -51,6 +53,35 @@ func whoami(c *gin.Context) {
c.String(http.StatusOK, authenticatedUser)
}

func sentryHeartbeatHandler(c *gin.Context) {
// Protected by 'TrustedHmacAuthentication' middleware
authenticatedUser := c.MustGet("authenticatedUser").(string)

// Set no cache headers
c.Header("Cache-Control", "no-cache, no-store, no-transform, must-revalidate, private, max-age=0")
c.Header("Pragma", "no-cache")
c.Header("Expires", "0")
c.Header("X-Accel-Expires", "0")

// Parse JSON
var heartbeat Heartbeat
if err := c.ShouldBindJSON(&heartbeat); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

// TEMP: Send to Telegram
bot := c.MustGet(BOT_CONTEXT).(*BotExtended)
bot.SendMessageToPrimaryTelegramGroup(fmt.Sprintf("Heartbeat from '%s' on '%s' at %d", authenticatedUser, heartbeat.HostName, heartbeat.Timestamp))

// Accept if we have not aborted.
if !c.IsAborted() {
var response HeartbeatResponse
response.accepted = true
c.JSON(http.StatusAccepted, response)
}
}

func trustedKnock(c *gin.Context) {
// Protected by 'TrustedHmacAuthentication' middleware
authenticatedUser := c.MustGet("authenticatedUser").(string)
Expand Down
2 changes: 1 addition & 1 deletion server/nodeRouter.go → server/fieldNodeRouter.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/warthog618/modem/serial"
)

func NodeRouter() *gin.Engine {
func FieldNodeRouter() *gin.Engine {
router := gin.Default()

// Static
Expand Down
30 changes: 28 additions & 2 deletions server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"log"
"os"
"strings"

"github.com/gin-gonic/gin"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
Expand Down Expand Up @@ -36,6 +37,8 @@ func main() {
log.Printf("Starting cloud")
bot := SetupTelegram()
initializeCloud(bot, mode)
case "sentry":
initializeSentry()
// case "home":
// log.Printf("Starting home")
// bot := SetupTelegram()
Expand Down Expand Up @@ -65,14 +68,37 @@ func initializeCloud(bot *tgbotapi.BotAPI, mode string) {
router.Run(fmt.Sprintf(":%s", PORT))
}

func initializeSentry() {
jarvisCloudBaseAddr := os.Getenv("JARVIS_CLOUD_BASE_ADDR")
trustedActors, err := GetTrustedActors()
if err != nil {
log.Fatalf("Failed to retrieve trusted actors: %s\n", err)
}

primaryActor := trustedActors[0]

// Check jarvisCloudBaseAddr contains protocol and no trailing slash (eg: https://example.com)
if !strings.HasPrefix(jarvisCloudBaseAddr, "http") || jarvisCloudBaseAddr[len(jarvisCloudBaseAddr)-1:] == "/" {
log.Fatalf("Misformed cloud base addr. Got: %s", jarvisCloudBaseAddr)
}

sentry := Sentry{
CloudBaseAddr: jarvisCloudBaseAddr,
Actor: primaryActor,
}

sentry.DoHeartbeat()

// TODO: sentry.Cron()
}

func determineMode() string {
DEFAULT_MODE := "cloud"
if len(os.Args) >= 2 {
return os.Args[1]
}
mode := os.Getenv("JARVIS_MODE")
if mode != "" {
return mode
}
return DEFAULT_MODE
return mode
}
80 changes: 80 additions & 0 deletions server/sentry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
)

type Sentry struct {
CloudBaseAddr string
Actor Actor
}

// Heartbeat object definition (JSON)
type Heartbeat struct {
Id string `json:"id"`
Timestamp int64 `json:"timestamp"`
HostName string `json:"hostname"`
}

type HeartbeatResponse struct {
accepted bool
}

func (s Sentry) DoHeartbeat() {
hostName, err := os.Hostname()
if err != nil {
hostName = "(unknown)"
}

values := Heartbeat{
Id: s.Actor.name,
Timestamp: time.Now().Unix(),
HostName: hostName,
}
s.sendHeartbeat(values)
}

func (s Sentry) sendHeartbeat(values Heartbeat) {

json_data, err := json.Marshal(values)
if err != nil {
fmt.Println(err.Error())
}

// Create new POST request object
req, err := http.NewRequest("POST", s.CloudBaseAddr+"/heartbeat", bytes.NewBuffer(json_data))
if err != nil {
fmt.Println(err.Error())
}

auth, nonce, err := GenerateAuthHeaderForPrimaryActor()
if err != nil {
fmt.Println(err.Error())
}

// Add headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", auth)
req.Header.Set("X-Jarvis-Timestamp", nonce)

// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err.Error())
}

// Close request
defer resp.Body.Close()

// Parse response
var res map[string]interface{}
json.NewDecoder(resp.Body).Decode(&res)
log.Println(res["json"])
}

0 comments on commit 2221b12

Please sign in to comment.