-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
137 lines (122 loc) · 3.75 KB
/
server.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// Package server contains handlers which respond to requests to combine
// pdf files and hands them off to the combiner package.
// TODO more informative validation errors
package server
import (
"fmt"
"github.com/PeopleAdmin/pdfcombiner/combiner"
"github.com/PeopleAdmin/pdfcombiner/job"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"sync"
"syscall"
"time"
)
// A CombinerServer needs a port to listen on and a WaitGroup to keep
// track of how many background jobs it has spawned that have not yet
// yet completed their work.
type CombinerServer struct {
port int
pending *sync.WaitGroup
}
var invalidMessage = []byte("{\"response\":\"invalid params\"}\n")
var okMessage = []byte("{\"response\":\"ok\"}\n")
var host, _ = os.Hostname()
var launchTime = time.Now()
// Listen starts a HTTP server listening on `Port` to respond to
// JSON-formatted combination requests.
func (c CombinerServer) Listen(listenPort int) {
c.port = listenPort
c.pending = new(sync.WaitGroup)
listener, err := net.Listen("tcp", c.portString())
if err != nil {
panic(err)
}
log.Println("Accepting connections on " + c.portString())
c.registerHandlers(listener)
http.Serve(listener, http.DefaultServeMux)
log.Println("Waiting for all jobs to finish...")
c.pending.Wait()
}
// ProcessJob is a handler to recieve a JSON body encoding a Job. If
// it validates, send it along to be fulfilled, keeping track of the
// in-flight job count.
func (c CombinerServer) ProcessJob(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
if !authenticate(w, r) {
return
}
j, err := job.NewFromJSON(r.Body)
logJobReceipt(r, j)
if err != nil || !j.IsValid() {
w.WriteHeader(http.StatusBadRequest)
w.Write(invalidMessage)
return
}
w.Write(okMessage)
c.registerWorker()
go func() {
defer c.unregisterWorker()
combiner.Combine(j)
}()
}
// Ping is no-op handler for responding to things like health checks.
// It responds 200 OK with no content to all requests.
func (c CombinerServer) Ping(w http.ResponseWriter, r *http.Request) {
log.Println(requestInfo(r))
}
func (c CombinerServer) Status(w http.ResponseWriter, r *http.Request) {
log.Println(requestInfo(r))
w.Header().Set("Content-Type", "application/json")
template := `{"host": "%s", "running": %d, "waiting": %d, "total_received": %d, "uptime_minutes": %d }` + "\n"
jobs := fmt.Sprintf(template,
host, combiner.CurrentJobs(), combiner.CurrentWait(), combiner.TotalJobsReceived(), uptime())
w.Write([]byte(jobs))
}
func uptime() int {
return int(time.Since(launchTime).Minutes())
}
func logJobReceipt(r *http.Request, j *job.Job) {
log.Printf("%s %v, callback: %s\n", j.Id(), requestInfo(r), j.Callback)
}
func requestInfo(r *http.Request) string {
return fmt.Sprintf("%v %v from %v", r.Method, r.URL, r.RemoteAddr)
}
// http.ListenAndServe needs a string for the port.
func (c CombinerServer) portString() string {
return ":" + strconv.Itoa(c.port)
}
// registerWorker increments the count of in-progress jobs
func (c CombinerServer) registerWorker() {
c.pending.Add(1)
}
// workerDone decrements the count of in-progress jobs.
func (c CombinerServer) unregisterWorker() {
c.pending.Done()
}
func (c CombinerServer) registerHandlers(listener net.Listener) {
http.HandleFunc("/health_check", c.Ping)
http.HandleFunc("/status", c.Status)
http.HandleFunc("/", c.ProcessJob)
handleSignals(listener)
}
// On OS shutdown or Ctrl-C, immediately close the tcp listener,
// but let background jobs finish before actually exiting.
func handleSignals(listener net.Listener) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt)
signal.Notify(sigs, syscall.SIGTERM)
go func() {
for _ = range sigs {
listener.Close()
}
}()
}