-
Notifications
You must be signed in to change notification settings - Fork 167
/
rpc.go
502 lines (452 loc) · 14.1 KB
/
rpc.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package server
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/net/http2"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/livepeer/go-livepeer/core"
"github.com/livepeer/go-livepeer/eth"
lpTypes "github.com/livepeer/go-livepeer/eth/types"
"github.com/livepeer/go-livepeer/monitor"
"github.com/livepeer/go-livepeer/net"
"github.com/livepeer/lpms/stream"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
)
const HTTPTimeout = 8 * time.Second
const GRPCTimeout = 8 * time.Second
const GRPCConnectTimeout = 3 * time.Second
const AuthType_LPE = "Livepeer-Eth-1"
type Orchestrator interface {
ServiceURI() *url.URL
Address() ethcommon.Address
Sign([]byte) ([]byte, error)
CurrentBlock() *big.Int
GetJob(int64) (*lpTypes.Job, error)
TranscodeSeg(*lpTypes.Job, *core.SignedSegment) (*core.TranscodeResult, error)
StreamIDs(*lpTypes.Job) ([]core.StreamID, error)
}
type Broadcaster interface {
Sign([]byte) ([]byte, error)
Job() *lpTypes.Job
SetHTTPClient(*http.Client)
GetHTTPClient() *http.Client
SetTranscoderInfo(*net.TranscoderInfo)
GetTranscoderInfo() *net.TranscoderInfo
}
func genTranscoderReq(b Broadcaster, jid int64) (*net.TranscoderRequest, error) {
sig, err := b.Sign([]byte(fmt.Sprintf("%v", jid)))
if err != nil {
return nil, err
}
return &net.TranscoderRequest{JobId: jid, Sig: sig}, nil
}
func blockInRange(orch Orchestrator, job *lpTypes.Job) bool {
blk := orch.CurrentBlock()
if blk == nil {
// The benefit of doubt.
// May be offchain or have internal errors in fetching a block.
return true
}
canClaim := job.FirstClaimSubmitted || blk.Cmp(new(big.Int).Add(job.CreationBlock, big.NewInt(256))) <= 0
return canClaim && !(blk.Cmp(job.CreationBlock) == -1 || blk.Cmp(job.EndBlock) == 1)
}
func verifyMsgSig(addr ethcommon.Address, msg string, sig []byte) bool {
return eth.VerifySig(addr, crypto.Keccak256([]byte(msg)), sig)
}
func verifyTranscoderReq(orch Orchestrator, req *net.TranscoderRequest, job *lpTypes.Job) error {
if orch.Address() != job.TranscoderAddress {
glog.Error("Transcoder was not assigned")
return fmt.Errorf("Transcoder was not assigned")
}
if !blockInRange(orch, job) {
glog.Error("Job out of range")
return fmt.Errorf("Job out of range")
}
if !verifyMsgSig(job.BroadcasterAddress, fmt.Sprintf("%v", job.JobId), req.Sig) {
glog.Error("transcoder req sig check failed")
return fmt.Errorf("transcoder req sig check failed")
}
return nil
}
func genToken(orch Orchestrator, job *lpTypes.Job) (string, error) {
sig, err := orch.Sign([]byte(fmt.Sprintf("%v", job.JobId)))
if err != nil {
return "", err
}
data, err := proto.Marshal(&net.AuthToken{JobId: job.JobId.Int64(), Sig: sig})
if err != nil {
glog.Error("Unable to marshal ", err)
return "", err
}
return base64.StdEncoding.EncodeToString(data), nil
}
func verifyToken(orch Orchestrator, creds string) (*lpTypes.Job, error) {
buf, err := base64.StdEncoding.DecodeString(creds)
if err != nil {
glog.Error("Unable to base64-decode ", err)
return nil, err
}
var token net.AuthToken
err = proto.Unmarshal(buf, &token)
if err != nil {
glog.Error("Unable to unmarshal ", err)
return nil, err
}
if !verifyMsgSig(orch.Address(), fmt.Sprintf("%v", token.JobId), token.Sig) {
glog.Error("Sig check failed")
return nil, fmt.Errorf("Token sig check failed")
}
job, err := orch.GetJob(token.JobId)
if err != nil || job == nil {
glog.Error("Could not get job ", err)
return nil, fmt.Errorf("Missing job (%s)", err.Error())
}
if !blockInRange(orch, job) {
glog.Errorf("Job %v too early or expired", job.JobId)
return nil, fmt.Errorf("Job out of range")
}
return job, nil
}
func genSegCreds(bcast Broadcaster, streamId string, segData *net.SegData) (string, error) {
seg := &lpTypes.Segment{
StreamID: streamId,
SegmentSequenceNumber: big.NewInt(segData.Seq),
DataHash: ethcommon.BytesToHash(segData.Hash),
}
sig, err := bcast.Sign(seg.Flatten())
if err != nil {
return "", nil
}
segData.Sig = sig
data, err := proto.Marshal(segData)
if err != nil {
glog.Error("Unable to marshal ", err)
return "", err
}
return base64.StdEncoding.EncodeToString(data), nil
}
func verifySegCreds(job *lpTypes.Job, segCreds string) (*net.SegData, error) {
buf, err := base64.StdEncoding.DecodeString(segCreds)
if err != nil {
glog.Error("Unable to base64-decode ", err)
return nil, err
}
var segData net.SegData
err = proto.Unmarshal(buf, &segData)
if err != nil {
glog.Error("Unable to unmarshal ", err)
return nil, err
}
seg := &lpTypes.Segment{
StreamID: job.StreamId,
SegmentSequenceNumber: big.NewInt(segData.Seq),
DataHash: ethcommon.BytesToHash(segData.Hash),
}
if !verifyMsgSig(job.BroadcasterAddress, string(seg.Flatten()), segData.Sig) {
glog.Error("Sig check failed")
return nil, fmt.Errorf("Segment sig check failed")
}
return &segData, nil
}
func getTranscoder(context context.Context, orch Orchestrator, req *net.TranscoderRequest) (*net.TranscoderInfo, error) {
glog.Info("Got transcoder request for job ", req.JobId)
job, err := orch.GetJob(req.JobId)
if err != nil {
glog.Error("Unable to get job ", err)
return nil, fmt.Errorf("Unable to get job (%s)", err.Error())
}
if err := verifyTranscoderReq(orch, req, job); err != nil {
return nil, fmt.Errorf("Invalid transcoder request (%v)", err)
}
creds, err := genToken(orch, job)
if err != nil {
return nil, err
}
sids, err := orch.StreamIDs(job)
if err != nil {
return nil, err
}
stringStreamIds := make(map[string]string)
for i, s := range sids {
stringStreamIds[s.String()] = job.Profiles[i].Name
}
tr := net.TranscoderInfo{
Transcoder: orch.ServiceURI().String(), // currently, orchestrator == transcoder
AuthType: AuthType_LPE,
Credentials: creds,
StreamIds: stringStreamIds,
}
return &tr, nil
}
type lphttp struct {
orchestrator Orchestrator
orchRpc *grpc.Server
transRpc *http.ServeMux
}
func (h *lphttp) ServeSegment(w http.ResponseWriter, r *http.Request) {
orch := h.orchestrator
// check the credentials from the orchestrator
authType := r.Header.Get("Authorization")
creds := r.Header.Get("Credentials")
if AuthType_LPE != authType {
glog.Error("Invalid auth type ", authType)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
job, err := verifyToken(orch, creds)
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
// check the segment sig from the broadcaster
seg := r.Header.Get("Livepeer-Segment")
segData, err := verifySegCreds(job, seg)
if err != nil {
glog.Error("Could not verify segment creds")
http.Error(w, err.Error(), http.StatusForbidden)
return
}
// download the segment and check the hash
data, err := ioutil.ReadAll(r.Body)
if err != nil {
glog.Error("Could not read request body", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
hash := crypto.Keccak256(data)
if !bytes.Equal(hash, segData.Hash) {
glog.Error("Mismatched hash for body; rejecting")
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
// Send down 200OK early as an indication that the upload completed
// Any further errors come through the response body
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
ss := core.SignedSegment{
Seg: stream.HLSSegment{
SeqNo: uint64(segData.Seq),
Data: data,
},
Sig: segData.Sig,
}
res, err := orch.TranscodeSeg(job, &ss)
// sanity check
if err == nil && len(res.Urls) != len(job.Profiles) {
err = fmt.Errorf("Mismatched result lengths")
}
// construct the response
var result net.TranscodeResult
if err != nil {
glog.Error("Could not transcode ", err)
result = net.TranscodeResult{Result: &net.TranscodeResult_Error{Error: err.Error()}}
} else {
segments := make([]*net.TranscodedSegmentData, len(res.Urls))
for i, v := range res.Urls {
d := &net.TranscodedSegmentData{
Url: orch.ServiceURI().String() + "/stream/" + v,
}
segments[i] = d
}
result = net.TranscodeResult{Result: &net.TranscodeResult_Data{
Data: &net.TranscodeData{
Segments: segments,
Sig: res.Sig,
}},
}
}
tr := &net.TranscodeResult{
Seq: segData.Seq,
Result: result.Result,
}
buf, err := proto.Marshal(tr)
if err != nil {
glog.Error("Unable to marshal transcode result ", err)
return
}
w.Write(buf)
}
// grpc methods
func (h *lphttp) GetTranscoder(context context.Context, req *net.TranscoderRequest) (*net.TranscoderInfo, error) {
return getTranscoder(context, h.orchestrator, req)
}
func (h *lphttp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ct := r.Header.Get("Content-Type")
if r.ProtoMajor == 2 && strings.HasPrefix(ct, "application/grpc") {
h.orchRpc.ServeHTTP(w, r)
} else {
h.transRpc.ServeHTTP(w, r)
}
}
// XXX do something about the implicit start of the http mux? this smells
func StartTranscodeServer(orch Orchestrator, bind string, mux *http.ServeMux, workDir string) {
s := grpc.NewServer()
lp := lphttp{
orchestrator: orch,
orchRpc: s,
transRpc: mux,
}
net.RegisterOrchestratorServer(s, &lp)
lp.transRpc.HandleFunc("/segment", lp.ServeSegment)
cert, key, err := getCert(orch.ServiceURI(), workDir)
if err != nil {
return // XXX return error
}
glog.Info("Listening for RPC on ", bind)
srv := http.Server{
Addr: bind,
Handler: &lp,
ReadTimeout: HTTPTimeout,
WriteTimeout: HTTPTimeout,
}
srv.ListenAndServeTLS(cert, key)
}
func StartBroadcastClient(bcast Broadcaster, orchestratorServer string) error {
tlsConfig := &tls.Config{InsecureSkipVerify: true}
httpc := &http.Client{
Transport: &http2.Transport{TLSClientConfig: tlsConfig},
Timeout: HTTPTimeout,
}
uri, err := url.Parse(orchestratorServer)
if err != nil {
glog.Error("Could not parse orchestrator URI: ", err)
return err
}
glog.Infof("Connecting RPC to %v", orchestratorServer)
conn, err := grpc.Dial(uri.Host,
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
grpc.WithBlock(),
grpc.WithTimeout(GRPCConnectTimeout))
if err != nil {
glog.Error("Did not connect: ", err)
return errors.New("Did not connect: " + err.Error())
}
defer conn.Close()
c := net.NewOrchestratorClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), GRPCTimeout)
defer cancel()
bcast.SetHTTPClient(httpc)
req, err := genTranscoderReq(bcast, bcast.Job().JobId.Int64())
r, err := c.GetTranscoder(ctx, req)
if err != nil {
glog.Errorf("Could not get transcoder for job %d: %s", bcast.Job().JobId.Int64(), err.Error())
return errors.New("Could not get transcoder: " + err.Error())
}
bcast.SetTranscoderInfo(r)
return nil
}
func SubmitSegment(bcast Broadcaster, seg *stream.HLSSegment, nonce uint64) (*net.TranscodeData, error) {
if monitor.Enabled {
monitor.SegmentUploadStart(nonce, seg.SeqNo)
}
hc := bcast.GetHTTPClient()
segData := &net.SegData{
Seq: int64(seg.SeqNo),
Hash: crypto.Keccak256(seg.Data),
}
segCreds, err := genSegCreds(bcast, bcast.Job().StreamId, segData)
if err != nil {
if monitor.Enabled {
monitor.LogSegmentUploadFailed(nonce, seg.SeqNo, err.Error())
}
return nil, err
}
ti := bcast.GetTranscoderInfo()
req, err := http.NewRequest("POST", ti.Transcoder+"/segment", bytes.NewBuffer(seg.Data))
if err != nil {
glog.Error("Could not generate trascode request to ", ti.Transcoder)
if monitor.Enabled {
monitor.LogSegmentUploadFailed(nonce, seg.SeqNo, err.Error())
}
return nil, err
}
req.Header.Set("Authorization", ti.AuthType)
req.Header.Set("Credentials", ti.Credentials)
req.Header.Set("Livepeer-Segment", segCreds)
req.Header.Set("Content-Type", "video/MP2T")
glog.Infof("Submitting segment %v : %v bytes", seg.SeqNo, len(seg.Data))
start := time.Now()
resp, err := hc.Do(req)
uploadDur := time.Since(start)
if err != nil {
glog.Error("Unable to submit segment ", seg.SeqNo, err)
if monitor.Enabled {
monitor.LogSegmentUploadFailed(nonce, seg.SeqNo, err.Error())
}
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
data, _ := ioutil.ReadAll(resp.Body)
glog.Errorf("Error submitting segment %d: code %d error %v", seg.SeqNo, resp.StatusCode, string(data))
if monitor.Enabled {
monitor.LogSegmentUploadFailed(nonce, seg.SeqNo, fmt.Sprintf("Code: %d Error: %s", resp.StatusCode,
strings.TrimSpace(string(data))))
}
return nil, fmt.Errorf(string(data))
}
glog.Infof("Uploaded segment %v", seg.SeqNo)
if monitor.Enabled {
monitor.LogSegmentUploaded(nonce, seg.SeqNo, uploadDur)
}
data, err := ioutil.ReadAll(resp.Body)
tookAllDur := time.Since(start)
if err != nil {
glog.Error(fmt.Sprintf("Unable to read response body for segment %v : %v", seg.SeqNo, err))
if monitor.Enabled {
monitor.LogSegmentTranscodeFailed("ReadBody", nonce, seg.SeqNo, err)
}
return nil, err
}
transcodeDur := tookAllDur - uploadDur
var tr net.TranscodeResult
err = proto.Unmarshal(data, &tr)
if err != nil {
glog.Error(fmt.Sprintf("Unable to parse response for segment %v : %v", seg.SeqNo, err))
if monitor.Enabled {
monitor.LogSegmentTranscodeFailed("ParseResponse", nonce, seg.SeqNo, err)
}
return nil, err
}
// check for errors and exit early if there's anything unusual
var tdata *net.TranscodeData
switch res := tr.Result.(type) {
case *net.TranscodeResult_Error:
err = fmt.Errorf(res.Error)
glog.Errorf("Transcode failed for segment %v: %v", seg.SeqNo, err)
if monitor.Enabled {
monitor.LogSegmentTranscodeFailed("Transcode", nonce, seg.SeqNo, err)
}
return nil, err
case *net.TranscodeResult_Data:
// fall through here for the normal case
tdata = res.Data
default:
glog.Error("Unexpected or unset transcode response field for ", seg.SeqNo)
err = fmt.Errorf("UnknownResponse")
if monitor.Enabled {
monitor.LogSegmentTranscodeFailed("UnknownResponse", nonce, seg.SeqNo, err)
}
return nil, err
}
// transcode succeeded; continue processing response
if monitor.Enabled {
monitor.LogSegmentTranscoded(nonce, seg.SeqNo, transcodeDur, tookAllDur)
}
glog.Info("Successfully transcoded segment ", seg.SeqNo)
return tdata, nil
}