agent service: new protocol & namespaces (#2545)
* initial worker impl * fix test * fix build * TestAgentNamespaces * log err * nit cmt * TestAgentMultiNode * Update pkg/agent/worker.go Co-authored-by: David Zhao <dz@livekit.io> * retry on worker selection & fix review comments * Update roommanager.go * license * use testutils.WIthTimeout * abstract namespace/enabled logic into agent.Client, incrementally dispatch * typos and dates * lock * timeout is now optional * pass in topics instead of fixed * handler handles connections * onIdle, numConnections * fix WithGrants * update protocol * check agent client * broadcast after unlock * fix data race * remove ReadChan, fix dispatcher --------- Co-authored-by: David Zhao <dz@livekit.io> Co-authored-by: David Colburn <xero73@gmail.com>
This commit is contained in:
co-authored by
David Zhao
David Colburn
parent
63b1fba082
commit
dc67f505a5
@@ -19,7 +19,7 @@ require (
|
||||
github.com/jxskiss/base62 v1.1.0
|
||||
github.com/livekit/mageutil v0.0.0-20230125210925-54e8a70427c1
|
||||
github.com/livekit/mediatransportutil v0.0.0-20240302142739-1c3dd691a1b8
|
||||
github.com/livekit/protocol v1.12.1-0.20240403063258-fc68e8d82b26
|
||||
github.com/livekit/protocol v1.12.1-0.20240403204952-bc6c7ffd71f0
|
||||
github.com/livekit/psrpc v0.5.3-0.20240327035954-cec3a0e614be
|
||||
github.com/mackerelio/go-osstat v0.2.4
|
||||
github.com/magefile/mage v1.15.0
|
||||
|
||||
@@ -132,8 +132,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/mediatransportutil v0.0.0-20240302142739-1c3dd691a1b8 h1:xawydPEACNO5Ncs2LgioTjWghXQ0eUN1q1RnVUUyVnI=
|
||||
github.com/livekit/mediatransportutil v0.0.0-20240302142739-1c3dd691a1b8/go.mod h1:jwKUCmObuiEDH0iiuJHaGMXwRs3RjrB4G6qqgkr/5oE=
|
||||
github.com/livekit/protocol v1.12.1-0.20240403063258-fc68e8d82b26 h1:8Oog+IH4NVbq7PEXYU7bIW8Kw4rqd0HgtWaOh++9ZcE=
|
||||
github.com/livekit/protocol v1.12.1-0.20240403063258-fc68e8d82b26/go.mod h1:mcv7L2DWB6iRckI++egmwFU7YEy3W+aLHnusNhioqi0=
|
||||
github.com/livekit/protocol v1.12.1-0.20240403204952-bc6c7ffd71f0 h1:BfQN4k6YG+XTdfbXnA2XZLAXinRNlJrGdTLAjyOW2Rg=
|
||||
github.com/livekit/protocol v1.12.1-0.20240403204952-bc6c7ffd71f0/go.mod h1:mcv7L2DWB6iRckI++egmwFU7YEy3W+aLHnusNhioqi0=
|
||||
github.com/livekit/psrpc v0.5.3-0.20240327035954-cec3a0e614be h1:W1nCFZ19rYAORMBNX82NeVPHjADN0UyORr6refbUXpU=
|
||||
github.com/livekit/psrpc v0.5.3-0.20240327035954-cec3a0e614be/go.mod h1:CQUBSPfYYAaevg1TNCc6/aYsa8DJH4jSRFdCeSZk5u0=
|
||||
github.com/mackerelio/go-osstat v0.2.4 h1:qxGbdPkFo65PXOb/F/nhDKpF2nGmGaCFDLXoZjJTtUs=
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// Copyright 2024 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 agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gammazero/workerpool"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
|
||||
serverutils "github.com/livekit/livekit-server/pkg/utils"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/livekit/protocol/rpc"
|
||||
"github.com/livekit/protocol/utils"
|
||||
"github.com/livekit/psrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
EnabledCacheTTL = 1 * time.Minute
|
||||
RoomAgentTopic = "room"
|
||||
PublisherAgentTopic = "publisher"
|
||||
DefaultHandlerNamespace = ""
|
||||
|
||||
CheckEnabledTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
type Client interface {
|
||||
// LaunchJob starts a room or participant job on an agent.
|
||||
// it will launch a job once for each worker in each namespace
|
||||
LaunchJob(ctx context.Context, desc *JobDescription)
|
||||
Stop() error
|
||||
}
|
||||
|
||||
type JobDescription struct {
|
||||
JobType livekit.JobType
|
||||
Room *livekit.Room
|
||||
// only set for participant jobs
|
||||
Participant *livekit.ParticipantInfo
|
||||
}
|
||||
|
||||
type agentClient struct {
|
||||
client rpc.AgentInternalClient
|
||||
|
||||
mu sync.RWMutex
|
||||
|
||||
// cache response to avoid constantly checking with controllers
|
||||
// cache is invalidated with AgentRegistered updates
|
||||
roomNamespaces *serverutils.IncrementalDispatcher[string]
|
||||
publisherNamespaces *serverutils.IncrementalDispatcher[string]
|
||||
enabledExpiresAt time.Time
|
||||
|
||||
workers *workerpool.WorkerPool
|
||||
|
||||
invalidateSub psrpc.Subscription[*emptypb.Empty]
|
||||
subDone chan struct{}
|
||||
}
|
||||
|
||||
func NewAgentClient(bus psrpc.MessageBus) (Client, error) {
|
||||
client, err := rpc.NewAgentInternalClient(bus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c := &agentClient{
|
||||
client: client,
|
||||
workers: workerpool.New(50),
|
||||
subDone: make(chan struct{}),
|
||||
}
|
||||
|
||||
sub, err := c.client.SubscribeWorkerRegistered(context.Background(), DefaultHandlerNamespace)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.invalidateSub = sub
|
||||
|
||||
go func() {
|
||||
// invalidate cache
|
||||
for range sub.Channel() {
|
||||
c.mu.Lock()
|
||||
c.roomNamespaces = nil
|
||||
c.publisherNamespaces = nil
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
c.subDone <- struct{}{}
|
||||
}()
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *agentClient) LaunchJob(ctx context.Context, desc *JobDescription) {
|
||||
roomNamespaces, publisherNamespaces, needsRefresh := c.getOrCreateDispatchers()
|
||||
|
||||
if needsRefresh {
|
||||
go c.checkEnabled(ctx, roomNamespaces, publisherNamespaces)
|
||||
}
|
||||
|
||||
target := roomNamespaces
|
||||
jobTypeTopic := RoomAgentTopic
|
||||
if desc.JobType == livekit.JobType_JT_PUBLISHER {
|
||||
target = publisherNamespaces
|
||||
jobTypeTopic = PublisherAgentTopic
|
||||
}
|
||||
|
||||
target.ForEach(func(ns string) {
|
||||
c.workers.Submit(func() {
|
||||
_, err := c.client.JobRequest(ctx, ns, jobTypeTopic, &livekit.Job{
|
||||
Id: utils.NewGuid(utils.AgentJobPrefix),
|
||||
Type: desc.JobType,
|
||||
Room: desc.Room,
|
||||
Participant: desc.Participant,
|
||||
Namespace: ns,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Errorw("failed to send job request", err, "namespace", ns, "jobType", jobTypeTopic)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func (c *agentClient) getOrCreateDispatchers() (*serverutils.IncrementalDispatcher[string], *serverutils.IncrementalDispatcher[string], bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if time.Since(c.enabledExpiresAt) > EnabledCacheTTL || c.roomNamespaces == nil || c.publisherNamespaces == nil {
|
||||
c.roomNamespaces = serverutils.NewIncrementalDispatcher[string]()
|
||||
c.publisherNamespaces = serverutils.NewIncrementalDispatcher[string]()
|
||||
return c.roomNamespaces, c.publisherNamespaces, true
|
||||
}
|
||||
return c.roomNamespaces, c.publisherNamespaces, false
|
||||
}
|
||||
|
||||
func (c *agentClient) checkEnabled(ctx context.Context, roomNamespaces, publisherNamespaces *serverutils.IncrementalDispatcher[string]) {
|
||||
defer roomNamespaces.Done()
|
||||
defer publisherNamespaces.Done()
|
||||
resChan, err := c.client.CheckEnabled(ctx, &rpc.CheckEnabledRequest{}, psrpc.WithRequestTimeout(CheckEnabledTimeout))
|
||||
if err != nil {
|
||||
logger.Errorw("failed to check enabled", err)
|
||||
return
|
||||
}
|
||||
|
||||
roomNSMap := make(map[string]bool)
|
||||
publisherNSMap := make(map[string]bool)
|
||||
|
||||
for r := range resChan {
|
||||
if r.Result.GetRoomEnabled() {
|
||||
for _, ns := range r.Result.GetNamespaces() {
|
||||
if _, ok := roomNSMap[ns]; !ok {
|
||||
roomNamespaces.Add(ns)
|
||||
roomNSMap[ns] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if r.Result.GetPublisherEnabled() {
|
||||
for _, ns := range r.Result.GetNamespaces() {
|
||||
if _, ok := publisherNSMap[ns]; !ok {
|
||||
publisherNamespaces.Add(ns)
|
||||
publisherNSMap[ns] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *agentClient) Stop() error {
|
||||
_ = c.invalidateSub.Close()
|
||||
<-c.subDone
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Copyright 2024 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 agent
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/logger"
|
||||
)
|
||||
|
||||
// Represents a job that is being executed by a worker
|
||||
type Job struct {
|
||||
id string
|
||||
jobType livekit.JobType
|
||||
status livekit.JobStatus
|
||||
namespace string
|
||||
|
||||
mu sync.Mutex
|
||||
load float32
|
||||
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
func NewJob(id, namespace string, jobType livekit.JobType) *Job {
|
||||
return &Job{
|
||||
id: id,
|
||||
status: livekit.JobStatus_JS_UNKNOWN,
|
||||
jobType: jobType,
|
||||
namespace: namespace,
|
||||
}
|
||||
}
|
||||
|
||||
func (j *Job) ID() string {
|
||||
return j.id
|
||||
}
|
||||
|
||||
func (j *Job) Namespace() string {
|
||||
return j.namespace
|
||||
}
|
||||
|
||||
func (j *Job) Type() livekit.JobType {
|
||||
return j.jobType
|
||||
}
|
||||
|
||||
func (j *Job) WorkerLoad() float32 {
|
||||
// Current load that this job is taking on its worker
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
return j.load
|
||||
}
|
||||
|
||||
func (j *Job) UpdateStatus(req *livekit.UpdateJobStatus) {
|
||||
j.mu.Lock()
|
||||
|
||||
if req.Status != nil {
|
||||
j.status = *req.Status // End of the job, SUCCESS or FAILURE
|
||||
|
||||
if j.status == livekit.JobStatus_JS_FAILED {
|
||||
j.Logger.Errorw("job failed", nil, "id", j.id, "type", j.jobType, "error", req.Error)
|
||||
}
|
||||
}
|
||||
|
||||
j.load = req.Load
|
||||
j.mu.Unlock()
|
||||
|
||||
if req.Metadata != nil {
|
||||
j.UpdateMetadata(req.GetMetadata())
|
||||
}
|
||||
}
|
||||
|
||||
func (j *Job) UpdateMetadata(metadata string) {
|
||||
j.Logger.Debugw("job metadata", nil, "id", j.id, "metadata", metadata)
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
// Copyright 2024 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 agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
pagent "github.com/livekit/protocol/agent"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/livekit/protocol/utils"
|
||||
putil "github.com/livekit/protocol/utils"
|
||||
)
|
||||
|
||||
type WorkerProtocolVersion int
|
||||
|
||||
const CurrentProtocol = 1
|
||||
|
||||
const (
|
||||
registerTimeout = 10 * time.Second
|
||||
assignJobTimeout = 10 * time.Second
|
||||
pingFrequency = 10 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
ErrWorkerClosed = errors.New("worker closed")
|
||||
ErrWorkerNotAvailable = errors.New("worker not available")
|
||||
ErrAvailabilityTimeout = errors.New("agent worker availability timeout")
|
||||
)
|
||||
|
||||
type sigConn interface {
|
||||
WriteServerMessage(msg *livekit.ServerMessage) (int, error)
|
||||
}
|
||||
|
||||
type Worker struct {
|
||||
id string
|
||||
jobType livekit.JobType
|
||||
version string
|
||||
name string
|
||||
namespace string
|
||||
load float32
|
||||
permissions *livekit.ParticipantPermission
|
||||
apiKey string
|
||||
apiSecret string
|
||||
serverInfo *livekit.ServerInfo
|
||||
mu sync.Mutex
|
||||
|
||||
protocolVersion WorkerProtocolVersion
|
||||
registered atomic.Bool
|
||||
status livekit.WorkerStatus
|
||||
runningJobs map[string]*Job
|
||||
|
||||
onWorkerRegistered func(w *Worker)
|
||||
|
||||
conn *websocket.Conn
|
||||
sigConn sigConn
|
||||
closed chan struct{}
|
||||
|
||||
availability map[string]chan *livekit.AvailabilityResponse
|
||||
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
func NewWorker(
|
||||
protocolVersion WorkerProtocolVersion,
|
||||
apiKey string,
|
||||
apiSecret string,
|
||||
serverInfo *livekit.ServerInfo,
|
||||
conn *websocket.Conn,
|
||||
sigConn sigConn,
|
||||
logger logger.Logger,
|
||||
) *Worker {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
w := &Worker{
|
||||
id: putil.NewGuid(utils.AgentWorkerPrefix),
|
||||
protocolVersion: protocolVersion,
|
||||
apiKey: apiKey,
|
||||
apiSecret: apiSecret,
|
||||
serverInfo: serverInfo,
|
||||
closed: make(chan struct{}),
|
||||
runningJobs: make(map[string]*Job),
|
||||
availability: make(map[string]chan *livekit.AvailabilityResponse),
|
||||
conn: conn,
|
||||
sigConn: sigConn,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
Logger: logger,
|
||||
}
|
||||
|
||||
go func() {
|
||||
<-time.After(registerTimeout)
|
||||
if !w.registered.Load() && !w.IsClosed() {
|
||||
w.Logger.Warnw("worker did not register in time", nil, "id", w.id)
|
||||
w.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *Worker) sendRequest(req *livekit.ServerMessage) {
|
||||
if _, err := w.sigConn.WriteServerMessage(req); err != nil {
|
||||
w.Logger.Errorw("error writing to websocket", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) ID() string {
|
||||
return w.id
|
||||
}
|
||||
|
||||
func (w *Worker) JobType() livekit.JobType {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.jobType
|
||||
}
|
||||
|
||||
func (w *Worker) Namespace() string {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.namespace
|
||||
}
|
||||
|
||||
func (w *Worker) Status() livekit.WorkerStatus {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.status
|
||||
}
|
||||
|
||||
func (w *Worker) Load() float32 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.load
|
||||
}
|
||||
|
||||
func (w *Worker) OnWorkerRegistered(f func(w *Worker)) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.onWorkerRegistered = f
|
||||
}
|
||||
|
||||
func (w *Worker) Registered() bool {
|
||||
return w.registered.Load()
|
||||
}
|
||||
|
||||
func (w *Worker) RunningJobs() map[string]*Job {
|
||||
jobs := make(map[string]*Job, len(w.runningJobs))
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
for k, v := range w.runningJobs {
|
||||
jobs[k] = v
|
||||
}
|
||||
return jobs
|
||||
}
|
||||
|
||||
func (w *Worker) AssignJob(ctx context.Context, job *livekit.Job) error {
|
||||
availCh := make(chan *livekit.AvailabilityResponse, 1)
|
||||
|
||||
w.mu.Lock()
|
||||
w.availability[job.Id] = availCh
|
||||
w.mu.Unlock()
|
||||
|
||||
w.sendRequest(&livekit.ServerMessage{Message: &livekit.ServerMessage_Availability{
|
||||
Availability: &livekit.AvailabilityRequest{Job: job},
|
||||
}})
|
||||
|
||||
// See handleAvailability for the response
|
||||
select {
|
||||
case res := <-availCh:
|
||||
if !res.Available {
|
||||
return ErrWorkerNotAvailable
|
||||
}
|
||||
|
||||
token, err := pagent.BuildAgentToken(w.apiKey, w.apiSecret, job.Room.Name, res.ParticipantIdentity, res.ParticipantName, res.ParticipantMetadata, w.permissions)
|
||||
if err != nil {
|
||||
w.Logger.Errorw("failed to build agent token", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// In OSS, Url is nil, and the used API Key is the same as the one used to connect the worker
|
||||
w.sendRequest(&livekit.ServerMessage{Message: &livekit.ServerMessage_Assignment{
|
||||
Assignment: &livekit.JobAssignment{Job: job, Url: nil, Token: token},
|
||||
}})
|
||||
|
||||
// TODO(theomonnom): Check if an agent was successfully connected to the room before returning
|
||||
return nil
|
||||
case <-time.After(assignJobTimeout):
|
||||
return ErrAvailabilityTimeout
|
||||
case <-w.ctx.Done():
|
||||
return ErrWorkerClosed
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) UpdateStatus(status *livekit.UpdateWorkerStatus) {
|
||||
w.mu.Lock()
|
||||
if status.Status != nil {
|
||||
w.status = status.GetStatus()
|
||||
}
|
||||
w.load = status.GetLoad()
|
||||
w.mu.Unlock()
|
||||
|
||||
if status.Metadata != nil {
|
||||
w.UpdateMetadata(status.GetMetadata())
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) UpdateMetadata(metadata string) {
|
||||
w.Logger.Debugw("worker metadata updated", nil, "metadata", metadata)
|
||||
}
|
||||
|
||||
func (w *Worker) IsClosed() bool {
|
||||
select {
|
||||
case <-w.closed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) Close() {
|
||||
w.mu.Lock()
|
||||
if w.IsClosed() {
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
w.Logger.Infow("closing worker")
|
||||
|
||||
close(w.closed)
|
||||
w.cancel()
|
||||
_ = w.conn.Close()
|
||||
w.mu.Unlock()
|
||||
}
|
||||
|
||||
func (w *Worker) HandleMessage(req *livekit.WorkerMessage) {
|
||||
switch m := req.Message.(type) {
|
||||
case *livekit.WorkerMessage_Register:
|
||||
go w.handleRegister(m.Register)
|
||||
case *livekit.WorkerMessage_Availability:
|
||||
go w.handleAvailability(m.Availability)
|
||||
case *livekit.WorkerMessage_UpdateJob:
|
||||
go w.handleJobUpdate(m.UpdateJob)
|
||||
case *livekit.WorkerMessage_SimulateJob:
|
||||
go w.handleSimulateJob(m.SimulateJob)
|
||||
case *livekit.WorkerMessage_Ping:
|
||||
go w.handleWorkerPing(m.Ping)
|
||||
case *livekit.WorkerMessage_UpdateWorker:
|
||||
go w.handleWorkerStatus(m.UpdateWorker)
|
||||
case *livekit.WorkerMessage_MigrateJob:
|
||||
go w.handleMigrateJob(m.MigrateJob)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) handleRegister(req *livekit.RegisterWorkerRequest) {
|
||||
if w.registered.Load() {
|
||||
w.Logger.Warnw("worker already registered", nil, "id", w.id)
|
||||
return
|
||||
}
|
||||
|
||||
w.mu.Lock()
|
||||
onWorkerRegistered := w.onWorkerRegistered
|
||||
w.jobType = req.Type
|
||||
w.version = req.Version
|
||||
w.name = req.Name
|
||||
w.namespace = req.GetNamespace()
|
||||
|
||||
if req.AllowedPermissions != nil {
|
||||
w.permissions = req.AllowedPermissions
|
||||
} else {
|
||||
// Use default agent permissions
|
||||
w.permissions = &livekit.ParticipantPermission{
|
||||
CanSubscribe: true,
|
||||
CanPublish: true,
|
||||
CanPublishData: true,
|
||||
CanUpdateMetadata: true,
|
||||
}
|
||||
}
|
||||
|
||||
w.status = livekit.WorkerStatus_WS_AVAILABLE
|
||||
w.registered.Store(true)
|
||||
w.mu.Unlock()
|
||||
|
||||
w.sendRequest(&livekit.ServerMessage{
|
||||
Message: &livekit.ServerMessage_Register{
|
||||
Register: &livekit.RegisterWorkerResponse{
|
||||
WorkerId: w.ID(),
|
||||
ServerInfo: w.serverInfo,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if onWorkerRegistered != nil {
|
||||
onWorkerRegistered(w)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) handleAvailability(res *livekit.AvailabilityResponse) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
|
||||
availCh, ok := w.availability[res.JobId]
|
||||
if !ok {
|
||||
w.Logger.Warnw("received availability response for unknown job", nil, "jobId", res.JobId)
|
||||
return
|
||||
}
|
||||
|
||||
availCh <- res
|
||||
delete(w.availability, res.JobId)
|
||||
}
|
||||
|
||||
func (w *Worker) handleJobUpdate(update *livekit.UpdateJobStatus) {
|
||||
w.mu.Lock()
|
||||
job, ok := w.runningJobs[update.JobId]
|
||||
w.mu.Unlock()
|
||||
|
||||
if !ok {
|
||||
w.Logger.Warnw("received job update for unknown job", nil, "jobId", update.JobId)
|
||||
return
|
||||
}
|
||||
|
||||
job.UpdateStatus(update)
|
||||
}
|
||||
|
||||
func (w *Worker) handleSimulateJob(simulate *livekit.SimulateJobRequest) {
|
||||
jobType := livekit.JobType_JT_ROOM
|
||||
if simulate.Participant != nil {
|
||||
jobType = livekit.JobType_JT_PUBLISHER
|
||||
}
|
||||
|
||||
job := &livekit.Job{
|
||||
Id: utils.NewGuid(utils.AgentJobPrefix),
|
||||
Type: jobType,
|
||||
Room: simulate.Room,
|
||||
Participant: simulate.Participant,
|
||||
Namespace: w.Namespace(),
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
err := w.AssignJob(ctx, job)
|
||||
if err != nil {
|
||||
w.Logger.Errorw("failed to simulate job, assignment failed", err, "jobId", job.Id)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (w *Worker) handleWorkerPing(ping *livekit.WorkerPing) {
|
||||
w.sendRequest(&livekit.ServerMessage{Message: &livekit.ServerMessage_Pong{
|
||||
Pong: &livekit.WorkerPong{
|
||||
LastTimestamp: ping.Timestamp,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
},
|
||||
}})
|
||||
}
|
||||
|
||||
func (w *Worker) handleWorkerStatus(update *livekit.UpdateWorkerStatus) {
|
||||
w.UpdateStatus(update)
|
||||
}
|
||||
|
||||
func (w *Worker) handleMigrateJob(migrate *livekit.MigrateJobRequest) {
|
||||
// TODO(theomonnom): On OSS this is not implemented
|
||||
// We could maybe just move a specific job to another worker
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
// 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 rtc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/livekit/protocol/rpc"
|
||||
"github.com/livekit/psrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
RoomAgentTopic = "room"
|
||||
PublisherAgentTopic = "publisher"
|
||||
)
|
||||
|
||||
type AgentClient interface {
|
||||
CheckEnabled(ctx context.Context, req *rpc.CheckEnabledRequest) *rpc.CheckEnabledResponse
|
||||
JobRequest(ctx context.Context, job *livekit.Job)
|
||||
}
|
||||
|
||||
type agentClient struct {
|
||||
client rpc.AgentInternalClient
|
||||
}
|
||||
|
||||
func NewAgentClient(bus psrpc.MessageBus) (AgentClient, error) {
|
||||
client, err := rpc.NewAgentInternalClient(bus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &agentClient{client: client}, nil
|
||||
}
|
||||
|
||||
func (c *agentClient) CheckEnabled(ctx context.Context, req *rpc.CheckEnabledRequest) *rpc.CheckEnabledResponse {
|
||||
res := &rpc.CheckEnabledResponse{}
|
||||
resChan, err := c.client.CheckEnabled(ctx, req, psrpc.WithRequestTimeout(time.Second))
|
||||
if err != nil {
|
||||
return res
|
||||
}
|
||||
|
||||
for r := range resChan {
|
||||
if r.Err != nil {
|
||||
continue
|
||||
}
|
||||
if r.Result.RoomEnabled {
|
||||
res.RoomEnabled = true
|
||||
if res.PublisherEnabled {
|
||||
return res
|
||||
}
|
||||
}
|
||||
if r.Result.PublisherEnabled {
|
||||
res.PublisherEnabled = true
|
||||
if res.RoomEnabled {
|
||||
return res
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func (c *agentClient) JobRequest(ctx context.Context, job *livekit.Job) {
|
||||
var topic string
|
||||
var logError bool
|
||||
switch job.Type {
|
||||
case livekit.JobType_JT_ROOM:
|
||||
topic = RoomAgentTopic
|
||||
case livekit.JobType_JT_PUBLISHER:
|
||||
topic = PublisherAgentTopic
|
||||
logError = true
|
||||
}
|
||||
|
||||
_, err := c.client.JobRequest(ctx, topic, job)
|
||||
if err != nil && logError {
|
||||
logger.Warnw("agent job request failed", err)
|
||||
}
|
||||
}
|
||||
+10
-32
@@ -34,9 +34,9 @@ import (
|
||||
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/livekit/protocol/rpc"
|
||||
"github.com/livekit/protocol/utils"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/agent"
|
||||
"github.com/livekit/livekit-server/pkg/config"
|
||||
"github.com/livekit/livekit-server/pkg/routing"
|
||||
"github.com/livekit/livekit-server/pkg/rtc/types"
|
||||
@@ -103,8 +103,7 @@ type Room struct {
|
||||
trackManager *RoomTrackManager
|
||||
|
||||
// agents
|
||||
agentClient AgentClient
|
||||
publisherAgentsEnabled bool
|
||||
agentClient agent.Client
|
||||
|
||||
// map of identity -> Participant
|
||||
participants map[livekit.ParticipantIdentity]types.LocalParticipant
|
||||
@@ -142,7 +141,7 @@ func NewRoom(
|
||||
audioConfig *config.AudioConfig,
|
||||
serverInfo *livekit.ServerInfo,
|
||||
telemetry telemetry.TelemetryService,
|
||||
agentClient AgentClient,
|
||||
agentClient agent.Client,
|
||||
egressLauncher EgressLauncher,
|
||||
) *Room {
|
||||
r := &Room{
|
||||
@@ -183,21 +182,6 @@ func NewRoom(
|
||||
}
|
||||
r.protoProxy = utils.NewProtoProxy[*livekit.Room](roomUpdateInterval, r.updateProto)
|
||||
|
||||
if agentClient != nil {
|
||||
go func() {
|
||||
res := r.agentClient.CheckEnabled(context.Background(), &rpc.CheckEnabledRequest{})
|
||||
if res.PublisherEnabled {
|
||||
r.lock.Lock()
|
||||
r.publisherAgentsEnabled = true
|
||||
// if there are already published tracks, start the agents
|
||||
for identity := range r.hasPublished {
|
||||
r.launchPublisherAgent(r.participants[identity])
|
||||
}
|
||||
r.lock.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
go r.audioUpdateWorker()
|
||||
go r.connectionQualityWorker()
|
||||
go r.changeUpdateWorker()
|
||||
@@ -1013,13 +997,10 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
|
||||
r.lock.Lock()
|
||||
hasPublished := r.hasPublished[participant.Identity()]
|
||||
r.hasPublished[participant.Identity()] = true
|
||||
publisherAgentsEnabled := r.publisherAgentsEnabled
|
||||
r.lock.Unlock()
|
||||
|
||||
if !hasPublished {
|
||||
if publisherAgentsEnabled {
|
||||
r.launchPublisherAgent(participant)
|
||||
}
|
||||
r.launchPublisherAgent(participant)
|
||||
if r.internal != nil && r.internal.ParticipantEgress != nil {
|
||||
go func() {
|
||||
if err := StartParticipantEgress(
|
||||
@@ -1429,18 +1410,15 @@ func (r *Room) simulationCleanupWorker() {
|
||||
}
|
||||
|
||||
func (r *Room) launchPublisherAgent(p types.Participant) {
|
||||
if p == nil || p.IsRecorder() || p.IsAgent() {
|
||||
if p == nil || p.IsRecorder() || p.IsAgent() || r.agentClient == nil {
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
r.agentClient.JobRequest(context.Background(), &livekit.Job{
|
||||
Id: utils.NewGuid("JP_"),
|
||||
Type: livekit.JobType_JT_PUBLISHER,
|
||||
Room: r.ToProto(),
|
||||
Participant: p.ToProto(),
|
||||
})
|
||||
}()
|
||||
go r.agentClient.LaunchJob(context.Background(), &agent.JobDescription{
|
||||
JobType: livekit.JobType_JT_PUBLISHER,
|
||||
Room: r.ToProto(),
|
||||
Participant: p.ToProto(),
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Room) DebugInfo() map[string]interface{} {
|
||||
|
||||
@@ -586,3 +586,4 @@ type OperationMonitor interface {
|
||||
Check() error
|
||||
IsIdle() bool
|
||||
}
|
||||
|
||||
|
||||
+243
-334
@@ -1,4 +1,4 @@
|
||||
// Copyright 2023 LiveKit, Inc.
|
||||
// Copyright 2024 LiveKit, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -27,16 +28,19 @@ import (
|
||||
"github.com/gorilla/websocket"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/agent"
|
||||
"github.com/livekit/livekit-server/pkg/config"
|
||||
"github.com/livekit/livekit-server/pkg/routing"
|
||||
"github.com/livekit/livekit-server/pkg/rtc"
|
||||
"github.com/livekit/livekit-server/pkg/rtc/types"
|
||||
"github.com/livekit/livekit-server/pkg/utils"
|
||||
"github.com/livekit/livekit-server/version"
|
||||
"github.com/livekit/protocol/auth"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/logger"
|
||||
"github.com/livekit/protocol/rpc"
|
||||
"github.com/livekit/psrpc"
|
||||
)
|
||||
|
||||
const AgentServiceVersion = "0.1.0"
|
||||
|
||||
type AgentService struct {
|
||||
upgrader websocket.Upgrader
|
||||
|
||||
@@ -44,38 +48,30 @@ type AgentService struct {
|
||||
}
|
||||
|
||||
type AgentHandler struct {
|
||||
agentServer rpc.AgentInternalServer
|
||||
roomTopic string
|
||||
publisherTopic string
|
||||
agentServer rpc.AgentInternalServer
|
||||
mu sync.Mutex
|
||||
|
||||
mu sync.Mutex
|
||||
availability map[string]chan *availability
|
||||
unregistered map[*websocket.Conn]*worker
|
||||
roomRegistered bool
|
||||
roomWorkers map[string]*worker
|
||||
publisherRegistered bool
|
||||
publisherWorkers map[string]*worker
|
||||
onWorkerRegistered func(handler *AgentHandler)
|
||||
serverInfo *livekit.ServerInfo
|
||||
workers map[string]*agent.Worker
|
||||
keyProvider auth.KeyProvider
|
||||
|
||||
namespaces map[string]*namespaceInfo
|
||||
publisherEnabled bool
|
||||
roomEnabled bool
|
||||
roomTopic string
|
||||
publisherTopic string
|
||||
}
|
||||
|
||||
type worker struct {
|
||||
mu sync.Mutex
|
||||
conn *websocket.Conn
|
||||
sigConn *WSSignalConnection
|
||||
|
||||
id string
|
||||
jobType livekit.JobType
|
||||
status livekit.WorkerStatus
|
||||
activeJobs int
|
||||
logger logger.Logger
|
||||
type namespaceInfo struct {
|
||||
numPublishers int32
|
||||
numRooms int32
|
||||
}
|
||||
|
||||
type availability struct {
|
||||
workerID string
|
||||
available bool
|
||||
}
|
||||
|
||||
func NewAgentService(bus psrpc.MessageBus) (*AgentService, error) {
|
||||
func NewAgentService(conf *config.Config,
|
||||
currentNode routing.LocalNode,
|
||||
bus psrpc.MessageBus,
|
||||
keyProvider auth.KeyProvider,
|
||||
) (*AgentService, error) {
|
||||
s := &AgentService{
|
||||
upgrader: websocket.Upgrader{},
|
||||
}
|
||||
@@ -86,12 +82,26 @@ func NewAgentService(bus psrpc.MessageBus) (*AgentService, error) {
|
||||
return true
|
||||
}
|
||||
|
||||
serverInfo := &livekit.ServerInfo{
|
||||
Edition: livekit.ServerInfo_Standard,
|
||||
Version: version.Version,
|
||||
Protocol: types.CurrentProtocol,
|
||||
AgentProtocol: agent.CurrentProtocol,
|
||||
Region: conf.Region,
|
||||
NodeId: currentNode.Id,
|
||||
}
|
||||
|
||||
agentServer, err := rpc.NewAgentInternalServer(s, bus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.AgentHandler = NewAgentHandler(agentServer, rtc.RoomAgentTopic, rtc.PublisherAgentTopic)
|
||||
|
||||
s.AgentHandler = NewAgentHandler(
|
||||
agentServer,
|
||||
keyProvider,
|
||||
serverInfo,
|
||||
agent.RoomAgentTopic,
|
||||
agent.PublisherAgentTopic,
|
||||
)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -116,64 +126,64 @@ func (s *AgentService) ServeHTTP(writer http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
s.HandleConnection(r.Context(), conn)
|
||||
s.HandleConnection(r, conn, nil)
|
||||
}
|
||||
|
||||
func NewAgentHandler(agentServer rpc.AgentInternalServer, roomTopic, publisherTopic string) *AgentHandler {
|
||||
func NewAgentHandler(
|
||||
agentServer rpc.AgentInternalServer,
|
||||
keyProvider auth.KeyProvider,
|
||||
serverInfo *livekit.ServerInfo,
|
||||
roomTopic string,
|
||||
publisherTopic string,
|
||||
) *AgentHandler {
|
||||
return &AgentHandler{
|
||||
agentServer: agentServer,
|
||||
roomTopic: roomTopic,
|
||||
publisherTopic: publisherTopic,
|
||||
availability: make(map[string]chan *availability),
|
||||
unregistered: make(map[*websocket.Conn]*worker),
|
||||
roomWorkers: make(map[string]*worker),
|
||||
publisherWorkers: make(map[string]*worker),
|
||||
agentServer: agentServer,
|
||||
workers: make(map[string]*agent.Worker),
|
||||
namespaces: make(map[string]*namespaceInfo),
|
||||
serverInfo: serverInfo,
|
||||
keyProvider: keyProvider,
|
||||
roomTopic: roomTopic,
|
||||
publisherTopic: publisherTopic,
|
||||
}
|
||||
}
|
||||
|
||||
// OnWorkerRegistered registers a callback to be called when the first worker of each type is registered
|
||||
func (s *AgentHandler) OnWorkerRegistered(handler func(handler *AgentHandler)) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.onWorkerRegistered = handler
|
||||
}
|
||||
func (h *AgentHandler) HandleConnection(r *http.Request, conn *websocket.Conn, onIdle func()) {
|
||||
var protocol agent.WorkerProtocolVersion
|
||||
if pv, err := strconv.Atoi(r.FormValue("protocol")); err == nil {
|
||||
protocol = agent.WorkerProtocolVersion(pv)
|
||||
}
|
||||
|
||||
func (s *AgentHandler) HandleConnection(ctx context.Context, conn *websocket.Conn) {
|
||||
sigConn := NewWSSignalConnection(conn)
|
||||
w := &worker{
|
||||
conn: conn,
|
||||
sigConn: sigConn,
|
||||
logger: utils.GetLogger(ctx),
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
s.unregistered[conn] = w
|
||||
s.mu.Unlock()
|
||||
logger := utils.GetLogger(r.Context())
|
||||
|
||||
apiKey := GetAPIKey(r.Context())
|
||||
apiSecret := h.keyProvider.GetSecret(apiKey)
|
||||
|
||||
worker := agent.NewWorker(protocol, apiKey, apiSecret, h.serverInfo, conn, sigConn, logger)
|
||||
worker.OnWorkerRegistered(h.registerWorkerTopic)
|
||||
|
||||
h.mu.Lock()
|
||||
h.workers[worker.ID()] = worker
|
||||
h.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.publisherWorkers, w.id)
|
||||
if s.publisherRegistered && !s.publisherAvailableLocked() {
|
||||
s.publisherRegistered = false
|
||||
s.agentServer.DeregisterJobRequestTopic(s.publisherTopic)
|
||||
}
|
||||
}
|
||||
worker.Close()
|
||||
|
||||
h.mu.Lock()
|
||||
delete(h.workers, worker.ID())
|
||||
numWorkers := len(h.workers)
|
||||
h.mu.Unlock()
|
||||
|
||||
if worker.Registered() {
|
||||
h.deregisterWorkerTopic(worker)
|
||||
}
|
||||
|
||||
if numWorkers == 0 && onIdle != nil {
|
||||
onIdle()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
|
||||
// handle incoming requests from websocket
|
||||
for {
|
||||
req, _, err := sigConn.ReadWorkerMessage()
|
||||
if err != nil {
|
||||
@@ -188,321 +198,220 @@ func (s *AgentHandler) HandleConnection(ctx context.Context, conn *websocket.Con
|
||||
websocket.CloseNormalClosure,
|
||||
websocket.CloseNoStatusReceived,
|
||||
) {
|
||||
w.logger.Infow("Agent worker closed WS connection", "wsError", err)
|
||||
worker.Logger.Infow("worker closed WS connection", "wsError", err)
|
||||
} else {
|
||||
w.logger.Errorw("error reading from websocket", err)
|
||||
worker.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)
|
||||
}
|
||||
worker.HandleMessage(req)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AgentHandler) handleRegister(worker *worker, msg *livekit.RegisterWorkerRequest) {
|
||||
if err := s.doHandleRegister(worker, msg); err != nil {
|
||||
worker.logger.Errorw("failed to register worker", err, "workerID", msg.WorkerId, "jobType", msg.Type)
|
||||
worker.conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AgentHandler) doHandleRegister(worker *worker, msg *livekit.RegisterWorkerRequest) error {
|
||||
if msg.WorkerId == "" {
|
||||
return errors.New("invalid worker id")
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
if worker.id != "" {
|
||||
s.mu.Unlock()
|
||||
return errors.New("worker already registered")
|
||||
}
|
||||
|
||||
onRegistered := s.onWorkerRegistered
|
||||
firstWorker := false
|
||||
|
||||
switch msg.Type {
|
||||
case livekit.JobType_JT_ROOM:
|
||||
worker.id = msg.WorkerId
|
||||
worker.jobType = msg.Type
|
||||
delete(s.unregistered, worker.conn)
|
||||
s.roomWorkers[worker.id] = worker
|
||||
|
||||
if !s.roomRegistered {
|
||||
err := s.agentServer.RegisterJobRequestTopic(s.roomTopic)
|
||||
if err != nil {
|
||||
worker.logger.Errorw("failed to register room agents", err)
|
||||
} else {
|
||||
s.roomRegistered = true
|
||||
firstWorker = true
|
||||
}
|
||||
}
|
||||
|
||||
case livekit.JobType_JT_PUBLISHER:
|
||||
worker.id = msg.WorkerId
|
||||
worker.jobType = msg.Type
|
||||
delete(s.unregistered, worker.conn)
|
||||
s.publisherWorkers[worker.id] = worker
|
||||
|
||||
if !s.publisherRegistered {
|
||||
err := s.agentServer.RegisterJobRequestTopic(s.publisherTopic)
|
||||
if err != nil {
|
||||
worker.logger.Errorw("failed to register publisher agents", err)
|
||||
} else {
|
||||
s.publisherRegistered = true
|
||||
firstWorker = true
|
||||
}
|
||||
}
|
||||
default:
|
||||
s.mu.Unlock()
|
||||
return errors.New("invalid job type")
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
_, err := worker.sigConn.WriteServerMessage(&livekit.ServerMessage{
|
||||
Message: &livekit.ServerMessage_Register{
|
||||
Register: &livekit.RegisterWorkerResponse{
|
||||
WorkerId: worker.id,
|
||||
ServerVersion: AgentServiceVersion,
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
worker.logger.Errorw("failed to write server message", err)
|
||||
}
|
||||
|
||||
if firstWorker && onRegistered != nil {
|
||||
onRegistered(s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AgentHandler) handleAvailability(w *worker, msg *livekit.AvailabilityResponse) {
|
||||
s.mu.Lock()
|
||||
availabilityChan, ok := s.availability[msg.JobId]
|
||||
s.mu.Unlock()
|
||||
func (h *AgentHandler) registerWorkerTopic(w *agent.Worker) {
|
||||
h.mu.Lock()
|
||||
|
||||
info, ok := h.namespaces[w.Namespace()]
|
||||
numPublishers := int32(0)
|
||||
numRooms := int32(0)
|
||||
if ok {
|
||||
availabilityChan <- &availability{
|
||||
workerID: w.id,
|
||||
available: msg.Available,
|
||||
numPublishers = info.numPublishers
|
||||
numRooms = info.numRooms
|
||||
}
|
||||
|
||||
var err error
|
||||
if w.JobType() == livekit.JobType_JT_PUBLISHER {
|
||||
numPublishers++
|
||||
if numPublishers == 1 {
|
||||
err = h.agentServer.RegisterJobRequestTopic(w.Namespace(), h.publisherTopic)
|
||||
}
|
||||
|
||||
} else if w.JobType() == livekit.JobType_JT_ROOM {
|
||||
numRooms++
|
||||
if numRooms == 1 {
|
||||
err = h.agentServer.RegisterJobRequestTopic(w.Namespace(), h.roomTopic)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AgentHandler) handleJobUpdate(w *worker, msg *livekit.JobStatusUpdate) {
|
||||
switch msg.Status {
|
||||
case livekit.JobStatus_JS_SUCCESS:
|
||||
w.logger.Debugw("job complete", "jobID", msg.JobId)
|
||||
case livekit.JobStatus_JS_FAILED:
|
||||
w.logger.Warnw("job failed", errors.New(msg.Error), "jobID", msg.JobId)
|
||||
if err != nil {
|
||||
w.Logger.Errorw("failed to register job request topic", err)
|
||||
h.mu.Unlock()
|
||||
w.Close() // Close the worker
|
||||
return
|
||||
}
|
||||
|
||||
w.mu.Lock()
|
||||
w.activeJobs--
|
||||
w.mu.Unlock()
|
||||
h.namespaces[w.Namespace()] = &namespaceInfo{
|
||||
numPublishers: numPublishers,
|
||||
numRooms: numRooms,
|
||||
}
|
||||
|
||||
h.roomEnabled = h.roomAvailableLocked()
|
||||
h.publisherEnabled = h.publisherAvailableLocked()
|
||||
h.mu.Unlock()
|
||||
|
||||
err = h.agentServer.PublishWorkerRegistered(context.Background(), agent.DefaultHandlerNamespace, &emptypb.Empty{})
|
||||
if err != nil {
|
||||
w.Logger.Errorw("failed to publish worker registered", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AgentHandler) handleStatus(w *worker, msg *livekit.UpdateWorkerStatus) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
func (h *AgentHandler) deregisterWorkerTopic(worker *agent.Worker) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
w.mu.Lock()
|
||||
w.status = msg.Status
|
||||
w.mu.Unlock()
|
||||
info, ok := h.namespaces[worker.Namespace()]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
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 {
|
||||
w.logger.Errorw("failed to register room agents", err)
|
||||
} else {
|
||||
s.roomRegistered = true
|
||||
}
|
||||
if worker.JobType() == livekit.JobType_JT_PUBLISHER {
|
||||
info.numPublishers--
|
||||
if info.numPublishers == 0 {
|
||||
h.agentServer.DeregisterJobRequestTopic(worker.Namespace(), h.publisherTopic)
|
||||
}
|
||||
case livekit.JobType_JT_PUBLISHER:
|
||||
if s.publisherRegistered && !s.publisherAvailableLocked() {
|
||||
s.publisherRegistered = false
|
||||
s.agentServer.DeregisterJobRequestTopic(s.publisherTopic)
|
||||
} else if !s.publisherRegistered && s.publisherAvailableLocked() {
|
||||
if err := s.agentServer.RegisterJobRequestTopic(s.publisherTopic); err != nil {
|
||||
w.logger.Errorw("failed to register publisher agents", err)
|
||||
} else {
|
||||
s.publisherRegistered = true
|
||||
}
|
||||
} else if worker.JobType() == livekit.JobType_JT_ROOM {
|
||||
info.numRooms--
|
||||
if info.numRooms == 0 {
|
||||
h.agentServer.DeregisterJobRequestTopic(worker.Namespace(), h.roomTopic)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AgentHandler) CheckEnabled(_ context.Context, _ *rpc.CheckEnabledRequest) (*rpc.CheckEnabledResponse, error) {
|
||||
s.mu.Lock()
|
||||
res := &rpc.CheckEnabledResponse{
|
||||
RoomEnabled: len(s.roomWorkers) > 0,
|
||||
PublisherEnabled: len(s.publisherWorkers) > 0,
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return res, nil
|
||||
}
|
||||
|
||||
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.publisherWorkers
|
||||
if info.numPublishers == 0 && info.numRooms == 0 {
|
||||
delete(h.namespaces, worker.Namespace())
|
||||
}
|
||||
|
||||
h.roomEnabled = h.roomAvailableLocked()
|
||||
h.publisherEnabled = h.publisherAvailableLocked()
|
||||
}
|
||||
|
||||
func (h *AgentHandler) roomAvailableLocked() bool {
|
||||
for _, w := range h.workers {
|
||||
if w.JobType() == livekit.JobType_JT_ROOM {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
|
||||
}
|
||||
|
||||
func (h *AgentHandler) publisherAvailableLocked() bool {
|
||||
for _, w := range h.workers {
|
||||
if w.JobType() == livekit.JobType_JT_PUBLISHER {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *AgentHandler) JobRequest(ctx context.Context, job *livekit.Job) (*emptypb.Empty, error) {
|
||||
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")
|
||||
h.mu.Lock()
|
||||
var selected *agent.Worker
|
||||
var maxLoad float32
|
||||
for _, w := range h.workers {
|
||||
if w.Namespace() != job.Namespace || w.JobType() != job.Type {
|
||||
continue
|
||||
}
|
||||
|
||||
attempted[selected.id] = true
|
||||
_, err := selected.sigConn.WriteServerMessage(&livekit.ServerMessage{Message: &livekit.ServerMessage_Availability{
|
||||
Availability: &livekit.AvailabilityRequest{Job: job},
|
||||
}})
|
||||
if err != nil {
|
||||
selected.logger.Errorw("failed to send availability request", err, "workerID", selected.id)
|
||||
_, ok := attempted[w.ID()]
|
||||
if ok {
|
||||
continue
|
||||
}
|
||||
|
||||
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 {
|
||||
selected.logger.Errorw("failed to assign job", err, "workerID", selected.id)
|
||||
} else {
|
||||
selected.mu.Lock()
|
||||
selected.activeJobs++
|
||||
selected.mu.Unlock()
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
if w.Status() == livekit.WorkerStatus_WS_AVAILABLE {
|
||||
load := w.Load()
|
||||
if len(w.RunningJobs()) > 0 && load > maxLoad {
|
||||
maxLoad = load
|
||||
selected = w
|
||||
} else if selected == nil {
|
||||
selected = w
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
if selected == nil {
|
||||
return nil, psrpc.NewErrorf(psrpc.DeadlineExceeded, "no workers available")
|
||||
}
|
||||
|
||||
attempted[selected.ID()] = true
|
||||
|
||||
err := selected.AssignJob(ctx, job)
|
||||
if err != nil {
|
||||
if errors.Is(err, agent.ErrWorkerNotAvailable) {
|
||||
continue // Try another worker
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
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.publisherWorkers
|
||||
}
|
||||
func (h *AgentHandler) JobRequestAffinity(ctx context.Context, job *livekit.Job) float32 {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
var affinity float32
|
||||
for _, w := range pool {
|
||||
if w.status == livekit.WorkerStatus_WS_AVAILABLE {
|
||||
if w.activeJobs > 0 {
|
||||
return 1
|
||||
var maxLoad float32
|
||||
for _, w := range h.workers {
|
||||
if w.Namespace() != job.Namespace || w.JobType() != job.Type {
|
||||
continue
|
||||
}
|
||||
|
||||
if w.Status() == livekit.WorkerStatus_WS_AVAILABLE {
|
||||
load := w.Load()
|
||||
if len(w.RunningJobs()) > 0 && load > maxLoad {
|
||||
maxLoad = load
|
||||
affinity = 0.5 + load/2
|
||||
} else {
|
||||
affinity = 0.5
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return affinity
|
||||
}
|
||||
|
||||
func (s *AgentHandler) NumConnections() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
func (h *AgentHandler) CheckEnabled(ctx context.Context, req *rpc.CheckEnabledRequest) (*rpc.CheckEnabledResponse, error) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
namespaces := make([]string, 0, len(h.namespaces))
|
||||
for ns := range h.namespaces {
|
||||
namespaces = append(namespaces, ns)
|
||||
}
|
||||
|
||||
return len(s.unregistered) + len(s.roomWorkers) + len(s.publisherWorkers)
|
||||
return &rpc.CheckEnabledResponse{
|
||||
Namespaces: namespaces,
|
||||
RoomEnabled: h.roomEnabled,
|
||||
PublisherEnabled: h.publisherEnabled,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AgentHandler) DrainConnections(interval time.Duration) {
|
||||
func (h *AgentHandler) NumConnections() int {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return len(h.workers)
|
||||
}
|
||||
|
||||
func (h *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()
|
||||
h.mu.Lock()
|
||||
defer h.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.publisherWorkers {
|
||||
_ = w.conn.Close()
|
||||
for _, w := range h.workers {
|
||||
w.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) publisherAvailableLocked() bool {
|
||||
for _, w := range s.publisherWorkers {
|
||||
if w.status == livekit.WorkerStatus_WS_AVAILABLE {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
+25
-5
@@ -34,6 +34,11 @@ const (
|
||||
|
||||
type grantsKey struct{}
|
||||
|
||||
type grantsValue struct {
|
||||
claims *auth.ClaimGrants
|
||||
apiKey string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrPermissionDenied = errors.New("permissions denied")
|
||||
ErrMissingAuthorization = errors.New("invalid authorization header. Must start with " + bearerPrefix)
|
||||
@@ -93,7 +98,10 @@ func (m *APIKeyAuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request,
|
||||
|
||||
// set grants in context
|
||||
ctx := r.Context()
|
||||
r = r.WithContext(context.WithValue(ctx, grantsKey{}, grants))
|
||||
r = r.WithContext(context.WithValue(ctx, grantsKey{}, &grantsValue{
|
||||
claims: grants,
|
||||
apiKey: v.APIKey(),
|
||||
}))
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
@@ -101,15 +109,27 @@ func (m *APIKeyAuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request,
|
||||
|
||||
func GetGrants(ctx context.Context) *auth.ClaimGrants {
|
||||
val := ctx.Value(grantsKey{})
|
||||
claims, ok := val.(*auth.ClaimGrants)
|
||||
v, ok := val.(*grantsValue)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return claims
|
||||
return v.claims
|
||||
}
|
||||
|
||||
func WithGrants(ctx context.Context, grants *auth.ClaimGrants) context.Context {
|
||||
return context.WithValue(ctx, grantsKey{}, grants)
|
||||
func GetAPIKey(ctx context.Context) string {
|
||||
val := ctx.Value(grantsKey{})
|
||||
v, ok := val.(*grantsValue)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return v.apiKey
|
||||
}
|
||||
|
||||
func WithGrants(ctx context.Context, grants *auth.ClaimGrants, apiKey string) context.Context {
|
||||
return context.WithValue(ctx, grantsKey{}, &grantsValue{
|
||||
claims: grants,
|
||||
apiKey: apiKey,
|
||||
})
|
||||
}
|
||||
|
||||
func SetAuthorizationToken(r *http.Request, token string) {
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/exp/maps"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/agent"
|
||||
"github.com/livekit/mediatransportutil/pkg/rtcconfig"
|
||||
"github.com/livekit/protocol/auth"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
@@ -70,7 +71,7 @@ type RoomManager struct {
|
||||
roomStore ObjectStore
|
||||
telemetry telemetry.TelemetryService
|
||||
clientConfManager clientconfiguration.ClientConfigurationManager
|
||||
agentClient rtc.AgentClient
|
||||
agentClient agent.Client
|
||||
egressLauncher rtc.EgressLauncher
|
||||
versionGenerator utils.TimedVersionGenerator
|
||||
turnAuthHandler *TURNAuthHandler
|
||||
@@ -91,7 +92,7 @@ func NewLocalRoomManager(
|
||||
router routing.Router,
|
||||
telemetry telemetry.TelemetryService,
|
||||
clientConfManager clientconfiguration.ClientConfigurationManager,
|
||||
agentClient rtc.AgentClient,
|
||||
agentClient agent.Client,
|
||||
egressLauncher rtc.EgressLauncher,
|
||||
versionGenerator utils.TimedVersionGenerator,
|
||||
turnAuthHandler *TURNAuthHandler,
|
||||
@@ -121,11 +122,12 @@ func NewLocalRoomManager(
|
||||
iceConfigCache: make(map[livekit.ParticipantIdentity]*iceConfigCacheEntry),
|
||||
|
||||
serverInfo: &livekit.ServerInfo{
|
||||
Edition: livekit.ServerInfo_Standard,
|
||||
Version: version.Version,
|
||||
Protocol: types.CurrentProtocol,
|
||||
Region: conf.Region,
|
||||
NodeId: currentNode.Id,
|
||||
Edition: livekit.ServerInfo_Standard,
|
||||
Version: version.Version,
|
||||
Protocol: types.CurrentProtocol,
|
||||
AgentProtocol: agent.CurrentProtocol,
|
||||
Region: conf.Region,
|
||||
NodeId: currentNode.Id,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
+11
-17
@@ -22,12 +22,12 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
"github.com/twitchtv/twirp"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/agent"
|
||||
"github.com/livekit/livekit-server/pkg/config"
|
||||
"github.com/livekit/livekit-server/pkg/routing"
|
||||
"github.com/livekit/livekit-server/pkg/rtc"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/rpc"
|
||||
"github.com/livekit/protocol/utils"
|
||||
"github.com/livekit/psrpc"
|
||||
)
|
||||
|
||||
@@ -39,7 +39,7 @@ type RoomService struct {
|
||||
router routing.MessageRouter
|
||||
roomAllocator RoomAllocator
|
||||
roomStore ServiceStore
|
||||
agentClient rtc.AgentClient
|
||||
agentClient agent.Client
|
||||
egressLauncher rtc.EgressLauncher
|
||||
topicFormatter rpc.TopicFormatter
|
||||
roomClient rpc.TypedRoomClient
|
||||
@@ -53,7 +53,7 @@ func NewRoomService(
|
||||
router routing.MessageRouter,
|
||||
roomAllocator RoomAllocator,
|
||||
serviceStore ServiceStore,
|
||||
agentClient rtc.AgentClient,
|
||||
agentClient agent.Client,
|
||||
egressLauncher rtc.EgressLauncher,
|
||||
topicFormatter rpc.TopicFormatter,
|
||||
roomClient rpc.TypedRoomClient,
|
||||
@@ -101,13 +101,10 @@ func (s *RoomService) CreateRoom(ctx context.Context, req *livekit.CreateRoomReq
|
||||
defer res.ResponseSource.Close()
|
||||
|
||||
if created {
|
||||
go func() {
|
||||
s.agentClient.JobRequest(ctx, &livekit.Job{
|
||||
Id: utils.NewGuid("JR_"),
|
||||
Type: livekit.JobType_JT_ROOM,
|
||||
Room: rm,
|
||||
})
|
||||
}()
|
||||
go s.agentClient.LaunchJob(ctx, &agent.JobDescription{
|
||||
JobType: livekit.JobType_JT_ROOM,
|
||||
Room: rm,
|
||||
})
|
||||
|
||||
if req.Egress != nil && req.Egress.Room != nil {
|
||||
_, err = s.egressLauncher.StartEgress(ctx, &rpc.StartEgressRequest{
|
||||
@@ -301,13 +298,10 @@ func (s *RoomService) UpdateRoomMetadata(ctx context.Context, req *livekit.Updat
|
||||
}
|
||||
|
||||
if created {
|
||||
go func() {
|
||||
s.agentClient.JobRequest(ctx, &livekit.Job{
|
||||
Id: utils.NewGuid("JR_"),
|
||||
Type: livekit.JobType_JT_ROOM,
|
||||
Room: room,
|
||||
})
|
||||
}()
|
||||
go s.agentClient.LaunchJob(ctx, &agent.JobDescription{
|
||||
JobType: livekit.JobType_JT_ROOM,
|
||||
Room: room,
|
||||
})
|
||||
}
|
||||
|
||||
return room, nil
|
||||
|
||||
@@ -38,7 +38,7 @@ func TestDeleteRoom(t *testing.T) {
|
||||
grant := &auth.ClaimGrants{
|
||||
Video: &auth.VideoGrant{},
|
||||
}
|
||||
ctx := service.WithGrants(context.Background(), grant)
|
||||
ctx := service.WithGrants(context.Background(), grant, "")
|
||||
_, err := svc.DeleteRoom(ctx, &livekit.DeleteRoomRequest{
|
||||
Room: "testroom",
|
||||
})
|
||||
@@ -52,7 +52,7 @@ func TestMetaDataLimits(t *testing.T) {
|
||||
grant := &auth.ClaimGrants{
|
||||
Video: &auth.VideoGrant{},
|
||||
}
|
||||
ctx := service.WithGrants(context.Background(), grant)
|
||||
ctx := service.WithGrants(context.Background(), grant, "")
|
||||
_, err := svc.UpdateParticipant(ctx, &livekit.UpdateParticipantRequest{
|
||||
Room: "testroom",
|
||||
Identity: "123",
|
||||
@@ -82,7 +82,7 @@ func TestMetaDataLimits(t *testing.T) {
|
||||
grant := &auth.ClaimGrants{
|
||||
Video: &auth.VideoGrant{},
|
||||
}
|
||||
ctx := service.WithGrants(context.Background(), grant)
|
||||
ctx := service.WithGrants(context.Background(), grant, "")
|
||||
_, err := svc.UpdateParticipant(ctx, &livekit.UpdateParticipantRequest{
|
||||
Room: "testroom",
|
||||
Identity: "123",
|
||||
|
||||
+10
-13
@@ -32,6 +32,7 @@ import (
|
||||
"go.uber.org/atomic"
|
||||
"golang.org/x/exp/maps"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/agent"
|
||||
"github.com/livekit/livekit-server/pkg/config"
|
||||
"github.com/livekit/livekit-server/pkg/routing"
|
||||
"github.com/livekit/livekit-server/pkg/routing/selector"
|
||||
@@ -40,7 +41,6 @@ import (
|
||||
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
|
||||
"github.com/livekit/livekit-server/pkg/utils"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
putil "github.com/livekit/protocol/utils"
|
||||
"github.com/livekit/psrpc"
|
||||
)
|
||||
|
||||
@@ -54,7 +54,7 @@ type RTCService struct {
|
||||
isDev bool
|
||||
limits config.LimitConfig
|
||||
parser *uaparser.Parser
|
||||
agentClient rtc.AgentClient
|
||||
agentClient agent.Client
|
||||
telemetry telemetry.TelemetryService
|
||||
|
||||
mu sync.Mutex
|
||||
@@ -67,7 +67,7 @@ func NewRTCService(
|
||||
store ServiceStore,
|
||||
router routing.MessageRouter,
|
||||
currentNode routing.LocalNode,
|
||||
agentClient rtc.AgentClient,
|
||||
agentClient agent.Client,
|
||||
telemetry telemetry.TelemetryService,
|
||||
) *RTCService {
|
||||
s := &RTCService{
|
||||
@@ -524,6 +524,13 @@ func (s *RTCService) startConnection(
|
||||
return cr, nil, err
|
||||
}
|
||||
|
||||
if created && s.agentClient != nil {
|
||||
go s.agentClient.LaunchJob(ctx, &agent.JobDescription{
|
||||
JobType: livekit.JobType_JT_ROOM,
|
||||
Room: cr.Room,
|
||||
})
|
||||
}
|
||||
|
||||
// this needs to be started first *before* using router functions on this node
|
||||
cr.StartParticipantSignalResults, err = s.router.StartParticipantSignal(ctx, roomName, pi)
|
||||
if err != nil {
|
||||
@@ -541,16 +548,6 @@ func (s *RTCService) startConnection(
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -125,6 +125,7 @@ func NewLivekitServer(conf *config.Config,
|
||||
mux.HandleFunc("/debug/goroutine", s.debugGoroutines)
|
||||
mux.HandleFunc("/debug/rooms", s.debugInfo)
|
||||
}
|
||||
|
||||
mux.Handle(roomServer.PathPrefix(), roomServer)
|
||||
mux.Handle(egressServer.PathPrefix(), egressServer)
|
||||
mux.Handle(ingressServer.PathPrefix(), ingressServer)
|
||||
|
||||
+2
-2
@@ -30,7 +30,7 @@ import (
|
||||
"github.com/livekit/livekit-server/pkg/clientconfiguration"
|
||||
"github.com/livekit/livekit-server/pkg/config"
|
||||
"github.com/livekit/livekit-server/pkg/routing"
|
||||
"github.com/livekit/livekit-server/pkg/rtc"
|
||||
"github.com/livekit/livekit-server/pkg/agent"
|
||||
"github.com/livekit/livekit-server/pkg/telemetry"
|
||||
"github.com/livekit/protocol/auth"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
@@ -77,7 +77,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
||||
NewRoomService,
|
||||
NewRTCService,
|
||||
NewAgentService,
|
||||
rtc.NewAgentClient,
|
||||
agent.NewAgentClient,
|
||||
getSignalRelayConfig,
|
||||
NewDefaultSignalServer,
|
||||
routing.NewSignalClient,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by Wire. DO NOT EDIT.
|
||||
|
||||
//go:generate go run -mod=mod github.com/google/wire/cmd/wire
|
||||
//go:generate go run github.com/google/wire/cmd/wire
|
||||
//go:build !wireinject
|
||||
// +build !wireinject
|
||||
|
||||
@@ -8,10 +8,10 @@ package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/livekit/livekit-server/pkg/agent"
|
||||
"github.com/livekit/livekit-server/pkg/clientconfiguration"
|
||||
"github.com/livekit/livekit-server/pkg/config"
|
||||
"github.com/livekit/livekit-server/pkg/routing"
|
||||
"github.com/livekit/livekit-server/pkg/rtc"
|
||||
"github.com/livekit/livekit-server/pkg/telemetry"
|
||||
"github.com/livekit/protocol/auth"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
@@ -60,7 +60,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
agentClient, err := rtc.NewAgentClient(messageBus)
|
||||
client, err := agent.NewAgentClient(messageBus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
roomService, err := NewRoomService(roomConfig, apiConfig, psrpcConfig, router, roomAllocator, objectStore, agentClient, rtcEgressLauncher, topicFormatter, roomClient, participantClient)
|
||||
roomService, err := NewRoomService(roomConfig, apiConfig, psrpcConfig, router, roomAllocator, objectStore, client, rtcEgressLauncher, topicFormatter, roomClient, participantClient)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -112,15 +112,15 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
||||
return nil, err
|
||||
}
|
||||
sipService := NewSIPService(sipConfig, nodeID, messageBus, sipClient, sipStore, roomService, telemetryService)
|
||||
rtcService := NewRTCService(conf, roomAllocator, objectStore, router, currentNode, agentClient, telemetryService)
|
||||
agentService, err := NewAgentService(messageBus)
|
||||
rtcService := NewRTCService(conf, roomAllocator, objectStore, router, currentNode, client, telemetryService)
|
||||
agentService, err := NewAgentService(conf, currentNode, messageBus, keyProvider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clientConfigurationManager := createClientConfiguration()
|
||||
timedVersionGenerator := utils.NewDefaultTimedVersionGenerator()
|
||||
turnAuthHandler := NewTURNAuthHandler(keyProvider)
|
||||
roomManager, err := NewLocalRoomManager(conf, objectStore, currentNode, router, telemetryService, clientConfigurationManager, agentClient, rtcEgressLauncher, timedVersionGenerator, turnAuthHandler, messageBus)
|
||||
roomManager, err := NewLocalRoomManager(conf, objectStore, currentNode, router, telemetryService, clientConfigurationManager, client, rtcEgressLauncher, timedVersionGenerator, turnAuthHandler, messageBus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -24,15 +24,19 @@ var (
|
||||
ConnectTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
func WithTimeout(t *testing.T, f func() string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), ConnectTimeout)
|
||||
func WithTimeout(t *testing.T, f func() string, timeouts ...time.Duration) {
|
||||
timeout := ConnectTimeout
|
||||
if len(timeouts) > 0 {
|
||||
timeout = timeouts[0]
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
lastErr := ""
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if lastErr != "" {
|
||||
t.Fatalf("did not reach expected state after %v: %s", ConnectTimeout, lastErr)
|
||||
t.Fatalf("did not reach expected state after %v: %s", timeout, lastErr)
|
||||
}
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
lastErr = f()
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright 2024 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 utils
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/frostbyte73/core"
|
||||
)
|
||||
|
||||
// IncrementalDispatcher is a dispatcher that allows multiple consumers to consume items as they become
|
||||
// available, while producers can add items at anytime.
|
||||
type IncrementalDispatcher[T any] struct {
|
||||
done core.Fuse
|
||||
lock sync.RWMutex
|
||||
cond *sync.Cond
|
||||
items []T
|
||||
}
|
||||
|
||||
func NewIncrementalDispatcher[T any]() *IncrementalDispatcher[T] {
|
||||
p := &IncrementalDispatcher[T]{}
|
||||
p.cond = sync.NewCond(&p.lock)
|
||||
return p
|
||||
}
|
||||
|
||||
func (d *IncrementalDispatcher[T]) Add(item T) {
|
||||
if d.done.IsBroken() {
|
||||
return
|
||||
}
|
||||
d.lock.Lock()
|
||||
d.items = append(d.items, item)
|
||||
d.lock.Unlock()
|
||||
d.cond.Broadcast()
|
||||
}
|
||||
|
||||
func (d *IncrementalDispatcher[T]) Done() {
|
||||
d.done.Break()
|
||||
d.cond.Broadcast()
|
||||
}
|
||||
|
||||
func (d *IncrementalDispatcher[T]) ForEach(fn func(T)) {
|
||||
idx := 0
|
||||
dispatchFromIdx := func() {
|
||||
var itemsToDispatch []T
|
||||
d.lock.RLock()
|
||||
for idx < len(d.items) {
|
||||
itemsToDispatch = append(itemsToDispatch, d.items[idx])
|
||||
idx++
|
||||
}
|
||||
d.lock.RUnlock()
|
||||
for _, item := range itemsToDispatch {
|
||||
fn(item)
|
||||
}
|
||||
}
|
||||
for !d.done.IsBroken() {
|
||||
dispatchFromIdx()
|
||||
d.lock.Lock()
|
||||
if idx == len(d.items) {
|
||||
d.cond.Wait()
|
||||
}
|
||||
d.lock.Unlock()
|
||||
}
|
||||
|
||||
dispatchFromIdx()
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright 2024 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 utils_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/testutils"
|
||||
"github.com/livekit/livekit-server/pkg/utils"
|
||||
)
|
||||
|
||||
func TestForEach(t *testing.T) {
|
||||
producer := utils.NewIncrementalDispatcher[int]()
|
||||
go func() {
|
||||
defer producer.Done()
|
||||
producer.Add(1)
|
||||
producer.Add(2)
|
||||
producer.Add(3)
|
||||
}()
|
||||
|
||||
sum := 0
|
||||
producer.ForEach(func(item int) {
|
||||
sum += item
|
||||
})
|
||||
|
||||
require.Equal(t, 6, sum)
|
||||
}
|
||||
|
||||
func TestConcurrentConsumption(t *testing.T) {
|
||||
producer := utils.NewIncrementalDispatcher[int]()
|
||||
numConsumers := 5
|
||||
sums := make([]atomic.Int32, numConsumers)
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := 0; i < numConsumers; i++ {
|
||||
wg.Add(1)
|
||||
i := i
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
producer.ForEach(func(item int) {
|
||||
sums[i].Add(int32(item))
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// Add items
|
||||
expectedSum := 0
|
||||
for i := 0; i < 20; i++ {
|
||||
expectedSum += i
|
||||
producer.Add(i)
|
||||
}
|
||||
|
||||
for i := 0; i < numConsumers; i++ {
|
||||
testutils.WithTimeout(t, func() string {
|
||||
if sums[i].Load() != int32(expectedSum) {
|
||||
return fmt.Sprintf("consumer %d did not consume all the items. expected %d, actual: %d",
|
||||
i, expectedSum, sums[i].Load())
|
||||
}
|
||||
return ""
|
||||
}, time.Second)
|
||||
}
|
||||
|
||||
// keep adding and ensure it's consumed
|
||||
for i := 20; i < 30; i++ {
|
||||
expectedSum += i
|
||||
producer.Add(i)
|
||||
}
|
||||
|
||||
// wait for all consumers to finish
|
||||
producer.Done()
|
||||
wg.Wait()
|
||||
|
||||
for i := 0; i < numConsumers; i++ {
|
||||
require.Equal(t, int32(expectedSum), sums[i].Load(), "consumer %d did not match", i)
|
||||
}
|
||||
}
|
||||
+30
-21
@@ -25,7 +25,6 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/utils"
|
||||
)
|
||||
|
||||
type agentClient struct {
|
||||
@@ -38,11 +37,13 @@ type agentClient struct {
|
||||
participantAvailability atomic.Int32
|
||||
participantJobs atomic.Int32
|
||||
|
||||
requestedJobs chan *livekit.Job
|
||||
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func newAgentClient(token string) (*agentClient, error) {
|
||||
host := fmt.Sprintf("ws://localhost:%d", defaultServerPort)
|
||||
func newAgentClient(token string, port uint32) (*agentClient, error) {
|
||||
host := fmt.Sprintf("ws://localhost:%d", port)
|
||||
u, err := url.Parse(host + "/agent")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -57,25 +58,24 @@ func newAgentClient(token string) (*agentClient, error) {
|
||||
}
|
||||
|
||||
return &agentClient{
|
||||
conn: conn,
|
||||
done: make(chan struct{}),
|
||||
conn: conn,
|
||||
requestedJobs: make(chan *livekit.Job, 100),
|
||||
done: make(chan struct{}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *agentClient) Run(jobType livekit.JobType) (err error) {
|
||||
func (c *agentClient) Run(jobType livekit.JobType, namespace string) (err error) {
|
||||
go c.read()
|
||||
|
||||
workerID := utils.NewGuid("W_")
|
||||
|
||||
switch jobType {
|
||||
case livekit.JobType_JT_ROOM:
|
||||
err = c.write(&livekit.WorkerMessage{
|
||||
Message: &livekit.WorkerMessage_Register{
|
||||
Register: &livekit.RegisterWorkerRequest{
|
||||
Type: livekit.JobType_JT_ROOM,
|
||||
WorkerId: workerID,
|
||||
Version: "version",
|
||||
Name: "name",
|
||||
Type: livekit.JobType_JT_ROOM,
|
||||
Version: "version",
|
||||
Namespace: &namespace,
|
||||
Name: "name",
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -84,10 +84,10 @@ func (c *agentClient) Run(jobType livekit.JobType) (err error) {
|
||||
err = c.write(&livekit.WorkerMessage{
|
||||
Message: &livekit.WorkerMessage_Register{
|
||||
Register: &livekit.RegisterWorkerRequest{
|
||||
Type: livekit.JobType_JT_PUBLISHER,
|
||||
WorkerId: workerID,
|
||||
Version: "version",
|
||||
Name: "name",
|
||||
Type: livekit.JobType_JT_PUBLISHER,
|
||||
Version: "version",
|
||||
Namespace: &namespace,
|
||||
Name: "name",
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -139,6 +139,8 @@ func (c *agentClient) handleAvailability(req *livekit.AvailabilityRequest) {
|
||||
c.participantAvailability.Inc()
|
||||
}
|
||||
|
||||
c.requestedJobs <- req.Job
|
||||
|
||||
c.write(&livekit.WorkerMessage{
|
||||
Message: &livekit.WorkerMessage_Availability{
|
||||
Availability: &livekit.AvailabilityResponse{
|
||||
@@ -157,16 +159,23 @@ 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
|
||||
}
|
||||
select {
|
||||
case <-c.done:
|
||||
return nil
|
||||
default:
|
||||
b, err := proto.Marshal(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.conn.WriteMessage(websocket.BinaryMessage, b)
|
||||
return c.conn.WriteMessage(websocket.BinaryMessage, b)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *agentClient) close() {
|
||||
c.mu.Lock()
|
||||
close(c.done)
|
||||
_ = c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
||||
_ = c.conn.Close()
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
+133
-21
@@ -15,72 +15,184 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/testutils"
|
||||
"github.com/livekit/protocol/auth"
|
||||
"github.com/livekit/protocol/livekit"
|
||||
)
|
||||
|
||||
var (
|
||||
RegisterTimeout = 2 * time.Second
|
||||
AssignJobTimeout = 3 * time.Second
|
||||
)
|
||||
|
||||
func TestAgents(t *testing.T) {
|
||||
_, finish := setupSingleNodeTest("TestAgents")
|
||||
defer finish()
|
||||
|
||||
ac1, err := newAgentClient(agentToken())
|
||||
|
||||
ac1, err := newAgentClient(agentToken(), defaultServerPort)
|
||||
require.NoError(t, err)
|
||||
ac2, err := newAgentClient(agentToken())
|
||||
ac2, err := newAgentClient(agentToken(), defaultServerPort)
|
||||
require.NoError(t, err)
|
||||
ac3, err := newAgentClient(agentToken())
|
||||
ac3, err := newAgentClient(agentToken(), defaultServerPort)
|
||||
require.NoError(t, err)
|
||||
ac4, err := newAgentClient(agentToken())
|
||||
ac4, err := newAgentClient(agentToken(), defaultServerPort)
|
||||
require.NoError(t, err)
|
||||
defer ac1.close()
|
||||
defer ac2.close()
|
||||
defer ac3.close()
|
||||
defer ac4.close()
|
||||
ac1.Run(livekit.JobType_JT_ROOM)
|
||||
ac2.Run(livekit.JobType_JT_ROOM)
|
||||
ac3.Run(livekit.JobType_JT_PUBLISHER)
|
||||
ac4.Run(livekit.JobType_JT_PUBLISHER)
|
||||
ac1.Run(livekit.JobType_JT_ROOM, "namespace")
|
||||
ac2.Run(livekit.JobType_JT_ROOM, "namespace")
|
||||
ac3.Run(livekit.JobType_JT_PUBLISHER, "namespace")
|
||||
ac4.Run(livekit.JobType_JT_PUBLISHER, "namespace")
|
||||
|
||||
time.Sleep(time.Second * 3)
|
||||
testutils.WithTimeout(t, func() string {
|
||||
if ac1.registered.Load() != 1 || ac2.registered.Load() != 1 || ac3.registered.Load() != 1 || ac4.registered.Load() != 1 {
|
||||
return "worker not registered"
|
||||
}
|
||||
|
||||
require.Equal(t, int32(1), ac1.registered.Load())
|
||||
require.Equal(t, int32(1), ac2.registered.Load())
|
||||
require.Equal(t, int32(1), ac3.registered.Load())
|
||||
require.Equal(t, int32(1), ac4.registered.Load())
|
||||
return ""
|
||||
}, RegisterTimeout)
|
||||
|
||||
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")
|
||||
t1, err := c1.AddStaticTrack("audio/opus", "audio", "micro")
|
||||
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)
|
||||
testutils.WithTimeout(t, func() string {
|
||||
if ac1.roomJobs.Load()+ac2.roomJobs.Load() != 1 {
|
||||
return "room job not assigned"
|
||||
}
|
||||
|
||||
require.Equal(t, int32(1), ac1.roomJobs.Load()+ac2.roomJobs.Load())
|
||||
require.Equal(t, int32(1), ac3.participantJobs.Load()+ac4.participantJobs.Load())
|
||||
if ac3.participantJobs.Load()+ac4.participantJobs.Load() != 1 {
|
||||
return fmt.Sprintf("participant jobs not assigned, ac3: %d, ac4: %d", ac3.participantJobs.Load(), ac4.participantJobs.Load())
|
||||
}
|
||||
|
||||
return ""
|
||||
}, 6 * time.Second)
|
||||
|
||||
// publish 2 tracks
|
||||
t3, err := c2.AddStaticTrack("audio/opus", "audio", "webcam")
|
||||
t3, err := c2.AddStaticTrack("audio/opus", "audio", "micro")
|
||||
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)
|
||||
testutils.WithTimeout(t, func() string {
|
||||
if ac1.roomJobs.Load()+ac2.roomJobs.Load() != 1 {
|
||||
return "room job must be assigned 1 time"
|
||||
}
|
||||
|
||||
require.Equal(t, int32(1), ac1.roomJobs.Load()+ac2.roomJobs.Load())
|
||||
require.Equal(t, int32(2), ac3.participantJobs.Load()+ac4.participantJobs.Load())
|
||||
if ac3.participantJobs.Load()+ac4.participantJobs.Load() != 2 {
|
||||
return "2 publisher jobs must assigned"
|
||||
}
|
||||
|
||||
return ""
|
||||
}, AssignJobTimeout)
|
||||
}
|
||||
|
||||
func TestAgentNamespaces(t *testing.T) {
|
||||
_, finish := setupSingleNodeTest("TestAgentNamespaces")
|
||||
defer finish()
|
||||
|
||||
ac1, err := newAgentClient(agentToken(), defaultServerPort)
|
||||
require.NoError(t, err)
|
||||
ac2, err := newAgentClient(agentToken(), defaultServerPort)
|
||||
require.NoError(t, err)
|
||||
defer ac1.close()
|
||||
defer ac2.close()
|
||||
ac1.Run(livekit.JobType_JT_ROOM, "namespace")
|
||||
ac2.Run(livekit.JobType_JT_ROOM, "namespace2")
|
||||
|
||||
testutils.WithTimeout(t, func() string {
|
||||
if ac1.registered.Load() != 1 || ac2.registered.Load() != 1 {
|
||||
return "worker not registered"
|
||||
}
|
||||
return ""
|
||||
}, RegisterTimeout)
|
||||
|
||||
c1 := createRTCClient("c1", defaultServerPort, nil)
|
||||
waitUntilConnected(t, c1)
|
||||
|
||||
testutils.WithTimeout(t, func() string {
|
||||
if ac1.roomJobs.Load() != 1 || ac2.roomJobs.Load() != 1 {
|
||||
return "room job not assigned"
|
||||
}
|
||||
|
||||
job1 := <-ac1.requestedJobs
|
||||
job2 := <-ac2.requestedJobs
|
||||
|
||||
if job1.Namespace != "namespace" {
|
||||
return "namespace is not 'namespace'"
|
||||
}
|
||||
|
||||
if job2.Namespace != "namespace2" {
|
||||
return "namespace is not 'namespace2'"
|
||||
}
|
||||
|
||||
if job1.Id == job2.Id {
|
||||
return "job ids are the same"
|
||||
}
|
||||
|
||||
return ""
|
||||
}, AssignJobTimeout)
|
||||
|
||||
}
|
||||
|
||||
func TestAgentMultiNode(t *testing.T) {
|
||||
_, _, finish := setupMultiNodeTest("TestAgentMultiNode")
|
||||
defer finish()
|
||||
|
||||
ac1, err := newAgentClient(agentToken(), defaultServerPort)
|
||||
require.NoError(t, err)
|
||||
ac2, err := newAgentClient(agentToken(), defaultServerPort)
|
||||
defer ac1.close()
|
||||
defer ac2.close()
|
||||
ac1.Run(livekit.JobType_JT_ROOM, "namespace")
|
||||
ac2.Run(livekit.JobType_JT_PUBLISHER, "namespace")
|
||||
|
||||
testutils.WithTimeout(t, func() string {
|
||||
if ac1.registered.Load() != 1 || ac2.registered.Load() != 1 {
|
||||
return "worker not registered"
|
||||
}
|
||||
return ""
|
||||
}, RegisterTimeout)
|
||||
|
||||
c1 := createRTCClient("c1", secondServerPort, nil) // Create a room on the second node
|
||||
waitUntilConnected(t, c1)
|
||||
|
||||
t1, err := c1.AddStaticTrack("audio/opus", "audio", "micro")
|
||||
require.NoError(t, err)
|
||||
defer t1.Stop()
|
||||
|
||||
time.Sleep(time.Second * 10)
|
||||
|
||||
testutils.WithTimeout(t, func() string {
|
||||
if ac1.roomJobs.Load() != 1 {
|
||||
return "room job not assigned"
|
||||
}
|
||||
|
||||
if ac2.participantJobs.Load() != 1 {
|
||||
return "participant job not assigned"
|
||||
}
|
||||
|
||||
return ""
|
||||
}, AssignJobTimeout)
|
||||
}
|
||||
|
||||
func agentToken() string {
|
||||
|
||||
Reference in New Issue
Block a user