Skip to content

Commit

Permalink
cmd: add liveness reporter to ping our backend
Browse files Browse the repository at this point in the history
  • Loading branch information
adityamaru committed Nov 26, 2024
1 parent 1233ced commit edf7171
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
82 changes: 82 additions & 0 deletions cmd/liveness_reporter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package cmd

import (
"bytes"
"context"
"encoding/json"
"fmt"
"math/rand"
"net/http"
"time"
)

type LivenessReporter struct {
client http.Client
backendEndpoint string
backendAdminToken string
ip string
region string
}

func (r *LivenessReporter) Report(ctx context.Context) {
requestBody := struct {
IP string `json:"ip"`
Region string `json:"region"`
}{
IP: r.ip,
Region: r.region,
}
jsonBody, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("failed to marshal request body: %v\n", err)
return
}

req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("%s/staticip/liveness", r.backendEndpoint), bytes.NewBuffer(jsonBody))
if err != nil {
fmt.Printf("failed to create request: %v\n", err)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.backendAdminToken))

resp, err := r.client.Do(req)
if err != nil {
fmt.Printf("failed to send request: %v\n", err)
return
}
defer func() {
if err := resp.Body.Close(); err != nil {
fmt.Printf("failed to close response body: %v\n", err)
}
}()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
fmt.Printf("error reporting liveness: unexpected status code: %d\n", resp.StatusCode)
}
}

const (
minLivenessReportInterval = 1500 * time.Millisecond
maxLivenessReportInterval = 2 * time.Second
)

func (r *LivenessReporter) Start(ctx context.Context) {
go func() {
ticker := time.NewTicker(r.randomInterval())
defer ticker.Stop()

for {
select {
case <-ticker.C:
r.Report(ctx)
ticker.Reset(r.randomInterval())
case <-ctx.Done():
return
}
}
}()
}

func (r *LivenessReporter) randomInterval() time.Duration {
return time.Duration(rand.Int63n(int64(maxLivenessReportInterval-minLivenessReportInterval))) + minLivenessReportInterval
}
10 changes: 10 additions & 0 deletions cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/netip"
"os"
"os/signal"
"strconv"
"syscall"
Expand Down Expand Up @@ -115,6 +116,15 @@ func runServer(cmd *cobra.Command, args []string) error {
defer sm.Wait()
defer done()

// Start the liveness reporter.
livenessReporter := &LivenessReporter{
ip: serverCmdArgs.ip[0],
region: serverCmdArgs.region,
backendEndpoint: os.Getenv("BACKEND_ENDPOINT"),
backendAdminToken: os.Getenv("BACKEND_ADMIN_TOKEN"),
}
livenessReporter.Start(ctx)

for _, ipStr := range serverCmdArgs.ip {
ip, err := netip.ParseAddr(ipStr)
if err != nil || !ip.Is4() {
Expand Down

0 comments on commit edf7171

Please sign in to comment.