Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd: add liveness reporter to ping our backend #6

Merged
merged 1 commit into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
adityamaru marked this conversation as resolved.
Show resolved Hide resolved
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
}
12 changes: 12 additions & 0 deletions cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"context"
"errors"
"fmt"
"net/http"
"net/netip"
"os"
"os/signal"
"strconv"
"syscall"
Expand Down Expand Up @@ -115,6 +117,16 @@ func runServer(cmd *cobra.Command, args []string) error {
defer sm.Wait()
defer done()

// Start the liveness reporter.
livenessReporter := &LivenessReporter{
client: http.Client{Timeout: 5 * time.Second},
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