-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathuserschedule.go
100 lines (89 loc) · 2.58 KB
/
userschedule.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// This is an example round-robin scheduler.
// It can be used by modifying Curio's base configuration Subsystems.UserSchedule
// to point to a machine named myscheduler with URL:
// http://myscheduler:7654/userschedule
// Be sure to open the selected port on the machine running this scheduler.
//
// Usage:
//
// Fork the repo from Github and clone it to your local machine,
// Edit this file as needed to implement your own scheduling logic,
// build with 'make userschedule' then run with ./userschedule
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"runtime/debug"
"runtime/pprof"
"sync"
"syscall"
"golang.org/x/xerrors"
)
const WorkerBusyTimeout = 60 // Seconds until Curio asks again for this task.
func sched(w http.ResponseWriter, r *http.Request) {
var input struct {
TaskID string `json:"task_id"`
TaskType string `json:"task_type"`
Workers []string `json:"workers"`
}
// Parse the request
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
OrHTTPFail(w, xerrors.Errorf("failed to parse request: %s", err))
}
// Scheduler Logic goes here
selectedWorker := roundRobin(input.TaskType, input.Workers)
// Respond to Curio
w.WriteHeader(http.StatusOK)
err := json.NewEncoder(w).Encode(struct {
Worker string `json:"worker"`
Timeout int `json:"timeout"`
}{selectedWorker, WorkerBusyTimeout})
if err != nil {
OrHTTPFail(w, err)
}
}
// ///////// Round Robin Scheduler ///////// //
var mx sync.Mutex
var m = make(map[string]int)
func roundRobin(taskType string, workers []string) string {
mx.Lock()
defer mx.Unlock()
selectedWorker := workers[m[taskType]%len(workers)]
m[taskType]++
return selectedWorker
}
// ///////////////////////////////////
// Everything below this line is boilerplate code.
// ///////////////////////////////////
func main() {
setupCloseHandler()
mux := http.NewServeMux()
mux.HandleFunc("/userschedule", func(w http.ResponseWriter, r *http.Request) {
defer func() { _ = recover() }()
sched(w, r)
})
fmt.Println(http.ListenAndServe(":7654", mux))
}
// Intentionally inlined dependencies to make it easy to copy-paste into your own codebase.
func OrHTTPFail(w http.ResponseWriter, err error) {
if err != nil {
w.WriteHeader(500)
_, _ = w.Write([]byte(err.Error()))
log.Printf("http fail. err %s, stack %s", err, string(debug.Stack()))
panic(1)
}
}
func setupCloseHandler() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
fmt.Println("\r- Ctrl+C pressed in Terminal")
_ = pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
panic(1)
}()
}