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/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-20240302142739-1c3dd691a1b8
|
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/livekit/psrpc v0.5.3-0.20240327035954-cec3a0e614be
|
||||||
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
|
||||||
|
|||||||
@@ -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/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 h1:xawydPEACNO5Ncs2LgioTjWghXQ0eUN1q1RnVUUyVnI=
|
||||||
github.com/livekit/mediatransportutil v0.0.0-20240302142739-1c3dd691a1b8/go.mod h1:jwKUCmObuiEDH0iiuJHaGMXwRs3RjrB4G6qqgkr/5oE=
|
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.20240403204952-bc6c7ffd71f0 h1:BfQN4k6YG+XTdfbXnA2XZLAXinRNlJrGdTLAjyOW2Rg=
|
||||||
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/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 h1:W1nCFZ19rYAORMBNX82NeVPHjADN0UyORr6refbUXpU=
|
||||||
github.com/livekit/psrpc v0.5.3-0.20240327035954-cec3a0e614be/go.mod h1:CQUBSPfYYAaevg1TNCc6/aYsa8DJH4jSRFdCeSZk5u0=
|
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=
|
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/livekit"
|
||||||
"github.com/livekit/protocol/logger"
|
"github.com/livekit/protocol/logger"
|
||||||
"github.com/livekit/protocol/rpc"
|
|
||||||
"github.com/livekit/protocol/utils"
|
"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/config"
|
||||||
"github.com/livekit/livekit-server/pkg/routing"
|
"github.com/livekit/livekit-server/pkg/routing"
|
||||||
"github.com/livekit/livekit-server/pkg/rtc/types"
|
"github.com/livekit/livekit-server/pkg/rtc/types"
|
||||||
@@ -103,8 +103,7 @@ type Room struct {
|
|||||||
trackManager *RoomTrackManager
|
trackManager *RoomTrackManager
|
||||||
|
|
||||||
// agents
|
// agents
|
||||||
agentClient AgentClient
|
agentClient agent.Client
|
||||||
publisherAgentsEnabled bool
|
|
||||||
|
|
||||||
// map of identity -> Participant
|
// map of identity -> Participant
|
||||||
participants map[livekit.ParticipantIdentity]types.LocalParticipant
|
participants map[livekit.ParticipantIdentity]types.LocalParticipant
|
||||||
@@ -142,7 +141,7 @@ func NewRoom(
|
|||||||
audioConfig *config.AudioConfig,
|
audioConfig *config.AudioConfig,
|
||||||
serverInfo *livekit.ServerInfo,
|
serverInfo *livekit.ServerInfo,
|
||||||
telemetry telemetry.TelemetryService,
|
telemetry telemetry.TelemetryService,
|
||||||
agentClient AgentClient,
|
agentClient agent.Client,
|
||||||
egressLauncher EgressLauncher,
|
egressLauncher EgressLauncher,
|
||||||
) *Room {
|
) *Room {
|
||||||
r := &Room{
|
r := &Room{
|
||||||
@@ -183,21 +182,6 @@ func NewRoom(
|
|||||||
}
|
}
|
||||||
r.protoProxy = utils.NewProtoProxy[*livekit.Room](roomUpdateInterval, r.updateProto)
|
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.audioUpdateWorker()
|
||||||
go r.connectionQualityWorker()
|
go r.connectionQualityWorker()
|
||||||
go r.changeUpdateWorker()
|
go r.changeUpdateWorker()
|
||||||
@@ -1013,13 +997,10 @@ func (r *Room) onTrackPublished(participant types.LocalParticipant, track types.
|
|||||||
r.lock.Lock()
|
r.lock.Lock()
|
||||||
hasPublished := r.hasPublished[participant.Identity()]
|
hasPublished := r.hasPublished[participant.Identity()]
|
||||||
r.hasPublished[participant.Identity()] = true
|
r.hasPublished[participant.Identity()] = true
|
||||||
publisherAgentsEnabled := r.publisherAgentsEnabled
|
|
||||||
r.lock.Unlock()
|
r.lock.Unlock()
|
||||||
|
|
||||||
if !hasPublished {
|
if !hasPublished {
|
||||||
if publisherAgentsEnabled {
|
r.launchPublisherAgent(participant)
|
||||||
r.launchPublisherAgent(participant)
|
|
||||||
}
|
|
||||||
if r.internal != nil && r.internal.ParticipantEgress != nil {
|
if r.internal != nil && r.internal.ParticipantEgress != nil {
|
||||||
go func() {
|
go func() {
|
||||||
if err := StartParticipantEgress(
|
if err := StartParticipantEgress(
|
||||||
@@ -1429,18 +1410,15 @@ func (r *Room) simulationCleanupWorker() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Room) launchPublisherAgent(p types.Participant) {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go r.agentClient.LaunchJob(context.Background(), &agent.JobDescription{
|
||||||
r.agentClient.JobRequest(context.Background(), &livekit.Job{
|
JobType: livekit.JobType_JT_PUBLISHER,
|
||||||
Id: utils.NewGuid("JP_"),
|
Room: r.ToProto(),
|
||||||
Type: livekit.JobType_JT_PUBLISHER,
|
Participant: p.ToProto(),
|
||||||
Room: r.ToProto(),
|
})
|
||||||
Participant: p.ToProto(),
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Room) DebugInfo() map[string]interface{} {
|
func (r *Room) DebugInfo() map[string]interface{} {
|
||||||
|
|||||||
@@ -586,3 +586,4 @@ type OperationMonitor interface {
|
|||||||
Check() error
|
Check() error
|
||||||
IsIdle() bool
|
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");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@@ -20,6 +20,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -27,16 +28,19 @@ import (
|
|||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
"google.golang.org/protobuf/types/known/emptypb"
|
"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"
|
||||||
|
"github.com/livekit/livekit-server/pkg/rtc/types"
|
||||||
"github.com/livekit/livekit-server/pkg/utils"
|
"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/livekit"
|
||||||
"github.com/livekit/protocol/logger"
|
|
||||||
"github.com/livekit/protocol/rpc"
|
"github.com/livekit/protocol/rpc"
|
||||||
"github.com/livekit/psrpc"
|
"github.com/livekit/psrpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
const AgentServiceVersion = "0.1.0"
|
|
||||||
|
|
||||||
type AgentService struct {
|
type AgentService struct {
|
||||||
upgrader websocket.Upgrader
|
upgrader websocket.Upgrader
|
||||||
|
|
||||||
@@ -44,38 +48,30 @@ type AgentService struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AgentHandler struct {
|
type AgentHandler struct {
|
||||||
agentServer rpc.AgentInternalServer
|
agentServer rpc.AgentInternalServer
|
||||||
roomTopic string
|
mu sync.Mutex
|
||||||
publisherTopic string
|
|
||||||
|
|
||||||
mu sync.Mutex
|
serverInfo *livekit.ServerInfo
|
||||||
availability map[string]chan *availability
|
workers map[string]*agent.Worker
|
||||||
unregistered map[*websocket.Conn]*worker
|
keyProvider auth.KeyProvider
|
||||||
roomRegistered bool
|
|
||||||
roomWorkers map[string]*worker
|
namespaces map[string]*namespaceInfo
|
||||||
publisherRegistered bool
|
publisherEnabled bool
|
||||||
publisherWorkers map[string]*worker
|
roomEnabled bool
|
||||||
onWorkerRegistered func(handler *AgentHandler)
|
roomTopic string
|
||||||
|
publisherTopic string
|
||||||
}
|
}
|
||||||
|
|
||||||
type worker struct {
|
type namespaceInfo struct {
|
||||||
mu sync.Mutex
|
numPublishers int32
|
||||||
conn *websocket.Conn
|
numRooms int32
|
||||||
sigConn *WSSignalConnection
|
|
||||||
|
|
||||||
id string
|
|
||||||
jobType livekit.JobType
|
|
||||||
status livekit.WorkerStatus
|
|
||||||
activeJobs int
|
|
||||||
logger logger.Logger
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type availability struct {
|
func NewAgentService(conf *config.Config,
|
||||||
workerID string
|
currentNode routing.LocalNode,
|
||||||
available bool
|
bus psrpc.MessageBus,
|
||||||
}
|
keyProvider auth.KeyProvider,
|
||||||
|
) (*AgentService, error) {
|
||||||
func NewAgentService(bus psrpc.MessageBus) (*AgentService, error) {
|
|
||||||
s := &AgentService{
|
s := &AgentService{
|
||||||
upgrader: websocket.Upgrader{},
|
upgrader: websocket.Upgrader{},
|
||||||
}
|
}
|
||||||
@@ -86,12 +82,26 @@ func NewAgentService(bus psrpc.MessageBus) (*AgentService, error) {
|
|||||||
return true
|
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)
|
agentServer, err := rpc.NewAgentInternalServer(s, bus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
s.AgentHandler = NewAgentHandler(agentServer, rtc.RoomAgentTopic, rtc.PublisherAgentTopic)
|
s.AgentHandler = NewAgentHandler(
|
||||||
|
agentServer,
|
||||||
|
keyProvider,
|
||||||
|
serverInfo,
|
||||||
|
agent.RoomAgentTopic,
|
||||||
|
agent.PublisherAgentTopic,
|
||||||
|
)
|
||||||
return s, nil
|
return s, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,64 +126,64 @@ func (s *AgentService) ServeHTTP(writer http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
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{
|
return &AgentHandler{
|
||||||
agentServer: agentServer,
|
agentServer: agentServer,
|
||||||
roomTopic: roomTopic,
|
workers: make(map[string]*agent.Worker),
|
||||||
publisherTopic: publisherTopic,
|
namespaces: make(map[string]*namespaceInfo),
|
||||||
availability: make(map[string]chan *availability),
|
serverInfo: serverInfo,
|
||||||
unregistered: make(map[*websocket.Conn]*worker),
|
keyProvider: keyProvider,
|
||||||
roomWorkers: make(map[string]*worker),
|
roomTopic: roomTopic,
|
||||||
publisherWorkers: make(map[string]*worker),
|
publisherTopic: publisherTopic,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnWorkerRegistered registers a callback to be called when the first worker of each type is registered
|
func (h *AgentHandler) HandleConnection(r *http.Request, conn *websocket.Conn, onIdle func()) {
|
||||||
func (s *AgentHandler) OnWorkerRegistered(handler func(handler *AgentHandler)) {
|
var protocol agent.WorkerProtocolVersion
|
||||||
s.mu.Lock()
|
if pv, err := strconv.Atoi(r.FormValue("protocol")); err == nil {
|
||||||
defer s.mu.Unlock()
|
protocol = agent.WorkerProtocolVersion(pv)
|
||||||
s.onWorkerRegistered = handler
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func (s *AgentHandler) HandleConnection(ctx context.Context, conn *websocket.Conn) {
|
|
||||||
sigConn := NewWSSignalConnection(conn)
|
sigConn := NewWSSignalConnection(conn)
|
||||||
w := &worker{
|
|
||||||
conn: conn,
|
|
||||||
sigConn: sigConn,
|
|
||||||
logger: utils.GetLogger(ctx),
|
|
||||||
}
|
|
||||||
|
|
||||||
s.mu.Lock()
|
logger := utils.GetLogger(r.Context())
|
||||||
s.unregistered[conn] = w
|
|
||||||
s.mu.Unlock()
|
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() {
|
defer func() {
|
||||||
s.mu.Lock()
|
worker.Close()
|
||||||
if w.id == "" {
|
|
||||||
delete(s.unregistered, conn)
|
h.mu.Lock()
|
||||||
} else {
|
delete(h.workers, worker.ID())
|
||||||
switch w.jobType {
|
numWorkers := len(h.workers)
|
||||||
case livekit.JobType_JT_ROOM:
|
h.mu.Unlock()
|
||||||
delete(s.roomWorkers, w.id)
|
|
||||||
if s.roomRegistered && !s.roomAvailableLocked() {
|
if worker.Registered() {
|
||||||
s.roomRegistered = false
|
h.deregisterWorkerTopic(worker)
|
||||||
s.agentServer.DeregisterJobRequestTopic(s.roomTopic)
|
}
|
||||||
}
|
|
||||||
case livekit.JobType_JT_PUBLISHER:
|
if numWorkers == 0 && onIdle != nil {
|
||||||
delete(s.publisherWorkers, w.id)
|
onIdle()
|
||||||
if s.publisherRegistered && !s.publisherAvailableLocked() {
|
|
||||||
s.publisherRegistered = false
|
|
||||||
s.agentServer.DeregisterJobRequestTopic(s.publisherTopic)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
s.mu.Unlock()
|
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// handle incoming requests from websocket
|
|
||||||
for {
|
for {
|
||||||
req, _, err := sigConn.ReadWorkerMessage()
|
req, _, err := sigConn.ReadWorkerMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -188,321 +198,220 @@ func (s *AgentHandler) HandleConnection(ctx context.Context, conn *websocket.Con
|
|||||||
websocket.CloseNormalClosure,
|
websocket.CloseNormalClosure,
|
||||||
websocket.CloseNoStatusReceived,
|
websocket.CloseNoStatusReceived,
|
||||||
) {
|
) {
|
||||||
w.logger.Infow("Agent worker closed WS connection", "wsError", err)
|
worker.Logger.Infow("worker closed WS connection", "wsError", err)
|
||||||
} else {
|
} else {
|
||||||
w.logger.Errorw("error reading from websocket", err)
|
worker.Logger.Errorw("error reading from websocket", err)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
switch m := req.Message.(type) {
|
worker.HandleMessage(req)
|
||||||
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) {
|
func (h *AgentHandler) registerWorkerTopic(w *agent.Worker) {
|
||||||
if err := s.doHandleRegister(worker, msg); err != nil {
|
h.mu.Lock()
|
||||||
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()
|
|
||||||
|
|
||||||
|
info, ok := h.namespaces[w.Namespace()]
|
||||||
|
numPublishers := int32(0)
|
||||||
|
numRooms := int32(0)
|
||||||
if ok {
|
if ok {
|
||||||
availabilityChan <- &availability{
|
numPublishers = info.numPublishers
|
||||||
workerID: w.id,
|
numRooms = info.numRooms
|
||||||
available: msg.Available,
|
}
|
||||||
|
|
||||||
|
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) {
|
if err != nil {
|
||||||
switch msg.Status {
|
w.Logger.Errorw("failed to register job request topic", err)
|
||||||
case livekit.JobStatus_JS_SUCCESS:
|
h.mu.Unlock()
|
||||||
w.logger.Debugw("job complete", "jobID", msg.JobId)
|
w.Close() // Close the worker
|
||||||
case livekit.JobStatus_JS_FAILED:
|
return
|
||||||
w.logger.Warnw("job failed", errors.New(msg.Error), "jobID", msg.JobId)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
w.mu.Lock()
|
h.namespaces[w.Namespace()] = &namespaceInfo{
|
||||||
w.activeJobs--
|
numPublishers: numPublishers,
|
||||||
w.mu.Unlock()
|
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) {
|
func (h *AgentHandler) deregisterWorkerTopic(worker *agent.Worker) {
|
||||||
s.mu.Lock()
|
h.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer h.mu.Unlock()
|
||||||
|
|
||||||
w.mu.Lock()
|
info, ok := h.namespaces[worker.Namespace()]
|
||||||
w.status = msg.Status
|
if !ok {
|
||||||
w.mu.Unlock()
|
return
|
||||||
|
}
|
||||||
|
|
||||||
switch w.jobType {
|
if worker.JobType() == livekit.JobType_JT_PUBLISHER {
|
||||||
case livekit.JobType_JT_ROOM:
|
info.numPublishers--
|
||||||
if s.roomRegistered && !s.roomAvailableLocked() {
|
if info.numPublishers == 0 {
|
||||||
s.roomRegistered = false
|
h.agentServer.DeregisterJobRequestTopic(worker.Namespace(), h.publisherTopic)
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
case livekit.JobType_JT_PUBLISHER:
|
} else if worker.JobType() == livekit.JobType_JT_ROOM {
|
||||||
if s.publisherRegistered && !s.publisherAvailableLocked() {
|
info.numRooms--
|
||||||
s.publisherRegistered = false
|
if info.numRooms == 0 {
|
||||||
s.agentServer.DeregisterJobRequestTopic(s.publisherTopic)
|
h.agentServer.DeregisterJobRequestTopic(worker.Namespace(), h.roomTopic)
|
||||||
} 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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func (s *AgentHandler) CheckEnabled(_ context.Context, _ *rpc.CheckEnabledRequest) (*rpc.CheckEnabledResponse, error) {
|
if info.numPublishers == 0 && info.numRooms == 0 {
|
||||||
s.mu.Lock()
|
delete(h.namespaces, worker.Namespace())
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)
|
attempted := make(map[string]bool)
|
||||||
for {
|
for {
|
||||||
select {
|
h.mu.Lock()
|
||||||
case <-ctx.Done():
|
var selected *agent.Worker
|
||||||
return nil, psrpc.NewErrorf(psrpc.DeadlineExceeded, "request timed out")
|
var maxLoad float32
|
||||||
default:
|
for _, w := range h.workers {
|
||||||
s.mu.Lock()
|
if w.Namespace() != job.Namespace || w.JobType() != job.Type {
|
||||||
var selected *worker
|
continue
|
||||||
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
|
_, ok := attempted[w.ID()]
|
||||||
_, err := selected.sigConn.WriteServerMessage(&livekit.ServerMessage{Message: &livekit.ServerMessage_Availability{
|
if ok {
|
||||||
Availability: &livekit.AvailabilityRequest{Job: job},
|
continue
|
||||||
}})
|
|
||||||
if err != nil {
|
|
||||||
selected.logger.Errorw("failed to send availability request", err, "workerID", selected.id)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
select {
|
if w.Status() == livekit.WorkerStatus_WS_AVAILABLE {
|
||||||
case <-ctx.Done():
|
load := w.Load()
|
||||||
return nil, psrpc.NewErrorf(psrpc.DeadlineExceeded, "request timed out")
|
if len(w.RunningJobs()) > 0 && load > maxLoad {
|
||||||
case res := <-ac:
|
maxLoad = load
|
||||||
if res.available {
|
selected = w
|
||||||
_, err = selected.sigConn.WriteServerMessage(&livekit.ServerMessage{Message: &livekit.ServerMessage_Assignment{
|
} else if selected == nil {
|
||||||
Assignment: &livekit.JobAssignment{Job: job},
|
selected = w
|
||||||
}})
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
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 {
|
func (h *AgentHandler) JobRequestAffinity(ctx context.Context, job *livekit.Job) float32 {
|
||||||
s.mu.Lock()
|
h.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer h.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
|
|
||||||
}
|
|
||||||
|
|
||||||
var affinity float32
|
var affinity float32
|
||||||
for _, w := range pool {
|
var maxLoad float32
|
||||||
if w.status == livekit.WorkerStatus_WS_AVAILABLE {
|
for _, w := range h.workers {
|
||||||
if w.activeJobs > 0 {
|
if w.Namespace() != job.Namespace || w.JobType() != job.Type {
|
||||||
return 1
|
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 {
|
} else {
|
||||||
affinity = 0.5
|
affinity = 0.5
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return affinity
|
return affinity
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AgentHandler) NumConnections() int {
|
func (h *AgentHandler) CheckEnabled(ctx context.Context, req *rpc.CheckEnabledRequest) (*rpc.CheckEnabledResponse, error) {
|
||||||
s.mu.Lock()
|
h.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
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
|
// jitter drain start
|
||||||
time.Sleep(time.Duration(rand.Int63n(int64(interval))))
|
time.Sleep(time.Duration(rand.Int63n(int64(interval))))
|
||||||
|
|
||||||
t := time.NewTicker(interval)
|
t := time.NewTicker(interval)
|
||||||
defer t.Stop()
|
defer t.Stop()
|
||||||
|
|
||||||
s.mu.Lock()
|
h.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer h.mu.Unlock()
|
||||||
|
|
||||||
for conn := range s.unregistered {
|
for _, w := range h.workers {
|
||||||
_ = conn.Close()
|
w.Close()
|
||||||
<-t.C
|
|
||||||
}
|
|
||||||
for _, w := range s.roomWorkers {
|
|
||||||
_ = w.conn.Close()
|
|
||||||
<-t.C
|
|
||||||
}
|
|
||||||
for _, w := range s.publisherWorkers {
|
|
||||||
_ = w.conn.Close()
|
|
||||||
<-t.C
|
<-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 grantsKey struct{}
|
||||||
|
|
||||||
|
type grantsValue struct {
|
||||||
|
claims *auth.ClaimGrants
|
||||||
|
apiKey string
|
||||||
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrPermissionDenied = errors.New("permissions denied")
|
ErrPermissionDenied = errors.New("permissions denied")
|
||||||
ErrMissingAuthorization = errors.New("invalid authorization header. Must start with " + bearerPrefix)
|
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
|
// set grants in context
|
||||||
ctx := r.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)
|
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 {
|
func GetGrants(ctx context.Context) *auth.ClaimGrants {
|
||||||
val := ctx.Value(grantsKey{})
|
val := ctx.Value(grantsKey{})
|
||||||
claims, ok := val.(*auth.ClaimGrants)
|
v, ok := val.(*grantsValue)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return claims
|
return v.claims
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithGrants(ctx context.Context, grants *auth.ClaimGrants) context.Context {
|
func GetAPIKey(ctx context.Context) string {
|
||||||
return context.WithValue(ctx, grantsKey{}, grants)
|
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) {
|
func SetAuthorizationToken(r *http.Request, token string) {
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"golang.org/x/exp/maps"
|
"golang.org/x/exp/maps"
|
||||||
|
|
||||||
|
"github.com/livekit/livekit-server/pkg/agent"
|
||||||
"github.com/livekit/mediatransportutil/pkg/rtcconfig"
|
"github.com/livekit/mediatransportutil/pkg/rtcconfig"
|
||||||
"github.com/livekit/protocol/auth"
|
"github.com/livekit/protocol/auth"
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
@@ -70,7 +71,7 @@ type RoomManager struct {
|
|||||||
roomStore ObjectStore
|
roomStore ObjectStore
|
||||||
telemetry telemetry.TelemetryService
|
telemetry telemetry.TelemetryService
|
||||||
clientConfManager clientconfiguration.ClientConfigurationManager
|
clientConfManager clientconfiguration.ClientConfigurationManager
|
||||||
agentClient rtc.AgentClient
|
agentClient agent.Client
|
||||||
egressLauncher rtc.EgressLauncher
|
egressLauncher rtc.EgressLauncher
|
||||||
versionGenerator utils.TimedVersionGenerator
|
versionGenerator utils.TimedVersionGenerator
|
||||||
turnAuthHandler *TURNAuthHandler
|
turnAuthHandler *TURNAuthHandler
|
||||||
@@ -91,7 +92,7 @@ func NewLocalRoomManager(
|
|||||||
router routing.Router,
|
router routing.Router,
|
||||||
telemetry telemetry.TelemetryService,
|
telemetry telemetry.TelemetryService,
|
||||||
clientConfManager clientconfiguration.ClientConfigurationManager,
|
clientConfManager clientconfiguration.ClientConfigurationManager,
|
||||||
agentClient rtc.AgentClient,
|
agentClient agent.Client,
|
||||||
egressLauncher rtc.EgressLauncher,
|
egressLauncher rtc.EgressLauncher,
|
||||||
versionGenerator utils.TimedVersionGenerator,
|
versionGenerator utils.TimedVersionGenerator,
|
||||||
turnAuthHandler *TURNAuthHandler,
|
turnAuthHandler *TURNAuthHandler,
|
||||||
@@ -121,11 +122,12 @@ func NewLocalRoomManager(
|
|||||||
iceConfigCache: make(map[livekit.ParticipantIdentity]*iceConfigCacheEntry),
|
iceConfigCache: make(map[livekit.ParticipantIdentity]*iceConfigCacheEntry),
|
||||||
|
|
||||||
serverInfo: &livekit.ServerInfo{
|
serverInfo: &livekit.ServerInfo{
|
||||||
Edition: livekit.ServerInfo_Standard,
|
Edition: livekit.ServerInfo_Standard,
|
||||||
Version: version.Version,
|
Version: version.Version,
|
||||||
Protocol: types.CurrentProtocol,
|
Protocol: types.CurrentProtocol,
|
||||||
Region: conf.Region,
|
AgentProtocol: agent.CurrentProtocol,
|
||||||
NodeId: currentNode.Id,
|
Region: conf.Region,
|
||||||
|
NodeId: currentNode.Id,
|
||||||
},
|
},
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-17
@@ -22,12 +22,12 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/twitchtv/twirp"
|
"github.com/twitchtv/twirp"
|
||||||
|
|
||||||
|
"github.com/livekit/livekit-server/pkg/agent"
|
||||||
"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/rtc"
|
"github.com/livekit/livekit-server/pkg/rtc"
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
"github.com/livekit/protocol/rpc"
|
"github.com/livekit/protocol/rpc"
|
||||||
"github.com/livekit/protocol/utils"
|
|
||||||
"github.com/livekit/psrpc"
|
"github.com/livekit/psrpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ type RoomService struct {
|
|||||||
router routing.MessageRouter
|
router routing.MessageRouter
|
||||||
roomAllocator RoomAllocator
|
roomAllocator RoomAllocator
|
||||||
roomStore ServiceStore
|
roomStore ServiceStore
|
||||||
agentClient rtc.AgentClient
|
agentClient agent.Client
|
||||||
egressLauncher rtc.EgressLauncher
|
egressLauncher rtc.EgressLauncher
|
||||||
topicFormatter rpc.TopicFormatter
|
topicFormatter rpc.TopicFormatter
|
||||||
roomClient rpc.TypedRoomClient
|
roomClient rpc.TypedRoomClient
|
||||||
@@ -53,7 +53,7 @@ func NewRoomService(
|
|||||||
router routing.MessageRouter,
|
router routing.MessageRouter,
|
||||||
roomAllocator RoomAllocator,
|
roomAllocator RoomAllocator,
|
||||||
serviceStore ServiceStore,
|
serviceStore ServiceStore,
|
||||||
agentClient rtc.AgentClient,
|
agentClient agent.Client,
|
||||||
egressLauncher rtc.EgressLauncher,
|
egressLauncher rtc.EgressLauncher,
|
||||||
topicFormatter rpc.TopicFormatter,
|
topicFormatter rpc.TopicFormatter,
|
||||||
roomClient rpc.TypedRoomClient,
|
roomClient rpc.TypedRoomClient,
|
||||||
@@ -101,13 +101,10 @@ func (s *RoomService) CreateRoom(ctx context.Context, req *livekit.CreateRoomReq
|
|||||||
defer res.ResponseSource.Close()
|
defer res.ResponseSource.Close()
|
||||||
|
|
||||||
if created {
|
if created {
|
||||||
go func() {
|
go s.agentClient.LaunchJob(ctx, &agent.JobDescription{
|
||||||
s.agentClient.JobRequest(ctx, &livekit.Job{
|
JobType: livekit.JobType_JT_ROOM,
|
||||||
Id: utils.NewGuid("JR_"),
|
Room: rm,
|
||||||
Type: livekit.JobType_JT_ROOM,
|
})
|
||||||
Room: rm,
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
|
|
||||||
if req.Egress != nil && req.Egress.Room != nil {
|
if req.Egress != nil && req.Egress.Room != nil {
|
||||||
_, err = s.egressLauncher.StartEgress(ctx, &rpc.StartEgressRequest{
|
_, err = s.egressLauncher.StartEgress(ctx, &rpc.StartEgressRequest{
|
||||||
@@ -301,13 +298,10 @@ func (s *RoomService) UpdateRoomMetadata(ctx context.Context, req *livekit.Updat
|
|||||||
}
|
}
|
||||||
|
|
||||||
if created {
|
if created {
|
||||||
go func() {
|
go s.agentClient.LaunchJob(ctx, &agent.JobDescription{
|
||||||
s.agentClient.JobRequest(ctx, &livekit.Job{
|
JobType: livekit.JobType_JT_ROOM,
|
||||||
Id: utils.NewGuid("JR_"),
|
Room: room,
|
||||||
Type: livekit.JobType_JT_ROOM,
|
})
|
||||||
Room: room,
|
|
||||||
})
|
|
||||||
}()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return room, nil
|
return room, nil
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func TestDeleteRoom(t *testing.T) {
|
|||||||
grant := &auth.ClaimGrants{
|
grant := &auth.ClaimGrants{
|
||||||
Video: &auth.VideoGrant{},
|
Video: &auth.VideoGrant{},
|
||||||
}
|
}
|
||||||
ctx := service.WithGrants(context.Background(), grant)
|
ctx := service.WithGrants(context.Background(), grant, "")
|
||||||
_, err := svc.DeleteRoom(ctx, &livekit.DeleteRoomRequest{
|
_, err := svc.DeleteRoom(ctx, &livekit.DeleteRoomRequest{
|
||||||
Room: "testroom",
|
Room: "testroom",
|
||||||
})
|
})
|
||||||
@@ -52,7 +52,7 @@ func TestMetaDataLimits(t *testing.T) {
|
|||||||
grant := &auth.ClaimGrants{
|
grant := &auth.ClaimGrants{
|
||||||
Video: &auth.VideoGrant{},
|
Video: &auth.VideoGrant{},
|
||||||
}
|
}
|
||||||
ctx := service.WithGrants(context.Background(), grant)
|
ctx := service.WithGrants(context.Background(), grant, "")
|
||||||
_, err := svc.UpdateParticipant(ctx, &livekit.UpdateParticipantRequest{
|
_, err := svc.UpdateParticipant(ctx, &livekit.UpdateParticipantRequest{
|
||||||
Room: "testroom",
|
Room: "testroom",
|
||||||
Identity: "123",
|
Identity: "123",
|
||||||
@@ -82,7 +82,7 @@ func TestMetaDataLimits(t *testing.T) {
|
|||||||
grant := &auth.ClaimGrants{
|
grant := &auth.ClaimGrants{
|
||||||
Video: &auth.VideoGrant{},
|
Video: &auth.VideoGrant{},
|
||||||
}
|
}
|
||||||
ctx := service.WithGrants(context.Background(), grant)
|
ctx := service.WithGrants(context.Background(), grant, "")
|
||||||
_, err := svc.UpdateParticipant(ctx, &livekit.UpdateParticipantRequest{
|
_, err := svc.UpdateParticipant(ctx, &livekit.UpdateParticipantRequest{
|
||||||
Room: "testroom",
|
Room: "testroom",
|
||||||
Identity: "123",
|
Identity: "123",
|
||||||
|
|||||||
+10
-13
@@ -32,6 +32,7 @@ import (
|
|||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
"golang.org/x/exp/maps"
|
"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/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"
|
||||||
@@ -40,7 +41,6 @@ import (
|
|||||||
"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/livekit-server/pkg/utils"
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
putil "github.com/livekit/protocol/utils"
|
|
||||||
"github.com/livekit/psrpc"
|
"github.com/livekit/psrpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ type RTCService struct {
|
|||||||
isDev bool
|
isDev bool
|
||||||
limits config.LimitConfig
|
limits config.LimitConfig
|
||||||
parser *uaparser.Parser
|
parser *uaparser.Parser
|
||||||
agentClient rtc.AgentClient
|
agentClient agent.Client
|
||||||
telemetry telemetry.TelemetryService
|
telemetry telemetry.TelemetryService
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
@@ -67,7 +67,7 @@ func NewRTCService(
|
|||||||
store ServiceStore,
|
store ServiceStore,
|
||||||
router routing.MessageRouter,
|
router routing.MessageRouter,
|
||||||
currentNode routing.LocalNode,
|
currentNode routing.LocalNode,
|
||||||
agentClient rtc.AgentClient,
|
agentClient agent.Client,
|
||||||
telemetry telemetry.TelemetryService,
|
telemetry telemetry.TelemetryService,
|
||||||
) *RTCService {
|
) *RTCService {
|
||||||
s := &RTCService{
|
s := &RTCService{
|
||||||
@@ -524,6 +524,13 @@ func (s *RTCService) startConnection(
|
|||||||
return cr, nil, err
|
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
|
// this needs to be started first *before* using router functions on this node
|
||||||
cr.StartParticipantSignalResults, err = s.router.StartParticipantSignal(ctx, roomName, pi)
|
cr.StartParticipantSignalResults, err = s.router.StartParticipantSignal(ctx, roomName, pi)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -541,16 +548,6 @@ func (s *RTCService) startConnection(
|
|||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -125,6 +125,7 @@ func NewLivekitServer(conf *config.Config,
|
|||||||
mux.HandleFunc("/debug/goroutine", s.debugGoroutines)
|
mux.HandleFunc("/debug/goroutine", s.debugGoroutines)
|
||||||
mux.HandleFunc("/debug/rooms", s.debugInfo)
|
mux.HandleFunc("/debug/rooms", s.debugInfo)
|
||||||
}
|
}
|
||||||
|
|
||||||
mux.Handle(roomServer.PathPrefix(), roomServer)
|
mux.Handle(roomServer.PathPrefix(), roomServer)
|
||||||
mux.Handle(egressServer.PathPrefix(), egressServer)
|
mux.Handle(egressServer.PathPrefix(), egressServer)
|
||||||
mux.Handle(ingressServer.PathPrefix(), ingressServer)
|
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/clientconfiguration"
|
||||||
"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/rtc"
|
"github.com/livekit/livekit-server/pkg/agent"
|
||||||
"github.com/livekit/livekit-server/pkg/telemetry"
|
"github.com/livekit/livekit-server/pkg/telemetry"
|
||||||
"github.com/livekit/protocol/auth"
|
"github.com/livekit/protocol/auth"
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
@@ -77,7 +77,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
|||||||
NewRoomService,
|
NewRoomService,
|
||||||
NewRTCService,
|
NewRTCService,
|
||||||
NewAgentService,
|
NewAgentService,
|
||||||
rtc.NewAgentClient,
|
agent.NewAgentClient,
|
||||||
getSignalRelayConfig,
|
getSignalRelayConfig,
|
||||||
NewDefaultSignalServer,
|
NewDefaultSignalServer,
|
||||||
routing.NewSignalClient,
|
routing.NewSignalClient,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Code generated by Wire. DO NOT EDIT.
|
// 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
|
//go:build !wireinject
|
||||||
// +build !wireinject
|
// +build !wireinject
|
||||||
|
|
||||||
@@ -8,10 +8,10 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/livekit/livekit-server/pkg/agent"
|
||||||
"github.com/livekit/livekit-server/pkg/clientconfiguration"
|
"github.com/livekit/livekit-server/pkg/clientconfiguration"
|
||||||
"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/rtc"
|
|
||||||
"github.com/livekit/livekit-server/pkg/telemetry"
|
"github.com/livekit/livekit-server/pkg/telemetry"
|
||||||
"github.com/livekit/protocol/auth"
|
"github.com/livekit/protocol/auth"
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
@@ -60,7 +60,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
agentClient, err := rtc.NewAgentClient(messageBus)
|
client, err := agent.NewAgentClient(messageBus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -95,7 +95,7 @@ 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, agentClient, rtcEgressLauncher, topicFormatter, roomClient, participantClient)
|
roomService, err := NewRoomService(roomConfig, apiConfig, psrpcConfig, router, roomAllocator, objectStore, client, rtcEgressLauncher, topicFormatter, roomClient, participantClient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -112,15 +112,15 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
sipService := NewSIPService(sipConfig, nodeID, messageBus, sipClient, sipStore, roomService, telemetryService)
|
sipService := NewSIPService(sipConfig, nodeID, messageBus, sipClient, sipStore, roomService, telemetryService)
|
||||||
rtcService := NewRTCService(conf, roomAllocator, objectStore, router, currentNode, agentClient, telemetryService)
|
rtcService := NewRTCService(conf, roomAllocator, objectStore, router, currentNode, client, telemetryService)
|
||||||
agentService, err := NewAgentService(messageBus)
|
agentService, err := NewAgentService(conf, currentNode, messageBus, keyProvider)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
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, agentClient, rtcEgressLauncher, timedVersionGenerator, turnAuthHandler, messageBus)
|
roomManager, err := NewLocalRoomManager(conf, objectStore, currentNode, router, telemetryService, clientConfigurationManager, client, rtcEgressLauncher, timedVersionGenerator, turnAuthHandler, messageBus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,15 +24,19 @@ var (
|
|||||||
ConnectTimeout = 30 * time.Second
|
ConnectTimeout = 30 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
func WithTimeout(t *testing.T, f func() string) {
|
func WithTimeout(t *testing.T, f func() string, timeouts ...time.Duration) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), ConnectTimeout)
|
timeout := ConnectTimeout
|
||||||
|
if len(timeouts) > 0 {
|
||||||
|
timeout = timeouts[0]
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
lastErr := ""
|
lastErr := ""
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
if lastErr != "" {
|
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):
|
case <-time.After(10 * time.Millisecond):
|
||||||
lastErr = f()
|
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"
|
"google.golang.org/protobuf/proto"
|
||||||
|
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
"github.com/livekit/protocol/utils"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type agentClient struct {
|
type agentClient struct {
|
||||||
@@ -38,11 +37,13 @@ type agentClient struct {
|
|||||||
participantAvailability atomic.Int32
|
participantAvailability atomic.Int32
|
||||||
participantJobs atomic.Int32
|
participantJobs atomic.Int32
|
||||||
|
|
||||||
|
requestedJobs chan *livekit.Job
|
||||||
|
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func newAgentClient(token string) (*agentClient, error) {
|
func newAgentClient(token string, port uint32) (*agentClient, error) {
|
||||||
host := fmt.Sprintf("ws://localhost:%d", defaultServerPort)
|
host := fmt.Sprintf("ws://localhost:%d", port)
|
||||||
u, err := url.Parse(host + "/agent")
|
u, err := url.Parse(host + "/agent")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -57,25 +58,24 @@ func newAgentClient(token string) (*agentClient, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &agentClient{
|
return &agentClient{
|
||||||
conn: conn,
|
conn: conn,
|
||||||
done: make(chan struct{}),
|
requestedJobs: make(chan *livekit.Job, 100),
|
||||||
|
done: make(chan struct{}),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *agentClient) Run(jobType livekit.JobType) (err error) {
|
func (c *agentClient) Run(jobType livekit.JobType, namespace string) (err error) {
|
||||||
go c.read()
|
go c.read()
|
||||||
|
|
||||||
workerID := utils.NewGuid("W_")
|
|
||||||
|
|
||||||
switch jobType {
|
switch jobType {
|
||||||
case livekit.JobType_JT_ROOM:
|
case livekit.JobType_JT_ROOM:
|
||||||
err = c.write(&livekit.WorkerMessage{
|
err = c.write(&livekit.WorkerMessage{
|
||||||
Message: &livekit.WorkerMessage_Register{
|
Message: &livekit.WorkerMessage_Register{
|
||||||
Register: &livekit.RegisterWorkerRequest{
|
Register: &livekit.RegisterWorkerRequest{
|
||||||
Type: livekit.JobType_JT_ROOM,
|
Type: livekit.JobType_JT_ROOM,
|
||||||
WorkerId: workerID,
|
Version: "version",
|
||||||
Version: "version",
|
Namespace: &namespace,
|
||||||
Name: "name",
|
Name: "name",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -84,10 +84,10 @@ func (c *agentClient) Run(jobType livekit.JobType) (err error) {
|
|||||||
err = c.write(&livekit.WorkerMessage{
|
err = c.write(&livekit.WorkerMessage{
|
||||||
Message: &livekit.WorkerMessage_Register{
|
Message: &livekit.WorkerMessage_Register{
|
||||||
Register: &livekit.RegisterWorkerRequest{
|
Register: &livekit.RegisterWorkerRequest{
|
||||||
Type: livekit.JobType_JT_PUBLISHER,
|
Type: livekit.JobType_JT_PUBLISHER,
|
||||||
WorkerId: workerID,
|
Version: "version",
|
||||||
Version: "version",
|
Namespace: &namespace,
|
||||||
Name: "name",
|
Name: "name",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -139,6 +139,8 @@ func (c *agentClient) handleAvailability(req *livekit.AvailabilityRequest) {
|
|||||||
c.participantAvailability.Inc()
|
c.participantAvailability.Inc()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.requestedJobs <- req.Job
|
||||||
|
|
||||||
c.write(&livekit.WorkerMessage{
|
c.write(&livekit.WorkerMessage{
|
||||||
Message: &livekit.WorkerMessage_Availability{
|
Message: &livekit.WorkerMessage_Availability{
|
||||||
Availability: &livekit.AvailabilityResponse{
|
Availability: &livekit.AvailabilityResponse{
|
||||||
@@ -157,16 +159,23 @@ func (c *agentClient) write(msg *livekit.WorkerMessage) error {
|
|||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
b, err := proto.Marshal(msg)
|
select {
|
||||||
if err != nil {
|
case <-c.done:
|
||||||
return err
|
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() {
|
func (c *agentClient) close() {
|
||||||
|
c.mu.Lock()
|
||||||
close(c.done)
|
close(c.done)
|
||||||
_ = c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
_ = c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
||||||
_ = c.conn.Close()
|
_ = c.conn.Close()
|
||||||
|
c.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|||||||
+133
-21
@@ -15,72 +15,184 @@
|
|||||||
package test
|
package test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"github.com/livekit/livekit-server/pkg/testutils"
|
||||||
"github.com/livekit/protocol/auth"
|
"github.com/livekit/protocol/auth"
|
||||||
"github.com/livekit/protocol/livekit"
|
"github.com/livekit/protocol/livekit"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
RegisterTimeout = 2 * time.Second
|
||||||
|
AssignJobTimeout = 3 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
func TestAgents(t *testing.T) {
|
func TestAgents(t *testing.T) {
|
||||||
_, finish := setupSingleNodeTest("TestAgents")
|
_, finish := setupSingleNodeTest("TestAgents")
|
||||||
defer finish()
|
defer finish()
|
||||||
|
|
||||||
ac1, err := newAgentClient(agentToken())
|
|
||||||
|
ac1, err := newAgentClient(agentToken(), defaultServerPort)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
ac2, err := newAgentClient(agentToken())
|
ac2, err := newAgentClient(agentToken(), defaultServerPort)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
ac3, err := newAgentClient(agentToken())
|
ac3, err := newAgentClient(agentToken(), defaultServerPort)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
ac4, err := newAgentClient(agentToken())
|
ac4, err := newAgentClient(agentToken(), defaultServerPort)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer ac1.close()
|
defer ac1.close()
|
||||||
defer ac2.close()
|
defer ac2.close()
|
||||||
defer ac3.close()
|
defer ac3.close()
|
||||||
defer ac4.close()
|
defer ac4.close()
|
||||||
ac1.Run(livekit.JobType_JT_ROOM)
|
ac1.Run(livekit.JobType_JT_ROOM, "namespace")
|
||||||
ac2.Run(livekit.JobType_JT_ROOM)
|
ac2.Run(livekit.JobType_JT_ROOM, "namespace")
|
||||||
ac3.Run(livekit.JobType_JT_PUBLISHER)
|
ac3.Run(livekit.JobType_JT_PUBLISHER, "namespace")
|
||||||
ac4.Run(livekit.JobType_JT_PUBLISHER)
|
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())
|
return ""
|
||||||
require.Equal(t, int32(1), ac2.registered.Load())
|
}, RegisterTimeout)
|
||||||
require.Equal(t, int32(1), ac3.registered.Load())
|
|
||||||
require.Equal(t, int32(1), ac4.registered.Load())
|
|
||||||
|
|
||||||
c1 := createRTCClient("c1", defaultServerPort, nil)
|
c1 := createRTCClient("c1", defaultServerPort, nil)
|
||||||
c2 := createRTCClient("c2", defaultServerPort, nil)
|
c2 := createRTCClient("c2", defaultServerPort, nil)
|
||||||
waitUntilConnected(t, c1, c2)
|
waitUntilConnected(t, c1, c2)
|
||||||
|
|
||||||
// publish 2 tracks
|
// publish 2 tracks
|
||||||
t1, err := c1.AddStaticTrack("audio/opus", "audio", "webcam")
|
t1, err := c1.AddStaticTrack("audio/opus", "audio", "micro")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer t1.Stop()
|
defer t1.Stop()
|
||||||
t2, err := c1.AddStaticTrack("video/vp8", "video", "webcam")
|
t2, err := c1.AddStaticTrack("video/vp8", "video", "webcam")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer t2.Stop()
|
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())
|
if ac3.participantJobs.Load()+ac4.participantJobs.Load() != 1 {
|
||||||
require.Equal(t, int32(1), ac3.participantJobs.Load()+ac4.participantJobs.Load())
|
return fmt.Sprintf("participant jobs not assigned, ac3: %d, ac4: %d", ac3.participantJobs.Load(), ac4.participantJobs.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}, 6 * time.Second)
|
||||||
|
|
||||||
// publish 2 tracks
|
// publish 2 tracks
|
||||||
t3, err := c2.AddStaticTrack("audio/opus", "audio", "webcam")
|
t3, err := c2.AddStaticTrack("audio/opus", "audio", "micro")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer t3.Stop()
|
defer t3.Stop()
|
||||||
t4, err := c2.AddStaticTrack("video/vp8", "video", "webcam")
|
t4, err := c2.AddStaticTrack("video/vp8", "video", "webcam")
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer t4.Stop()
|
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())
|
if ac3.participantJobs.Load()+ac4.participantJobs.Load() != 2 {
|
||||||
require.Equal(t, int32(2), ac3.participantJobs.Load()+ac4.participantJobs.Load())
|
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 {
|
func agentToken() string {
|
||||||
|
|||||||
Reference in New Issue
Block a user