Agents (#2203)
* agents * add test * undo name changes * remove debug logs * fixes * fix data race in test
This commit is contained in:
@@ -18,7 +18,7 @@ require (
|
|||||||
github.com/jxskiss/base62 v1.1.0
|
github.com/jxskiss/base62 v1.1.0
|
||||||
github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1
|
github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1
|
||||||
github.com/livekit/mediatransportutil v0.0.0-20231017082622-43f077b4e60e
|
github.com/livekit/mediatransportutil v0.0.0-20231017082622-43f077b4e60e
|
||||||
github.com/livekit/protocol v1.8.2-0.20231101040827-02a4a42603b1
|
github.com/livekit/protocol v1.9.1-0.20231103182211-6d382559cf42
|
||||||
github.com/livekit/psrpc v0.5.0
|
github.com/livekit/psrpc v0.5.0
|
||||||
github.com/mackerelio/go-osstat v0.2.4
|
github.com/mackerelio/go-osstat v0.2.4
|
||||||
github.com/magefile/mage v1.15.0
|
github.com/magefile/mage v1.15.0
|
||||||
|
|||||||
@@ -125,8 +125,8 @@ github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1 h1:jm09419p0lqTkD
|
|||||||
github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ=
|
github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ=
|
||||||
github.com/livekit/mediatransportutil v0.0.0-20231017082622-43f077b4e60e h1:yNeIo7MSMUWgoLu7LkNKnBYnJBFPFH9Wq4S6h1kS44M=
|
github.com/livekit/mediatransportutil v0.0.0-20231017082622-43f077b4e60e h1:yNeIo7MSMUWgoLu7LkNKnBYnJBFPFH9Wq4S6h1kS44M=
|
||||||
github.com/livekit/mediatransportutil v0.0.0-20231017082622-43f077b4e60e/go.mod h1:+WIOYwiBMive5T81V8B2wdAc2zQNRjNQiJIcPxMTILY=
|
github.com/livekit/mediatransportutil v0.0.0-20231017082622-43f077b4e60e/go.mod h1:+WIOYwiBMive5T81V8B2wdAc2zQNRjNQiJIcPxMTILY=
|
||||||
github.com/livekit/protocol v1.8.2-0.20231101040827-02a4a42603b1 h1:WPWxU9w5XHAsonxnSSIIXbWMty9b5uHnTnyKS9TpaXM=
|
github.com/livekit/protocol v1.9.1-0.20231103182211-6d382559cf42 h1:uDziAK5uhQPOj0fCKl+YyJx51tdFORLjC+rHgNNBCmY=
|
||||||
github.com/livekit/protocol v1.8.2-0.20231101040827-02a4a42603b1/go.mod h1:l2WjlZWErS6vBlQaQyCGwWLt1aOx10XfQTsmvLjJWFQ=
|
github.com/livekit/protocol v1.9.1-0.20231103182211-6d382559cf42/go.mod h1:l2WjlZWErS6vBlQaQyCGwWLt1aOx10XfQTsmvLjJWFQ=
|
||||||
github.com/livekit/psrpc v0.5.0 h1:g+yYNSs6Y1/vM7UlFkB2s/ARe2y3RKWZhX8ata5j+eo=
|
github.com/livekit/psrpc v0.5.0 h1:g+yYNSs6Y1/vM7UlFkB2s/ARe2y3RKWZhX8ata5j+eo=
|
||||||
github.com/livekit/psrpc v0.5.0/go.mod h1:1XYH1LLoD/YbvBvt6xg2KQ/J3InLXSJK6PL/+DKmuAU=
|
github.com/livekit/psrpc v0.5.0/go.mod h1:1XYH1LLoD/YbvBvt6xg2KQ/J3InLXSJK6PL/+DKmuAU=
|
||||||
github.com/mackerelio/go-osstat v0.2.4 h1:qxGbdPkFo65PXOb/F/nhDKpF2nGmGaCFDLXoZjJTtUs=
|
github.com/mackerelio/go-osstat v0.2.4 h1:qxGbdPkFo65PXOb/F/nhDKpF2nGmGaCFDLXoZjJTtUs=
|
||||||
|
|||||||
@@ -27,6 +27,10 @@ import (
|
|||||||
"github.com/livekit/protocol/webhook"
|
"github.com/livekit/protocol/webhook"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type AgentClient interface {
|
||||||
|
JobRequest(ctx context.Context, job *livekit.Job)
|
||||||
|
}
|
||||||
|
|
||||||
type EgressLauncher interface {
|
type EgressLauncher interface {
|
||||||
StartEgress(context.Context, *rpc.StartEgressRequest) (*livekit.EgressInfo, error)
|
StartEgress(context.Context, *rpc.StartEgressRequest) (*livekit.EgressInfo, error)
|
||||||
StartEgressWithClusterId(ctx context.Context, clusterId string, req *rpc.StartEgressRequest) (*livekit.EgressInfo, error)
|
StartEgressWithClusterId(ctx context.Context, clusterId string, req *rpc.StartEgressRequest) (*livekit.EgressInfo, error)
|
||||||
+23
-7
@@ -74,6 +74,7 @@ type Room struct {
|
|||||||
audioConfig *config.AudioConfig
|
audioConfig *config.AudioConfig
|
||||||
serverInfo *livekit.ServerInfo
|
serverInfo *livekit.ServerInfo
|
||||||
telemetry telemetry.TelemetryService
|
telemetry telemetry.TelemetryService
|
||||||
|
agentClient AgentClient
|
||||||
egressLauncher EgressLauncher
|
egressLauncher EgressLauncher
|
||||||
trackManager *RoomTrackManager
|
trackManager *RoomTrackManager
|
||||||
|
|
||||||
@@ -113,6 +114,7 @@ func NewRoom(
|
|||||||
audioConfig *config.AudioConfig,
|
audioConfig *config.AudioConfig,
|
||||||
serverInfo *livekit.ServerInfo,
|
serverInfo *livekit.ServerInfo,
|
||||||
telemetry telemetry.TelemetryService,
|
telemetry telemetry.TelemetryService,
|
||||||
|
agentClient AgentClient,
|
||||||
egressLauncher EgressLauncher,
|
egressLauncher EgressLauncher,
|
||||||
) *Room {
|
) *Room {
|
||||||
r := &Room{
|
r := &Room{
|
||||||
@@ -127,6 +129,7 @@ func NewRoom(
|
|||||||
audioConfig: audioConfig,
|
audioConfig: audioConfig,
|
||||||
telemetry: telemetry,
|
telemetry: telemetry,
|
||||||
egressLauncher: egressLauncher,
|
egressLauncher: egressLauncher,
|
||||||
|
agentClient: agentClient,
|
||||||
trackManager: NewRoomTrackManager(),
|
trackManager: NewRoomTrackManager(),
|
||||||
serverInfo: serverInfo,
|
serverInfo: serverInfo,
|
||||||
participants: make(map[livekit.ParticipantIdentity]types.LocalParticipant),
|
participants: make(map[livekit.ParticipantIdentity]types.LocalParticipant),
|
||||||
@@ -898,10 +901,21 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
|
|||||||
|
|
||||||
r.trackManager.AddTrack(track, participant.Identity(), participant.ID())
|
r.trackManager.AddTrack(track, participant.Identity(), participant.ID())
|
||||||
|
|
||||||
// auto egress
|
// launch jobs
|
||||||
if r.internal != nil {
|
_, hasPublished := r.hasPublished.Swap(participant.Identity(), true)
|
||||||
if r.internal.ParticipantEgress != nil {
|
if !hasPublished {
|
||||||
if _, hasPublished := r.hasPublished.Swap(participant.Identity(), true); !hasPublished {
|
if r.agentClient != nil {
|
||||||
|
go func() {
|
||||||
|
r.agentClient.JobRequest(context.Background(), &livekit.Job{
|
||||||
|
Id: utils.NewGuid("JP_"),
|
||||||
|
Type: livekit.JobType_JT_PUBLISHER,
|
||||||
|
Room: r.protoRoom,
|
||||||
|
Participant: participant.ToProto(),
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
if r.internal != nil && r.internal.ParticipantEgress != nil {
|
||||||
|
go func() {
|
||||||
if err := StartParticipantEgress(
|
if err := StartParticipantEgress(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
r.egressLauncher,
|
r.egressLauncher,
|
||||||
@@ -913,9 +927,11 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
|
|||||||
); err != nil {
|
); err != nil {
|
||||||
r.Logger.Errorw("failed to launch participant egress", err)
|
r.Logger.Errorw("failed to launch participant egress", err)
|
||||||
}
|
}
|
||||||
}
|
}()
|
||||||
}
|
}
|
||||||
if r.internal.TrackEgress != nil {
|
}
|
||||||
|
if r.internal != nil && r.internal.TrackEgress != nil {
|
||||||
|
go func() {
|
||||||
if err := StartTrackEgress(
|
if err := StartTrackEgress(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
r.egressLauncher,
|
r.egressLauncher,
|
||||||
@@ -927,7 +943,7 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
|
|||||||
); err != nil {
|
); err != nil {
|
||||||
r.Logger.Errorw("failed to launch track egress", err)
|
r.Logger.Errorw("failed to launch track egress", err)
|
||||||
}
|
}
|
||||||
}
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -739,7 +739,7 @@ func newRoomWithParticipants(t *testing.T, opts testRoomOpts) *Room {
|
|||||||
Region: "testregion",
|
Region: "testregion",
|
||||||
},
|
},
|
||||||
telemetry.NewTelemetryService(webhook.NewDefaultNotifier("", "", nil), &telemetryfakes.FakeAnalyticsService{}),
|
telemetry.NewTelemetryService(webhook.NewDefaultNotifier("", "", nil), &telemetryfakes.FakeAnalyticsService{}),
|
||||||
nil,
|
nil, nil,
|
||||||
)
|
)
|
||||||
for i := 0; i < opts.num+opts.numHidden; i++ {
|
for i := 0; i < opts.num+opts.numHidden; i++ {
|
||||||
identity := livekit.ParticipantIdentity(fmt.Sprintf("p%d", i))
|
identity := livekit.ParticipantIdentity(fmt.Sprintf("p%d", i))
|
||||||
|
|||||||
@@ -0,0 +1,446 @@
|
|||||||
|
// Copyright 2023 LiveKit, Inc.
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
"google.golang.org/protobuf/types/known/emptypb"
|
||||||
|
|
||||||
|
"github.com/livekit/livekit-server/pkg/rtc"
|
||||||
|
"github.com/livekit/protocol/livekit"
|
||||||
|
"github.com/livekit/protocol/logger"
|
||||||
|
"github.com/livekit/protocol/rpc"
|
||||||
|
"github.com/livekit/psrpc"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AgentService struct {
|
||||||
|
upgrader websocket.Upgrader
|
||||||
|
|
||||||
|
*AgentHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
type AgentHandler struct {
|
||||||
|
agentServer rpc.AgentInternalServer
|
||||||
|
roomTopic string
|
||||||
|
participantTopic string
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
availability map[string]chan *availability
|
||||||
|
unregistered map[*websocket.Conn]*worker
|
||||||
|
roomRegistered bool
|
||||||
|
roomWorkers map[string]*worker
|
||||||
|
participantRegistered bool
|
||||||
|
participantWorkers map[string]*worker
|
||||||
|
}
|
||||||
|
|
||||||
|
type worker struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
conn *websocket.Conn
|
||||||
|
sigConn *WSSignalConnection
|
||||||
|
|
||||||
|
id string
|
||||||
|
jobType livekit.JobType
|
||||||
|
status livekit.WorkerStatus
|
||||||
|
activeJobs int
|
||||||
|
}
|
||||||
|
|
||||||
|
type availability struct {
|
||||||
|
workerID string
|
||||||
|
available bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAgentService(bus psrpc.MessageBus) (*AgentService, error) {
|
||||||
|
s := &AgentService{
|
||||||
|
upgrader: websocket.Upgrader{},
|
||||||
|
}
|
||||||
|
|
||||||
|
// allow connections from any origin, since script may be hosted anywhere
|
||||||
|
// security is enforced by access tokens
|
||||||
|
s.upgrader.CheckOrigin = func(r *http.Request) bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
agentServer, err := rpc.NewAgentInternalServer(s, bus)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
s.AgentHandler = NewAgentHandler(agentServer, "room", "participant")
|
||||||
|
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentService) ServeHTTP(writer http.ResponseWriter, r *http.Request) {
|
||||||
|
// reject non websocket requests
|
||||||
|
if !websocket.IsWebSocketUpgrade(r) {
|
||||||
|
writer.WriteHeader(404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// require a claim
|
||||||
|
claims := GetGrants(r.Context())
|
||||||
|
if claims == nil || claims.Video == nil || !claims.Video.Agent {
|
||||||
|
handleError(writer, http.StatusUnauthorized, rtc.ErrPermissionDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// upgrade
|
||||||
|
conn, err := s.upgrader.Upgrade(writer, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
handleError(writer, http.StatusInternalServerError, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.HandleConnection(conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAgentHandler(agentServer rpc.AgentInternalServer, roomTopic, participantTopic string) *AgentHandler {
|
||||||
|
return &AgentHandler{
|
||||||
|
agentServer: agentServer,
|
||||||
|
roomTopic: roomTopic,
|
||||||
|
participantTopic: participantTopic,
|
||||||
|
availability: make(map[string]chan *availability),
|
||||||
|
unregistered: make(map[*websocket.Conn]*worker),
|
||||||
|
roomWorkers: make(map[string]*worker),
|
||||||
|
participantWorkers: make(map[string]*worker),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) HandleConnection(conn *websocket.Conn) {
|
||||||
|
sigConn := NewWSSignalConnection(conn)
|
||||||
|
w := &worker{
|
||||||
|
conn: conn,
|
||||||
|
sigConn: sigConn,
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
s.unregistered[conn] = w
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
s.mu.Lock()
|
||||||
|
if w.id == "" {
|
||||||
|
delete(s.unregistered, conn)
|
||||||
|
} else {
|
||||||
|
switch w.jobType {
|
||||||
|
case livekit.JobType_JT_ROOM:
|
||||||
|
delete(s.roomWorkers, w.id)
|
||||||
|
if s.roomRegistered && !s.roomAvailableLocked() {
|
||||||
|
s.roomRegistered = false
|
||||||
|
s.agentServer.DeregisterJobRequestTopic(s.roomTopic)
|
||||||
|
}
|
||||||
|
case livekit.JobType_JT_PUBLISHER:
|
||||||
|
delete(s.participantWorkers, w.id)
|
||||||
|
if s.participantRegistered && !s.participantAvailableLocked() {
|
||||||
|
s.participantRegistered = false
|
||||||
|
s.agentServer.DeregisterJobRequestTopic(s.participantTopic)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
|
}()
|
||||||
|
|
||||||
|
// handle incoming requests from websocket
|
||||||
|
for {
|
||||||
|
req, _, err := sigConn.ReadWorkerMessage()
|
||||||
|
if err != nil {
|
||||||
|
// normal/expected closure
|
||||||
|
if err == io.EOF ||
|
||||||
|
strings.HasSuffix(err.Error(), "use of closed network connection") ||
|
||||||
|
strings.HasSuffix(err.Error(), "connection reset by peer") ||
|
||||||
|
websocket.IsCloseError(
|
||||||
|
err,
|
||||||
|
websocket.CloseAbnormalClosure,
|
||||||
|
websocket.CloseGoingAway,
|
||||||
|
websocket.CloseNormalClosure,
|
||||||
|
websocket.CloseNoStatusReceived,
|
||||||
|
) {
|
||||||
|
logger.Infow("exit ws read loop for closed connection", "wsError", err)
|
||||||
|
} else {
|
||||||
|
logger.Errorw("error reading from websocket", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch m := req.Message.(type) {
|
||||||
|
case *livekit.WorkerMessage_Register:
|
||||||
|
go s.handleRegister(w, m.Register)
|
||||||
|
case *livekit.WorkerMessage_Availability:
|
||||||
|
go s.handleAvailability(w, m.Availability)
|
||||||
|
case *livekit.WorkerMessage_JobUpdate:
|
||||||
|
go s.handleJobUpdate(w, m.JobUpdate)
|
||||||
|
case *livekit.WorkerMessage_Status:
|
||||||
|
go s.handleStatus(w, m.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) handleRegister(worker *worker, msg *livekit.RegisterWorkerRequest) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
switch msg.Type {
|
||||||
|
case livekit.JobType_JT_ROOM:
|
||||||
|
worker.id = msg.WorkerId
|
||||||
|
delete(s.unregistered, worker.conn)
|
||||||
|
s.roomWorkers[worker.id] = worker
|
||||||
|
|
||||||
|
if !s.roomRegistered {
|
||||||
|
err := s.agentServer.RegisterJobRequestTopic(s.roomTopic)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("failed to register room agents", err)
|
||||||
|
} else {
|
||||||
|
s.roomRegistered = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case livekit.JobType_JT_PUBLISHER:
|
||||||
|
worker.id = msg.WorkerId
|
||||||
|
delete(s.unregistered, worker.conn)
|
||||||
|
s.participantWorkers[worker.id] = worker
|
||||||
|
|
||||||
|
if !s.participantRegistered {
|
||||||
|
err := s.agentServer.RegisterJobRequestTopic(s.participantTopic)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("failed to register participant agents", err)
|
||||||
|
} else {
|
||||||
|
s.participantRegistered = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
worker.sigConn.WriteServerMessage(&livekit.ServerMessage{
|
||||||
|
Message: &livekit.ServerMessage_Register{
|
||||||
|
Register: &livekit.RegisterWorkerResponse{
|
||||||
|
WorkerId: worker.id,
|
||||||
|
ServerVersion: "version",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) handleAvailability(w *worker, msg *livekit.AvailabilityResponse) {
|
||||||
|
s.mu.Lock()
|
||||||
|
availabilityChan, ok := s.availability[msg.JobId]
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if ok {
|
||||||
|
availabilityChan <- &availability{
|
||||||
|
workerID: w.id,
|
||||||
|
available: msg.Available,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) handleJobUpdate(w *worker, msg *livekit.JobStatusUpdate) {
|
||||||
|
switch msg.Status {
|
||||||
|
case livekit.JobStatus_JS_SUCCESS:
|
||||||
|
logger.Debugw("job complete", "jobID", msg.JobId)
|
||||||
|
case livekit.JobStatus_JS_FAILED:
|
||||||
|
logger.Warnw("job failed", errors.New(msg.Error), "jobID", msg.JobId)
|
||||||
|
}
|
||||||
|
|
||||||
|
w.mu.Lock()
|
||||||
|
w.activeJobs--
|
||||||
|
w.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) handleStatus(w *worker, msg *livekit.UpdateWorkerStatus) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
w.mu.Lock()
|
||||||
|
w.status = msg.Status
|
||||||
|
w.mu.Unlock()
|
||||||
|
|
||||||
|
switch w.jobType {
|
||||||
|
case livekit.JobType_JT_ROOM:
|
||||||
|
if s.roomRegistered && !s.roomAvailableLocked() {
|
||||||
|
s.roomRegistered = false
|
||||||
|
s.agentServer.DeregisterJobRequestTopic(s.roomTopic)
|
||||||
|
} else if !s.roomRegistered && s.roomAvailableLocked() {
|
||||||
|
if err := s.agentServer.RegisterJobRequestTopic(s.roomTopic); err != nil {
|
||||||
|
logger.Errorw("failed to register room agents", err)
|
||||||
|
} else {
|
||||||
|
s.roomRegistered = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case livekit.JobType_JT_PUBLISHER:
|
||||||
|
if s.participantRegistered && !s.participantAvailableLocked() {
|
||||||
|
s.participantRegistered = false
|
||||||
|
s.agentServer.DeregisterJobRequestTopic(s.participantTopic)
|
||||||
|
} else if !s.participantRegistered && s.participantAvailableLocked() {
|
||||||
|
if err := s.agentServer.RegisterJobRequestTopic(s.participantTopic); err != nil {
|
||||||
|
logger.Errorw("failed to register participant agents", err)
|
||||||
|
} else {
|
||||||
|
s.participantRegistered = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) JobRequest(ctx context.Context, job *livekit.Job) (*emptypb.Empty, error) {
|
||||||
|
s.mu.Lock()
|
||||||
|
ac := make(chan *availability, 100)
|
||||||
|
s.availability[job.Id] = ac
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
s.mu.Lock()
|
||||||
|
delete(s.availability, job.Id)
|
||||||
|
s.mu.Unlock()
|
||||||
|
}()
|
||||||
|
|
||||||
|
var pool map[string]*worker
|
||||||
|
switch job.Type {
|
||||||
|
case livekit.JobType_JT_ROOM:
|
||||||
|
pool = s.roomWorkers
|
||||||
|
case livekit.JobType_JT_PUBLISHER:
|
||||||
|
pool = s.participantWorkers
|
||||||
|
}
|
||||||
|
|
||||||
|
attempted := make(map[string]bool)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, psrpc.NewErrorf(psrpc.DeadlineExceeded, "request timed out")
|
||||||
|
default:
|
||||||
|
s.mu.Lock()
|
||||||
|
var selected *worker
|
||||||
|
for _, w := range pool {
|
||||||
|
if attempted[w.id] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if w.status == livekit.WorkerStatus_WS_AVAILABLE {
|
||||||
|
if w.activeJobs > 0 {
|
||||||
|
selected = w
|
||||||
|
break
|
||||||
|
} else if selected == nil {
|
||||||
|
selected = w
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if selected == nil {
|
||||||
|
return nil, psrpc.NewErrorf(psrpc.Unavailable, "no workers available")
|
||||||
|
}
|
||||||
|
|
||||||
|
attempted[selected.id] = true
|
||||||
|
_, err := selected.sigConn.WriteServerMessage(&livekit.ServerMessage{Message: &livekit.ServerMessage_Availability{
|
||||||
|
Availability: &livekit.AvailabilityRequest{Job: job},
|
||||||
|
}})
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("failed to send availability request", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, psrpc.NewErrorf(psrpc.DeadlineExceeded, "request timed out")
|
||||||
|
case res := <-ac:
|
||||||
|
if res.available {
|
||||||
|
_, err = selected.sigConn.WriteServerMessage(&livekit.ServerMessage{Message: &livekit.ServerMessage_Assignment{
|
||||||
|
Assignment: &livekit.JobAssignment{Job: job},
|
||||||
|
}})
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("failed to assign job", err)
|
||||||
|
} else {
|
||||||
|
selected.mu.Lock()
|
||||||
|
selected.activeJobs++
|
||||||
|
selected.mu.Unlock()
|
||||||
|
return &emptypb.Empty{}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) JobRequestAffinity(ctx context.Context, job *livekit.Job) float32 {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
var pool map[string]*worker
|
||||||
|
switch job.Type {
|
||||||
|
case livekit.JobType_JT_ROOM:
|
||||||
|
pool = s.roomWorkers
|
||||||
|
case livekit.JobType_JT_PUBLISHER:
|
||||||
|
pool = s.participantWorkers
|
||||||
|
}
|
||||||
|
|
||||||
|
var affinity float32
|
||||||
|
for _, w := range pool {
|
||||||
|
if w.status == livekit.WorkerStatus_WS_AVAILABLE {
|
||||||
|
if w.activeJobs > 0 {
|
||||||
|
return 1
|
||||||
|
} else {
|
||||||
|
affinity = 0.5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return affinity
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) DrainConnections(interval time.Duration) {
|
||||||
|
// jitter drain start
|
||||||
|
time.Sleep(time.Duration(rand.Int63n(int64(interval))))
|
||||||
|
|
||||||
|
t := time.NewTicker(interval)
|
||||||
|
defer t.Stop()
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
for conn := range s.unregistered {
|
||||||
|
_ = conn.Close()
|
||||||
|
<-t.C
|
||||||
|
}
|
||||||
|
for _, w := range s.roomWorkers {
|
||||||
|
_ = w.conn.Close()
|
||||||
|
<-t.C
|
||||||
|
}
|
||||||
|
for _, w := range s.participantWorkers {
|
||||||
|
_ = w.conn.Close()
|
||||||
|
<-t.C
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) roomAvailableLocked() bool {
|
||||||
|
for _, w := range s.roomWorkers {
|
||||||
|
if w.status == livekit.WorkerStatus_WS_AVAILABLE {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AgentHandler) participantAvailableLocked() bool {
|
||||||
|
for _, w := range s.participantWorkers {
|
||||||
|
if w.status == livekit.WorkerStatus_WS_AVAILABLE {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
// Copyright 2023 LiveKit, Inc.
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"google.golang.org/protobuf/types/known/emptypb"
|
||||||
|
|
||||||
|
"github.com/livekit/livekit-server/pkg/rtc"
|
||||||
|
"github.com/livekit/protocol/livekit"
|
||||||
|
"github.com/livekit/protocol/logger"
|
||||||
|
"github.com/livekit/protocol/rpc"
|
||||||
|
"github.com/livekit/protocol/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
type agentClient struct {
|
||||||
|
s *AgentService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAgentClient(s *AgentService) rtc.AgentClient {
|
||||||
|
return &agentClient{s}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *agentClient) JobRequest(ctx context.Context, job *livekit.Job) {
|
||||||
|
_, _ = c.s.JobRequest(ctx, job)
|
||||||
|
}
|
||||||
|
|
||||||
|
type IOClient interface {
|
||||||
|
CreateEgress(ctx context.Context, info *livekit.EgressInfo) (*emptypb.Empty, error)
|
||||||
|
GetEgress(ctx context.Context, req *rpc.GetEgressRequest) (*livekit.EgressInfo, error)
|
||||||
|
ListEgress(ctx context.Context, req *livekit.ListEgressRequest) (*livekit.ListEgressResponse, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type egressLauncher struct {
|
||||||
|
client rpc.EgressClient
|
||||||
|
io IOClient
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEgressLauncher(client rpc.EgressClient, io IOClient) rtc.EgressLauncher {
|
||||||
|
if client == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &egressLauncher{
|
||||||
|
client: client,
|
||||||
|
io: io,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *egressLauncher) StartEgress(ctx context.Context, req *rpc.StartEgressRequest) (*livekit.EgressInfo, error) {
|
||||||
|
info, err := s.StartEgressWithClusterId(ctx, "", req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = s.io.CreateEgress(ctx, info)
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorw("failed to create egress", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *egressLauncher) StartEgressWithClusterId(ctx context.Context, clusterId string, req *rpc.StartEgressRequest) (*livekit.EgressInfo, error) {
|
||||||
|
if s.client == nil {
|
||||||
|
return nil, ErrEgressNotConnected
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure we have an Egress ID
|
||||||
|
if req.EgressId == "" {
|
||||||
|
req.EgressId = utils.NewGuid(utils.EgressPrefix)
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.client.StartEgress(ctx, clusterId, req)
|
||||||
|
}
|
||||||
+2
-46
@@ -25,40 +25,23 @@ import (
|
|||||||
"github.com/livekit/livekit-server/pkg/rtc"
|
"github.com/livekit/livekit-server/pkg/rtc"
|
||||||
"github.com/livekit/protocol/egress"
|
"github.com/livekit/protocol/egress"
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
"github.com/livekit/protocol/logger"
|
|
||||||
"github.com/livekit/protocol/rpc"
|
"github.com/livekit/protocol/rpc"
|
||||||
"github.com/livekit/protocol/utils"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type EgressService struct {
|
type EgressService struct {
|
||||||
|
launcher rtc.EgressLauncher
|
||||||
client rpc.EgressClient
|
client rpc.EgressClient
|
||||||
io IOClient
|
io IOClient
|
||||||
roomService livekit.RoomService
|
roomService livekit.RoomService
|
||||||
store ServiceStore
|
store ServiceStore
|
||||||
launcher rtc.EgressLauncher
|
|
||||||
}
|
|
||||||
|
|
||||||
type egressLauncher struct {
|
|
||||||
client rpc.EgressClient
|
|
||||||
io IOClient
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewEgressLauncher(client rpc.EgressClient, io IOClient) rtc.EgressLauncher {
|
|
||||||
if client == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return &egressLauncher{
|
|
||||||
client: client,
|
|
||||||
io: io,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewEgressService(
|
func NewEgressService(
|
||||||
client rpc.EgressClient,
|
client rpc.EgressClient,
|
||||||
|
launcher rtc.EgressLauncher,
|
||||||
store ServiceStore,
|
store ServiceStore,
|
||||||
io IOClient,
|
io IOClient,
|
||||||
rs livekit.RoomService,
|
rs livekit.RoomService,
|
||||||
launcher rtc.EgressLauncher,
|
|
||||||
) *EgressService {
|
) *EgressService {
|
||||||
return &EgressService{
|
return &EgressService{
|
||||||
client: client,
|
client: client,
|
||||||
@@ -189,33 +172,6 @@ func (s *EgressService) startEgress(ctx context.Context, roomName livekit.RoomNa
|
|||||||
return s.launcher.StartEgress(ctx, req)
|
return s.launcher.StartEgress(ctx, req)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *egressLauncher) StartEgress(ctx context.Context, req *rpc.StartEgressRequest) (*livekit.EgressInfo, error) {
|
|
||||||
info, err := s.StartEgressWithClusterId(ctx, "", req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.io.CreateEgress(ctx, info)
|
|
||||||
if err != nil {
|
|
||||||
logger.Errorw("failed to create egress", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return info, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *egressLauncher) StartEgressWithClusterId(ctx context.Context, clusterId string, req *rpc.StartEgressRequest) (*livekit.EgressInfo, error) {
|
|
||||||
if s.client == nil {
|
|
||||||
return nil, ErrEgressNotConnected
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure we have an Egress ID
|
|
||||||
if req.EgressId == "" {
|
|
||||||
req.EgressId = utils.NewGuid(utils.EgressPrefix)
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.client.StartEgress(ctx, clusterId, req)
|
|
||||||
}
|
|
||||||
|
|
||||||
type LayoutMetadata struct {
|
type LayoutMetadata struct {
|
||||||
Layout string `json:"layout"`
|
Layout string `json:"layout"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,10 +18,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"google.golang.org/protobuf/types/known/emptypb"
|
|
||||||
|
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
"github.com/livekit/protocol/rpc"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
|
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
|
||||||
@@ -74,13 +71,6 @@ type IngressStore interface {
|
|||||||
DeleteIngress(ctx context.Context, info *livekit.IngressInfo) error
|
DeleteIngress(ctx context.Context, info *livekit.IngressInfo) error
|
||||||
}
|
}
|
||||||
|
|
||||||
//counterfeiter:generate . IOClient
|
|
||||||
type IOClient interface {
|
|
||||||
CreateEgress(ctx context.Context, info *livekit.EgressInfo) (*emptypb.Empty, error)
|
|
||||||
GetEgress(ctx context.Context, req *rpc.GetEgressRequest) (*livekit.EgressInfo, error)
|
|
||||||
ListEgress(ctx context.Context, req *livekit.ListEgressRequest) (*livekit.ListEgressResponse, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
//counterfeiter:generate . RoomAllocator
|
//counterfeiter:generate . RoomAllocator
|
||||||
type RoomAllocator interface {
|
type RoomAllocator interface {
|
||||||
CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest) (*livekit.Room, bool, error)
|
CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest) (*livekit.Room, bool, error)
|
||||||
|
|||||||
@@ -60,8 +60,10 @@ func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.Cre
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
// find existing room and update it
|
// find existing room and update it
|
||||||
|
var created bool
|
||||||
rm, internal, err := r.roomStore.LoadRoom(ctx, livekit.RoomName(req.Name), true)
|
rm, internal, err := r.roomStore.LoadRoom(ctx, livekit.RoomName(req.Name), true)
|
||||||
if err == ErrRoomNotFound {
|
if err == ErrRoomNotFound {
|
||||||
|
created = true
|
||||||
rm = &livekit.Room{
|
rm = &livekit.Room{
|
||||||
Sid: utils.NewGuid(utils.RoomPrefix),
|
Sid: utils.NewGuid(utils.RoomPrefix),
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
@@ -114,7 +116,7 @@ func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.Cre
|
|||||||
return nil, false, routing.ErrNodeLimitReached
|
return nil, false, routing.ErrNodeLimitReached
|
||||||
}
|
}
|
||||||
|
|
||||||
return rm, false, nil
|
return rm, created, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// select a new node
|
// select a new node
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ type RoomManager struct {
|
|||||||
roomStore ObjectStore
|
roomStore ObjectStore
|
||||||
telemetry telemetry.TelemetryService
|
telemetry telemetry.TelemetryService
|
||||||
clientConfManager clientconfiguration.ClientConfigurationManager
|
clientConfManager clientconfiguration.ClientConfigurationManager
|
||||||
|
agentClient rtc.AgentClient
|
||||||
egressLauncher rtc.EgressLauncher
|
egressLauncher rtc.EgressLauncher
|
||||||
versionGenerator utils.TimedVersionGenerator
|
versionGenerator utils.TimedVersionGenerator
|
||||||
turnAuthHandler *TURNAuthHandler
|
turnAuthHandler *TURNAuthHandler
|
||||||
@@ -89,6 +90,7 @@ func NewLocalRoomManager(
|
|||||||
router routing.Router,
|
router routing.Router,
|
||||||
telemetry telemetry.TelemetryService,
|
telemetry telemetry.TelemetryService,
|
||||||
clientConfManager clientconfiguration.ClientConfigurationManager,
|
clientConfManager clientconfiguration.ClientConfigurationManager,
|
||||||
|
agentClient rtc.AgentClient,
|
||||||
egressLauncher rtc.EgressLauncher,
|
egressLauncher rtc.EgressLauncher,
|
||||||
versionGenerator utils.TimedVersionGenerator,
|
versionGenerator utils.TimedVersionGenerator,
|
||||||
turnAuthHandler *TURNAuthHandler,
|
turnAuthHandler *TURNAuthHandler,
|
||||||
@@ -108,6 +110,7 @@ func NewLocalRoomManager(
|
|||||||
telemetry: telemetry,
|
telemetry: telemetry,
|
||||||
clientConfManager: clientConfManager,
|
clientConfManager: clientConfManager,
|
||||||
egressLauncher: egressLauncher,
|
egressLauncher: egressLauncher,
|
||||||
|
agentClient: agentClient,
|
||||||
versionGenerator: versionGenerator,
|
versionGenerator: versionGenerator,
|
||||||
turnAuthHandler: turnAuthHandler,
|
turnAuthHandler: turnAuthHandler,
|
||||||
bus: bus,
|
bus: bus,
|
||||||
@@ -527,7 +530,7 @@ func (r *RoomManager) getOrCreateRoom(ctx context.Context, roomName livekit.Room
|
|||||||
}
|
}
|
||||||
|
|
||||||
// construct ice servers
|
// construct ice servers
|
||||||
newRoom := rtc.NewRoom(ri, internal, *r.rtcConfig, &r.config.Audio, r.serverInfo, r.telemetry, r.egressLauncher)
|
newRoom := rtc.NewRoom(ri, internal, *r.rtcConfig, &r.config.Audio, r.serverInfo, r.telemetry, r.agentClient, r.egressLauncher)
|
||||||
|
|
||||||
roomTopic := rpc.FormatRoomTopic(roomName)
|
roomTopic := rpc.FormatRoomTopic(roomName)
|
||||||
roomServer := utils.Must(rpc.NewTypedRoomServer(r, r.bus))
|
roomServer := utils.Must(rpc.NewTypedRoomServer(r, r.bus))
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import (
|
|||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
"github.com/livekit/protocol/logger"
|
"github.com/livekit/protocol/logger"
|
||||||
"github.com/livekit/protocol/rpc"
|
"github.com/livekit/protocol/rpc"
|
||||||
|
"github.com/livekit/protocol/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A rooms service that supports a single node
|
// A rooms service that supports a single node
|
||||||
@@ -41,6 +42,7 @@ type RoomService struct {
|
|||||||
router routing.MessageRouter
|
router routing.MessageRouter
|
||||||
roomAllocator RoomAllocator
|
roomAllocator RoomAllocator
|
||||||
roomStore ServiceStore
|
roomStore ServiceStore
|
||||||
|
agentClient rtc.AgentClient
|
||||||
egressLauncher rtc.EgressLauncher
|
egressLauncher rtc.EgressLauncher
|
||||||
topicFormatter rpc.TopicFormatter
|
topicFormatter rpc.TopicFormatter
|
||||||
roomClient rpc.TypedRoomClient
|
roomClient rpc.TypedRoomClient
|
||||||
@@ -54,6 +56,7 @@ func NewRoomService(
|
|||||||
router routing.MessageRouter,
|
router routing.MessageRouter,
|
||||||
roomAllocator RoomAllocator,
|
roomAllocator RoomAllocator,
|
||||||
serviceStore ServiceStore,
|
serviceStore ServiceStore,
|
||||||
|
agentClient rtc.AgentClient,
|
||||||
egressLauncher rtc.EgressLauncher,
|
egressLauncher rtc.EgressLauncher,
|
||||||
topicFormatter rpc.TopicFormatter,
|
topicFormatter rpc.TopicFormatter,
|
||||||
roomClient rpc.TypedRoomClient,
|
roomClient rpc.TypedRoomClient,
|
||||||
@@ -66,6 +69,7 @@ func NewRoomService(
|
|||||||
router: router,
|
router: router,
|
||||||
roomAllocator: roomAllocator,
|
roomAllocator: roomAllocator,
|
||||||
roomStore: serviceStore,
|
roomStore: serviceStore,
|
||||||
|
agentClient: agentClient,
|
||||||
egressLauncher: egressLauncher,
|
egressLauncher: egressLauncher,
|
||||||
topicFormatter: topicFormatter,
|
topicFormatter: topicFormatter,
|
||||||
roomClient: roomClient,
|
roomClient: roomClient,
|
||||||
@@ -112,14 +116,23 @@ func (s *RoomService) CreateRoom(ctx context.Context, req *livekit.CreateRoomReq
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if created && req.Egress != nil && req.Egress.Room != nil {
|
if created {
|
||||||
egress := &rpc.StartEgressRequest{
|
if s.agentClient != nil {
|
||||||
Request: &rpc.StartEgressRequest_RoomComposite{
|
s.agentClient.JobRequest(ctx, &livekit.Job{
|
||||||
RoomComposite: req.Egress.Room,
|
Id: utils.NewGuid("JR_"),
|
||||||
},
|
Type: livekit.JobType_JT_ROOM,
|
||||||
RoomId: rm.Sid,
|
Room: rm,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if req.Egress != nil && req.Egress.Room != nil {
|
||||||
|
egress := &rpc.StartEgressRequest{
|
||||||
|
Request: &rpc.StartEgressRequest_RoomComposite{
|
||||||
|
RoomComposite: req.Egress.Room,
|
||||||
|
},
|
||||||
|
RoomId: rm.Sid,
|
||||||
|
}
|
||||||
|
_, err = s.egressLauncher.StartEgress(ctx, egress)
|
||||||
}
|
}
|
||||||
_, err = s.egressLauncher.StartEgress(ctx, egress)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return rm, err
|
return rm, err
|
||||||
@@ -427,7 +440,7 @@ func (s *RoomService) UpdateRoomMetadata(ctx context.Context, req *livekit.Updat
|
|||||||
|
|
||||||
// no one has joined the room, would not have been created on an RTC node.
|
// no one has joined the room, would not have been created on an RTC node.
|
||||||
// in this case, we'd want to run create again
|
// in this case, we'd want to run create again
|
||||||
_, _, err = s.roomAllocator.CreateRoom(ctx, &livekit.CreateRoomRequest{
|
room, created, err := s.roomAllocator.CreateRoom(ctx, &livekit.CreateRoomRequest{
|
||||||
Name: req.Room,
|
Name: req.Room,
|
||||||
Metadata: req.Metadata,
|
Metadata: req.Metadata,
|
||||||
})
|
})
|
||||||
@@ -465,6 +478,14 @@ func (s *RoomService) UpdateRoomMetadata(ctx context.Context, req *livekit.Updat
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if created && s.agentClient != nil {
|
||||||
|
s.agentClient.JobRequest(ctx, &livekit.Job{
|
||||||
|
Id: utils.NewGuid("JR_"),
|
||||||
|
Type: livekit.JobType_JT_ROOM,
|
||||||
|
Room: room,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return room, nil
|
return room, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -136,6 +136,7 @@ func newTestRoomService(conf config.RoomConfig) *TestRoomService {
|
|||||||
allocator,
|
allocator,
|
||||||
store,
|
store,
|
||||||
nil,
|
nil,
|
||||||
|
nil,
|
||||||
rpc.NewTopicFormatter(),
|
rpc.NewTopicFormatter(),
|
||||||
&rpcfakes.FakeTypedRoomClient{},
|
&rpcfakes.FakeTypedRoomClient{},
|
||||||
&rpcfakes.FakeTypedParticipantClient{},
|
&rpcfakes.FakeTypedParticipantClient{},
|
||||||
|
|||||||
@@ -31,17 +31,17 @@ import (
|
|||||||
"github.com/ua-parser/uap-go/uaparser"
|
"github.com/ua-parser/uap-go/uaparser"
|
||||||
"golang.org/x/exp/maps"
|
"golang.org/x/exp/maps"
|
||||||
|
|
||||||
"github.com/livekit/livekit-server/pkg/utils"
|
|
||||||
"github.com/livekit/protocol/livekit"
|
|
||||||
"github.com/livekit/protocol/logger"
|
|
||||||
"github.com/livekit/psrpc"
|
|
||||||
|
|
||||||
"github.com/livekit/livekit-server/pkg/config"
|
"github.com/livekit/livekit-server/pkg/config"
|
||||||
"github.com/livekit/livekit-server/pkg/routing"
|
"github.com/livekit/livekit-server/pkg/routing"
|
||||||
"github.com/livekit/livekit-server/pkg/routing/selector"
|
"github.com/livekit/livekit-server/pkg/routing/selector"
|
||||||
"github.com/livekit/livekit-server/pkg/rtc"
|
"github.com/livekit/livekit-server/pkg/rtc"
|
||||||
"github.com/livekit/livekit-server/pkg/telemetry"
|
"github.com/livekit/livekit-server/pkg/telemetry"
|
||||||
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
|
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
|
||||||
|
"github.com/livekit/livekit-server/pkg/utils"
|
||||||
|
"github.com/livekit/protocol/livekit"
|
||||||
|
"github.com/livekit/protocol/logger"
|
||||||
|
putil "github.com/livekit/protocol/utils"
|
||||||
|
"github.com/livekit/psrpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
type RTCService struct {
|
type RTCService struct {
|
||||||
@@ -54,6 +54,7 @@ type RTCService struct {
|
|||||||
isDev bool
|
isDev bool
|
||||||
limits config.LimitConfig
|
limits config.LimitConfig
|
||||||
parser *uaparser.Parser
|
parser *uaparser.Parser
|
||||||
|
agentClient rtc.AgentClient
|
||||||
telemetry telemetry.TelemetryService
|
telemetry telemetry.TelemetryService
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
@@ -66,6 +67,7 @@ func NewRTCService(
|
|||||||
store ServiceStore,
|
store ServiceStore,
|
||||||
router routing.MessageRouter,
|
router routing.MessageRouter,
|
||||||
currentNode routing.LocalNode,
|
currentNode routing.LocalNode,
|
||||||
|
agentClient rtc.AgentClient,
|
||||||
telemetry telemetry.TelemetryService,
|
telemetry telemetry.TelemetryService,
|
||||||
) *RTCService {
|
) *RTCService {
|
||||||
s := &RTCService{
|
s := &RTCService{
|
||||||
@@ -78,6 +80,7 @@ func NewRTCService(
|
|||||||
isDev: conf.Development,
|
isDev: conf.Development,
|
||||||
limits: conf.Limit,
|
limits: conf.Limit,
|
||||||
parser: uaparser.NewFromSaved(),
|
parser: uaparser.NewFromSaved(),
|
||||||
|
agentClient: agentClient,
|
||||||
telemetry: telemetry,
|
telemetry: telemetry,
|
||||||
connections: map[*websocket.Conn]struct{}{},
|
connections: map[*websocket.Conn]struct{}{},
|
||||||
}
|
}
|
||||||
@@ -229,6 +232,7 @@ func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
logger.Warnw("failed to start connection, retrying", err, fieldsWithAttempt...)
|
logger.Warnw("failed to start connection, retrying", err, fieldsWithAttempt...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
prometheus.IncrementParticipantJoinFail(1)
|
prometheus.IncrementParticipantJoinFail(1)
|
||||||
handleError(w, http.StatusInternalServerError, err, loggerFields...)
|
handleError(w, http.StatusInternalServerError, err, loggerFields...)
|
||||||
@@ -514,10 +518,16 @@ type connectionResult struct {
|
|||||||
ResponseSource routing.MessageSource
|
ResponseSource routing.MessageSource
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *RTCService) startConnection(ctx context.Context, roomName livekit.RoomName, pi routing.ParticipantInit, timeout time.Duration) (connectionResult, *livekit.SignalResponse, error) {
|
func (s *RTCService) startConnection(
|
||||||
|
ctx context.Context,
|
||||||
|
roomName livekit.RoomName,
|
||||||
|
pi routing.ParticipantInit,
|
||||||
|
timeout time.Duration,
|
||||||
|
) (connectionResult, *livekit.SignalResponse, error) {
|
||||||
var cr connectionResult
|
var cr connectionResult
|
||||||
|
var created bool
|
||||||
var err error
|
var err error
|
||||||
cr.Room, _, err = s.roomAllocator.CreateRoom(ctx, &livekit.CreateRoomRequest{Name: string(roomName)})
|
cr.Room, created, err = s.roomAllocator.CreateRoom(ctx, &livekit.CreateRoomRequest{Name: string(roomName)})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cr, nil, err
|
return cr, nil, err
|
||||||
}
|
}
|
||||||
@@ -538,6 +548,17 @@ func (s *RTCService) startConnection(ctx context.Context, roomName livekit.RoomN
|
|||||||
cr.ResponseSource.Close()
|
cr.ResponseSource.Close()
|
||||||
return cr, nil, err
|
return cr, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if created && s.agentClient != nil {
|
||||||
|
go func() {
|
||||||
|
s.agentClient.JobRequest(ctx, &livekit.Job{
|
||||||
|
Id: putil.NewGuid("JR_"),
|
||||||
|
Type: livekit.JobType_JT_ROOM,
|
||||||
|
Room: cr.Room,
|
||||||
|
})
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
return cr, initialResponse, nil
|
return cr, initialResponse, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -559,5 +580,4 @@ func readInitialResponse(source routing.MessageSource, timeout time.Duration) (*
|
|||||||
return res, nil
|
return res, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ type LivekitServer struct {
|
|||||||
config *config.Config
|
config *config.Config
|
||||||
ioService *IOInfoService
|
ioService *IOInfoService
|
||||||
rtcService *RTCService
|
rtcService *RTCService
|
||||||
|
agentService *AgentService
|
||||||
httpServer *http.Server
|
httpServer *http.Server
|
||||||
promServer *http.Server
|
promServer *http.Server
|
||||||
router routing.Router
|
router routing.Router
|
||||||
@@ -66,6 +67,7 @@ func NewLivekitServer(conf *config.Config,
|
|||||||
ingressService *IngressService,
|
ingressService *IngressService,
|
||||||
ioService *IOInfoService,
|
ioService *IOInfoService,
|
||||||
rtcService *RTCService,
|
rtcService *RTCService,
|
||||||
|
agentService *AgentService,
|
||||||
keyProvider auth.KeyProvider,
|
keyProvider auth.KeyProvider,
|
||||||
router routing.Router,
|
router routing.Router,
|
||||||
roomManager *RoomManager,
|
roomManager *RoomManager,
|
||||||
@@ -77,6 +79,7 @@ func NewLivekitServer(conf *config.Config,
|
|||||||
config: conf,
|
config: conf,
|
||||||
ioService: ioService,
|
ioService: ioService,
|
||||||
rtcService: rtcService,
|
rtcService: rtcService,
|
||||||
|
agentService: agentService,
|
||||||
router: router,
|
router: router,
|
||||||
roomManager: roomManager,
|
roomManager: roomManager,
|
||||||
signalServer: signalServer,
|
signalServer: signalServer,
|
||||||
@@ -125,6 +128,7 @@ func NewLivekitServer(conf *config.Config,
|
|||||||
mux.Handle(egressServer.PathPrefix(), egressServer)
|
mux.Handle(egressServer.PathPrefix(), egressServer)
|
||||||
mux.Handle(ingressServer.PathPrefix(), ingressServer)
|
mux.Handle(ingressServer.PathPrefix(), ingressServer)
|
||||||
mux.Handle("/rtc", rtcService)
|
mux.Handle("/rtc", rtcService)
|
||||||
|
mux.Handle("/agent", agentService)
|
||||||
mux.HandleFunc("/rtc/validate", rtcService.Validate)
|
mux.HandleFunc("/rtc/validate", rtcService.Validate)
|
||||||
mux.HandleFunc("/", s.defaultHandler)
|
mux.HandleFunc("/", s.defaultHandler)
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -62,16 +62,18 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
|||||||
NewIOInfoService,
|
NewIOInfoService,
|
||||||
wire.Bind(new(IOClient), new(*IOInfoService)),
|
wire.Bind(new(IOClient), new(*IOInfoService)),
|
||||||
rpc.NewEgressClient,
|
rpc.NewEgressClient,
|
||||||
|
rpc.NewIngressClient,
|
||||||
getEgressStore,
|
getEgressStore,
|
||||||
NewEgressLauncher,
|
NewEgressLauncher,
|
||||||
NewEgressService,
|
NewEgressService,
|
||||||
rpc.NewIngressClient,
|
|
||||||
getIngressStore,
|
getIngressStore,
|
||||||
getIngressConfig,
|
getIngressConfig,
|
||||||
NewIngressService,
|
NewIngressService,
|
||||||
NewRoomAllocator,
|
NewRoomAllocator,
|
||||||
NewRoomService,
|
NewRoomService,
|
||||||
NewRTCService,
|
NewRTCService,
|
||||||
|
NewAgentService,
|
||||||
|
NewAgentClient,
|
||||||
getSignalRelayConfig,
|
getSignalRelayConfig,
|
||||||
NewDefaultSignalServer,
|
NewDefaultSignalServer,
|
||||||
routing.NewSignalClient,
|
routing.NewSignalClient,
|
||||||
|
|||||||
+10
-5
@@ -55,6 +55,11 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
agentService, err := NewAgentService(messageBus)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rtcAgentClient := NewAgentClient(agentService)
|
||||||
egressClient, err := rpc.NewEgressClient(messageBus)
|
egressClient, err := rpc.NewEgressClient(messageBus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -86,22 +91,22 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
roomService, err := NewRoomService(roomConfig, apiConfig, psrpcConfig, router, roomAllocator, objectStore, rtcEgressLauncher, topicFormatter, roomClient, participantClient)
|
roomService, err := NewRoomService(roomConfig, apiConfig, psrpcConfig, router, roomAllocator, objectStore, rtcAgentClient, rtcEgressLauncher, topicFormatter, roomClient, participantClient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
egressService := NewEgressService(egressClient, objectStore, ioInfoService, roomService, rtcEgressLauncher)
|
egressService := NewEgressService(egressClient, rtcEgressLauncher, objectStore, ioInfoService, roomService)
|
||||||
ingressConfig := getIngressConfig(conf)
|
ingressConfig := getIngressConfig(conf)
|
||||||
ingressClient, err := rpc.NewIngressClient(messageBus)
|
ingressClient, err := rpc.NewIngressClient(messageBus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
ingressService := NewIngressService(ingressConfig, nodeID, messageBus, ingressClient, ingressStore, roomService, telemetryService)
|
ingressService := NewIngressService(ingressConfig, nodeID, messageBus, ingressClient, ingressStore, roomService, telemetryService)
|
||||||
rtcService := NewRTCService(conf, roomAllocator, objectStore, router, currentNode, telemetryService)
|
rtcService := NewRTCService(conf, roomAllocator, objectStore, router, currentNode, rtcAgentClient, telemetryService)
|
||||||
clientConfigurationManager := createClientConfiguration()
|
clientConfigurationManager := createClientConfiguration()
|
||||||
timedVersionGenerator := utils.NewDefaultTimedVersionGenerator()
|
timedVersionGenerator := utils.NewDefaultTimedVersionGenerator()
|
||||||
turnAuthHandler := NewTURNAuthHandler(keyProvider)
|
turnAuthHandler := NewTURNAuthHandler(keyProvider)
|
||||||
roomManager, err := NewLocalRoomManager(conf, objectStore, currentNode, router, telemetryService, clientConfigurationManager, rtcEgressLauncher, timedVersionGenerator, turnAuthHandler, messageBus)
|
roomManager, err := NewLocalRoomManager(conf, objectStore, currentNode, router, telemetryService, clientConfigurationManager, rtcAgentClient, rtcEgressLauncher, timedVersionGenerator, turnAuthHandler, messageBus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -114,7 +119,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
livekitServer, err := NewLivekitServer(conf, roomService, egressService, ingressService, ioInfoService, rtcService, keyProvider, router, roomManager, signalServer, server, currentNode)
|
livekitServer, err := NewLivekitServer(conf, roomService, egressService, ingressService, ioInfoService, rtcService, agentService, keyProvider, router, roomManager, signalServer, server, currentNode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,6 +83,40 @@ func (c *WSSignalConnection) ReadRequest() (*livekit.SignalRequest, int, error)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *WSSignalConnection) ReadWorkerMessage() (*livekit.WorkerMessage, int, error) {
|
||||||
|
for {
|
||||||
|
// handle special messages and pass on the rest
|
||||||
|
messageType, payload, err := c.conn.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := &livekit.WorkerMessage{}
|
||||||
|
switch messageType {
|
||||||
|
case websocket.BinaryMessage:
|
||||||
|
if c.useJSON {
|
||||||
|
c.mu.Lock()
|
||||||
|
// switch to protobuf if client supports it
|
||||||
|
c.useJSON = false
|
||||||
|
c.mu.Unlock()
|
||||||
|
}
|
||||||
|
// protobuf encoded
|
||||||
|
err := proto.Unmarshal(payload, msg)
|
||||||
|
return msg, len(payload), err
|
||||||
|
case websocket.TextMessage:
|
||||||
|
c.mu.Lock()
|
||||||
|
// json encoded, also write back JSON
|
||||||
|
c.useJSON = true
|
||||||
|
c.mu.Unlock()
|
||||||
|
err := protojson.Unmarshal(payload, msg)
|
||||||
|
return msg, len(payload), err
|
||||||
|
default:
|
||||||
|
logger.Debugw("unsupported message", "message", messageType)
|
||||||
|
return nil, len(payload), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (c *WSSignalConnection) WriteResponse(msg *livekit.SignalResponse) (int, error) {
|
func (c *WSSignalConnection) WriteResponse(msg *livekit.SignalResponse) (int, error) {
|
||||||
var msgType int
|
var msgType int
|
||||||
var payload []byte
|
var payload []byte
|
||||||
@@ -105,6 +139,28 @@ func (c *WSSignalConnection) WriteResponse(msg *livekit.SignalResponse) (int, er
|
|||||||
return len(payload), c.conn.WriteMessage(msgType, payload)
|
return len(payload), c.conn.WriteMessage(msgType, payload)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *WSSignalConnection) WriteServerMessage(msg *livekit.ServerMessage) (int, error) {
|
||||||
|
var msgType int
|
||||||
|
var payload []byte
|
||||||
|
var err error
|
||||||
|
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
if c.useJSON {
|
||||||
|
msgType = websocket.TextMessage
|
||||||
|
payload, err = protojson.Marshal(msg)
|
||||||
|
} else {
|
||||||
|
msgType = websocket.BinaryMessage
|
||||||
|
payload, err = proto.Marshal(msg)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return len(payload), c.conn.WriteMessage(msgType, payload)
|
||||||
|
}
|
||||||
|
|
||||||
func (c *WSSignalConnection) pingWorker() {
|
func (c *WSSignalConnection) pingWorker() {
|
||||||
for {
|
for {
|
||||||
<-time.After(pingFrequency)
|
<-time.After(pingFrequency)
|
||||||
|
|||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
"google.golang.org/protobuf/proto"
|
||||||
|
|
||||||
|
"github.com/livekit/protocol/livekit"
|
||||||
|
"github.com/livekit/protocol/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
type agentClient struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
conn *websocket.Conn
|
||||||
|
|
||||||
|
registered atomic.Int32
|
||||||
|
roomAvailability atomic.Int32
|
||||||
|
roomJobs atomic.Int32
|
||||||
|
participantAvailability atomic.Int32
|
||||||
|
participantJobs atomic.Int32
|
||||||
|
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAgentClient(token string) (*agentClient, error) {
|
||||||
|
host := fmt.Sprintf("ws://localhost:%d", defaultServerPort)
|
||||||
|
u, err := url.Parse(host + "/agent")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
requestHeader := make(http.Header)
|
||||||
|
requestHeader.Set("Authorization", "Bearer "+token)
|
||||||
|
|
||||||
|
connectUrl := u.String()
|
||||||
|
conn, _, err := websocket.DefaultDialer.Dial(connectUrl, requestHeader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &agentClient{
|
||||||
|
conn: conn,
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *agentClient) Run() error {
|
||||||
|
go c.read()
|
||||||
|
|
||||||
|
workerID := utils.NewGuid("W_")
|
||||||
|
|
||||||
|
if err := c.write(&livekit.WorkerMessage{
|
||||||
|
Message: &livekit.WorkerMessage_Register{
|
||||||
|
Register: &livekit.RegisterWorkerRequest{
|
||||||
|
Type: livekit.JobType_JT_ROOM,
|
||||||
|
WorkerId: workerID,
|
||||||
|
Version: "version",
|
||||||
|
Name: "name",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.write(&livekit.WorkerMessage{
|
||||||
|
Message: &livekit.WorkerMessage_Register{
|
||||||
|
Register: &livekit.RegisterWorkerRequest{
|
||||||
|
Type: livekit.JobType_JT_PUBLISHER,
|
||||||
|
WorkerId: workerID,
|
||||||
|
Version: "version",
|
||||||
|
Name: "name",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *agentClient) read() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-c.done:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
_, b, err := c.conn.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := &livekit.ServerMessage{}
|
||||||
|
if err = proto.Unmarshal(b, msg); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch m := msg.Message.(type) {
|
||||||
|
case *livekit.ServerMessage_Assignment:
|
||||||
|
go c.handleAssignment(m.Assignment)
|
||||||
|
case *livekit.ServerMessage_Availability:
|
||||||
|
go c.handleAvailability(m.Availability)
|
||||||
|
case *livekit.ServerMessage_Register:
|
||||||
|
go c.handleRegister(m.Register)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *agentClient) handleAssignment(req *livekit.JobAssignment) {
|
||||||
|
if req.Job.Type == livekit.JobType_JT_ROOM {
|
||||||
|
c.roomJobs.Inc()
|
||||||
|
} else {
|
||||||
|
c.participantJobs.Inc()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *agentClient) handleAvailability(req *livekit.AvailabilityRequest) {
|
||||||
|
if req.Job.Type == livekit.JobType_JT_ROOM {
|
||||||
|
c.roomAvailability.Inc()
|
||||||
|
} else {
|
||||||
|
c.participantAvailability.Inc()
|
||||||
|
}
|
||||||
|
|
||||||
|
c.write(&livekit.WorkerMessage{
|
||||||
|
Message: &livekit.WorkerMessage_Availability{
|
||||||
|
Availability: &livekit.AvailabilityResponse{
|
||||||
|
JobId: req.Job.Id,
|
||||||
|
Available: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *agentClient) handleRegister(req *livekit.RegisterWorkerResponse) {
|
||||||
|
c.registered.Inc()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *agentClient) write(msg *livekit.WorkerMessage) error {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
b, err := proto.Marshal(msg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.conn.WriteMessage(websocket.BinaryMessage, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *agentClient) close() {
|
||||||
|
close(c.done)
|
||||||
|
_ = c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
||||||
|
_ = c.conn.Close()
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"github.com/livekit/protocol/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAgents(t *testing.T) {
|
||||||
|
_, finish := setupSingleNodeTest("TestAgents")
|
||||||
|
defer finish()
|
||||||
|
|
||||||
|
ac1, err := newAgentClient(agentToken())
|
||||||
|
require.NoError(t, err)
|
||||||
|
ac2, err := newAgentClient(agentToken())
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer ac1.close()
|
||||||
|
defer ac2.close()
|
||||||
|
ac1.Run()
|
||||||
|
ac2.Run()
|
||||||
|
|
||||||
|
time.Sleep(time.Second * 3)
|
||||||
|
|
||||||
|
require.Equal(t, int32(2), ac1.registered.Load())
|
||||||
|
require.Equal(t, int32(2), ac2.registered.Load())
|
||||||
|
|
||||||
|
c1 := createRTCClient("c1", defaultServerPort, nil)
|
||||||
|
c2 := createRTCClient("c2", defaultServerPort, nil)
|
||||||
|
waitUntilConnected(t, c1, c2)
|
||||||
|
|
||||||
|
// publish 2 tracks
|
||||||
|
t1, err := c1.AddStaticTrack("audio/opus", "audio", "webcam")
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer t1.Stop()
|
||||||
|
t2, err := c1.AddStaticTrack("video/vp8", "video", "webcam")
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer t2.Stop()
|
||||||
|
|
||||||
|
time.Sleep(time.Second * 3)
|
||||||
|
|
||||||
|
require.Equal(t, int32(1), ac1.roomJobs.Load()+ac2.roomJobs.Load())
|
||||||
|
require.Equal(t, int32(1), ac1.participantJobs.Load()+ac2.participantJobs.Load())
|
||||||
|
|
||||||
|
// publish 2 tracks
|
||||||
|
t3, err := c2.AddStaticTrack("audio/opus", "audio", "webcam")
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer t3.Stop()
|
||||||
|
t4, err := c2.AddStaticTrack("video/vp8", "video", "webcam")
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer t4.Stop()
|
||||||
|
|
||||||
|
time.Sleep(time.Second * 3)
|
||||||
|
|
||||||
|
require.Equal(t, int32(1), ac1.roomJobs.Load()+ac2.roomJobs.Load())
|
||||||
|
require.Equal(t, int32(2), ac1.participantJobs.Load()+ac2.participantJobs.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func agentToken() string {
|
||||||
|
at := auth.NewAccessToken(testApiKey, testApiSecret).
|
||||||
|
AddGrant(&auth.VideoGrant{Agent: true})
|
||||||
|
t, err := at.ToJWT()
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user