63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"sea-vhost/internal/schedulerbridge"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func main() {
|
|
if e := tick(); e != nil {
|
|
fmt.Fprintln(os.Stderr, "Sea vHost 调度触发失败")
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
func tick() error {
|
|
if len(os.Args) != 2 || os.Args[1] != "tick" {
|
|
return fmt.Errorf("usage: sea-vhost-scheduler tick")
|
|
}
|
|
raw, e := os.ReadFile(schedulerbridge.ConfigPath)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
var cfg schedulerbridge.Config
|
|
if json.Unmarshal(raw, &cfg) != nil || cfg.Validate() != nil {
|
|
return fmt.Errorf("invalid configuration")
|
|
}
|
|
nonce := make([]byte, 16)
|
|
if _, e = rand.Read(nonce); e != nil {
|
|
return e
|
|
}
|
|
node := strconv.FormatUint(cfg.NodeID, 10)
|
|
stamp := strconv.FormatInt(time.Now().Unix(), 10)
|
|
n := hex.EncodeToString(nonce)
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
r, e := http.NewRequestWithContext(ctx, "POST", strings.TrimRight(cfg.Controller, "/")+schedulerbridge.TickPath, nil)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
r.Header.Set("X-Sea-Node", node)
|
|
r.Header.Set("X-Sea-Time", stamp)
|
|
r.Header.Set("X-Sea-Nonce", n)
|
|
r.Header.Set("X-Sea-Signature", schedulerbridge.Signature(cfg.Key, node, stamp, n))
|
|
client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
|
res, e := client.Do(r)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
res.Body.Close()
|
|
if res.StatusCode != 202 && res.StatusCode != 204 {
|
|
return fmt.Errorf("trigger rejected")
|
|
}
|
|
return nil
|
|
}
|