-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.go
87 lines (72 loc) · 2.23 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
package main
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"git.sr.ht/~spc/go-log"
pb "github.com/redhatinsights/yggdrasil/protocol"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// forwarderServer implements the Worker gRPC service as defined by the yggdrasil
// gRPC protocol. It accepts Assignment messages, unmarshals the data into a
// string, and echoes the content back to the Dispatch service by calling the
// "Finish" method.
type forwarderServer struct {
pb.UnimplementedWorkerServer
Url string
Username string
Password string
}
type httpMessage struct {
ResponseTo string `json:"response_to"`
Metadata map[string]string `json:"metadata"`
Content []byte `json:"content"`
Directive string `json:"directive"`
}
// Send implements the "Send" method of the Worker gRPC service.
func (s *forwarderServer) Send(ctx context.Context, d *pb.Data) (*pb.Receipt, error) {
go func() {
log.Tracef("received data: %#v", d)
// Dial the Dispatcher and call "Finish"
conn, err := grpc.Dial(yggdDispatchSocketAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dataJson := jsonData(d)
log.Infof("sending %v", dataJson)
// Call http post
request, _ := http.NewRequest("POST", s.Url, bytes.NewBuffer(dataJson))
request.Header.Set("Content-Type", "application/json")
request.SetBasicAuth(s.Username, s.Password)
client := &http.Client{}
response, error := client.Do(request)
if error != nil {
log.Fatal(error)
}
defer response.Body.Close()
log.Tracef("response Status: %v", response.Status)
log.Tracef("response Headers: %+v", response.Header)
body, _ := io.ReadAll(response.Body)
log.Tracef("response Body: %v", string(body))
}()
// Respond to the start request that the work was accepted.
return &pb.Receipt{}, nil
}
func jsonData(d *pb.Data) []byte {
// Create a data message to send back to the dispatcher.
data := httpMessage{
ResponseTo: d.GetMessageId(),
Metadata: d.GetMetadata(),
Content: d.GetContent(),
Directive: d.GetDirective(),
}
dataJson, error := json.Marshal(data)
if error != nil {
log.Fatal(error)
}
return dataJson
}