Skip to content

Instantly share code, notes, and snippets.

@hulucc
Created October 11, 2020 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hulucc/0a049cfec62502fb60498af975da19ae to your computer and use it in GitHub Desktop.
Save hulucc/0a049cfec62502fb60498af975da19ae to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
func server() {
fmt.Println("server...")
host, err := os.Hostname()
if err != nil {
panic(err)
}
p := make([]byte, 2048)
server, err := net.ListenUDP("udp", &net.UDPAddr{
Port: 30000,
IP: net.ParseIP("0.0.0.0"),
})
if err != nil {
fmt.Printf("Some error %v\n", err)
return
}
stop := false
for {
n, addr, err := server.ReadFromUDP(p)
if err != nil {
fmt.Printf("Some error %v", err)
continue
}
fmt.Printf("recv %s\n", p[:n])
if string(p[:n]) == "stop" {
stop = true
continue
}
if stop && string(p[:n]) == "health" {
fmt.Println("stopped => unhealth")
continue
}
server.WriteToUDP([]byte(fmt.Sprintf("%s:%s", host, p[:n])), addr)
}
}
func rollout() {
cmd := exec.Command("make", "deploy-local")
err := cmd.Run()
if err != nil {
fmt.Printf("rollout err: %v", err)
}
}
func health() {
conn, err := net.Dial("udp", "127.0.0.1:30000")
if err != nil {
panic(err)
}
_, err = fmt.Fprintf(conn, fmt.Sprintf("health"))
if err != nil {
panic(err)
}
p := make([]byte, 2048)
conn.SetReadDeadline(time.Now().Add(time.Second))
n, err := conn.Read(p)
if err != nil {
panic(err)
}
fmt.Println(string(p[:n]))
if n == 0 {
os.Exit(1)
}
}
func stop() {
conn, err := net.Dial("udp", "127.0.0.1:30000")
if err != nil {
panic(err)
}
_, err = fmt.Fprintf(conn, fmt.Sprintf("stop"))
if err != nil {
panic(err)
}
}
func client() {
conn, err := net.Dial("udp", "127.0.0.1:30000")
defer conn.Close()
if err != nil {
panic(err)
}
go func() {
i := 0
for {
i = i + 1
fmt.Fprintf(conn, fmt.Sprintf("%d", i))
time.Sleep(time.Millisecond * 10)
}
}()
lastHost := ""
lastIndex := 0
for {
p := make([]byte, 2048)
n, err := conn.Read(p)
if err != nil {
fmt.Printf("read error %v\n", err)
continue
}
splits := strings.Split(string(p[:n]), ":")
host := splits[0]
index, err := strconv.Atoi(splits[1])
if err != nil {
panic(err)
}
if index != lastIndex+1 {
missStart := lastIndex + 1
missEnd := index - 1
fmt.Printf("index jump: %d-%d\n", missStart, missEnd)
if missEnd-missStart > 10 {
os.Exit(1)
}
}
if host != lastHost {
fmt.Printf("new host: %s\n", host)
lastHost = host
go rollout()
}
lastIndex = index
}
}
func main() {
switch os.Args[1] {
case "server":
server()
case "client":
client()
case "health":
health()
case "stop":
stop()
default:
fmt.Println("please specify type")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment