Implement Agents protocol addition (#2786)

This commit is contained in:
Benjamin Pracht
2024-06-27 19:20:52 -07:00
committed by GitHub
parent 6815d85c01
commit 32a4d03c9e
12 changed files with 325 additions and 171 deletions
+55 -32
View File
@@ -20,15 +20,13 @@ import (
"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/protocol/utils/guid"
"github.com/livekit/psrpc"
"google.golang.org/protobuf/types/known/emptypb"
)
const (
@@ -43,15 +41,17 @@ const (
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)
LaunchJob(ctx context.Context, desc *JobRequest)
Stop() error
}
type JobDescription struct {
type JobRequest struct {
JobType livekit.JobType
Room *livekit.Room
// only set for participant jobs
Participant *livekit.ParticipantInfo
Metadata string
Namespace string
}
type agentClient struct {
@@ -105,52 +105,75 @@ func NewAgentClient(bus psrpc.MessageBus) (Client, error) {
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
func (c *agentClient) LaunchJob(ctx context.Context, desc *JobRequest) {
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: guid.New(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)
}
if !c.isNamespaceActive(desc.Namespace, desc.JobType) {
logger.Infow("not dispatching agent job since no worker is available", "namespace", desc.Namespace, "jobType", desc.JobType)
return
}
c.workers.Submit(func() {
_, err := c.client.JobRequest(context.Background(), desc.Namespace, jobTypeTopic, &livekit.Job{
Id: utils.NewGuid(utils.AgentJobPrefix),
Type: desc.JobType,
Room: desc.Room,
Participant: desc.Participant,
Namespace: desc.Namespace,
Metadata: desc.Metadata,
})
if err != nil {
logger.Infow("failed to send job request", "error", err, "namespace", desc.Namespace, "jobType", desc.JobType)
}
})
}
func (c *agentClient) getOrCreateDispatchers() (*serverutils.IncrementalDispatcher[string], *serverutils.IncrementalDispatcher[string], bool) {
func (c *agentClient) isNamespaceActive(ns string, jobType livekit.JobType) bool {
c.mu.Lock()
defer c.mu.Unlock()
if time.Since(c.enabledExpiresAt) > EnabledCacheTTL || c.roomNamespaces == nil || c.publisherNamespaces == nil {
c.enabledExpiresAt = time.Now()
c.roomNamespaces = serverutils.NewIncrementalDispatcher[string]()
c.publisherNamespaces = serverutils.NewIncrementalDispatcher[string]()
return c.roomNamespaces, c.publisherNamespaces, true
go c.checkEnabled(c.roomNamespaces, c.publisherNamespaces)
}
return c.roomNamespaces, c.publisherNamespaces, false
target := c.roomNamespaces
if jobType == livekit.JobType_JT_PUBLISHER {
target = c.publisherNamespaces
}
c.mu.Unlock()
done := make(chan bool, 1)
go func() {
target.ForEach(func(curNs string) {
if curNs == ns {
select {
case done <- true:
default:
}
return
}
})
select {
case done <- false:
default:
}
}()
return <-done
}
func (c *agentClient) checkEnabled(ctx context.Context, roomNamespaces, publisherNamespaces *serverutils.IncrementalDispatcher[string]) {
func (c *agentClient) checkEnabled(roomNamespaces, publisherNamespaces *serverutils.IncrementalDispatcher[string]) {
defer roomNamespaces.Done()
defer publisherNamespaces.Done()
resChan, err := c.client.CheckEnabled(ctx, &rpc.CheckEnabledRequest{}, psrpc.WithRequestTimeout(CheckEnabledTimeout))
resChan, err := c.client.CheckEnabled(context.Background(), &rpc.CheckEnabledRequest{}, psrpc.WithRequestTimeout(CheckEnabledTimeout))
if err != nil {
logger.Errorw("failed to check enabled", err)
return
-86
View File
@@ -1,86 +0,0 @@
// 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)
}
+37 -14
View File
@@ -67,7 +67,7 @@ type Worker struct {
protocolVersion WorkerProtocolVersion
registered atomic.Bool
status livekit.WorkerStatus
runningJobs map[string]*Job
runningJobs map[string]*livekit.Job
onWorkerRegistered func(w *Worker)
@@ -101,7 +101,7 @@ func NewWorker(
apiSecret: apiSecret,
serverInfo: serverInfo,
closed: make(chan struct{}),
runningJobs: make(map[string]*Job),
runningJobs: make(map[string]*livekit.Job),
availability: make(map[string]chan *livekit.AvailabilityResponse),
conn: conn,
sigConn: sigConn,
@@ -134,6 +134,7 @@ func (w *Worker) ID() string {
func (w *Worker) JobType() livekit.JobType {
w.mu.Lock()
defer w.mu.Unlock()
return w.jobType
}
@@ -165,8 +166,8 @@ func (w *Worker) Registered() bool {
return w.registered.Load()
}
func (w *Worker) RunningJobs() map[string]*Job {
jobs := make(map[string]*Job, len(w.runningJobs))
func (w *Worker) RunningJobs() map[string]*livekit.Job {
jobs := make(map[string]*livekit.Job, len(w.runningJobs))
w.mu.Lock()
defer w.mu.Unlock()
for k, v := range w.runningJobs {
@@ -182,6 +183,10 @@ func (w *Worker) AssignJob(ctx context.Context, job *livekit.Job) error {
w.availability[job.Id] = availCh
w.mu.Unlock()
if job.State == nil {
job.State = &livekit.JobState{}
}
w.sendRequest(&livekit.ServerMessage{Message: &livekit.ServerMessage_Availability{
Availability: &livekit.AvailabilityRequest{Job: job},
}})
@@ -204,7 +209,12 @@ func (w *Worker) AssignJob(ctx context.Context, job *livekit.Job) error {
Assignment: &livekit.JobAssignment{Job: job, Url: nil, Token: token},
}})
// TODO(theomonnom): Check if an agent was successfully connected to the room before returning
w.mu.Lock()
w.runningJobs[job.Id] = job
w.mu.Unlock()
// TODO sweep jobs that are never started. We can't do this until all SDKs actually update the the JOB state
return nil
case <-time.After(assignJobTimeout):
return ErrAvailabilityTimeout
@@ -222,10 +232,6 @@ func (w *Worker) UpdateStatus(status *livekit.UpdateWorkerStatus) {
}
w.load = status.GetLoad()
w.mu.Unlock()
if status.Metadata != nil {
w.UpdateMetadata(status.GetMetadata())
}
}
func (w *Worker) UpdateMetadata(metadata string) {
@@ -283,10 +289,10 @@ func (w *Worker) handleRegister(req *livekit.RegisterWorkerRequest) {
w.mu.Lock()
onWorkerRegistered := w.onWorkerRegistered
w.jobType = req.Type
w.version = req.Version
w.name = req.Name
w.namespace = req.GetNamespace()
w.jobType = req.GetType()
if req.AllowedPermissions != nil {
w.permissions = req.AllowedPermissions
@@ -336,15 +342,32 @@ func (w *Worker) handleAvailability(res *livekit.AvailabilityResponse) {
func (w *Worker) handleJobUpdate(update *livekit.UpdateJobStatus) {
w.mu.Lock()
job, ok := w.runningJobs[update.JobId]
w.mu.Unlock()
defer w.mu.Unlock()
job, ok := w.runningJobs[update.JobId]
if !ok {
w.Logger.Warnw("received job update for unknown job", nil, "jobId", update.JobId)
w.Logger.Infow("received job update for unknown job", "jobId", update.JobId)
return
}
job.UpdateStatus(update)
now := time.Now()
job.State.UpdatedAt = now.UnixNano()
if job.State.Status == livekit.JobStatus_JS_PENDING && update.Status >= livekit.JobStatus_JS_RUNNING {
job.State.StartedAt = now.UnixNano()
}
if job.State.Status < livekit.JobStatus_JS_SUCCESS && update.Status >= livekit.JobStatus_JS_SUCCESS {
job.State.EndedAt = now.UnixNano()
}
job.State.Status = update.Status
job.State.Error = update.Error
// TODO do not delete, leafve inside the JobDefinition
if job.State.Status >= livekit.JobStatus_JS_SUCCESS {
delete(w.runningJobs, job.Id)
}
}
func (w *Worker) handleSimulateJob(simulate *livekit.SimulateJobRequest) {