Skip to content

Commit 5b5ad33

Browse files
committed
refactor for shared cloud agents lib
1 parent e0e8548 commit 5b5ad33

File tree

3 files changed

+276
-88
lines changed

3 files changed

+276
-88
lines changed

cmd/lk/agent.go

Lines changed: 9 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import (
1818
"context"
1919
"errors"
2020
"fmt"
21-
"net/http"
2221
"os"
2322
"path/filepath"
2423
"regexp"
@@ -30,13 +29,11 @@ import (
3029
"github.com/twitchtv/twirp"
3130
"github.com/urfave/cli/v3"
3231

33-
livekitcli "github.com/livekit/livekit-cli/v2"
3432
"github.com/livekit/livekit-cli/v2/pkg/agentfs"
3533
"github.com/livekit/livekit-cli/v2/pkg/config"
3634
"github.com/livekit/livekit-cli/v2/pkg/util"
3735
lkproto "github.com/livekit/protocol/livekit"
3836
"github.com/livekit/protocol/logger"
39-
lksdk "github.com/livekit/server-sdk-go/v2"
4037
)
4138

4239
const (
@@ -282,7 +279,7 @@ var (
282279
},
283280
}
284281
subdomainPattern = regexp.MustCompile(`^(?:https?|wss?)://([^.]+)\.`)
285-
agentsClient *lksdk.AgentClient
282+
agentsClient *agentfs.Client
286283
ignoredSecrets = []string{
287284
"LIVEKIT_API_KEY",
288285
"LIVEKIT_API_SECRET",
@@ -318,12 +315,7 @@ func createAgentClient(ctx context.Context, cmd *cli.Command) (context.Context,
318315
}
319316
}
320317

321-
agentsClient, err = lksdk.NewAgentClient(project.URL, project.APIKey, project.APISecret, twirp.WithClientHooks(&twirp.ClientHooks{
322-
RequestPrepared: func(ctx context.Context, req *http.Request) (context.Context, error) {
323-
req.Header.Set("X-LIVEKIT-CLI-VERSION", livekitcli.Version)
324-
return ctx, nil
325-
},
326-
}))
318+
agentsClient, err = agentfs.New(agentfs.WithProject(project.URL, project.APIKey, project.APISecret))
327319
if err != nil {
328320
return ctx, err
329321
}
@@ -354,7 +346,7 @@ func createAgent(ctx context.Context, cmd *cli.Command) error {
354346
}
355347
var err error
356348
// Recreate the client with the new project
357-
agentsClient, err = lksdk.NewAgentClient(project.URL, project.APIKey, project.APISecret)
349+
agentsClient, err = agentfs.New(agentfs.WithProject(project.URL, project.APIKey, project.APISecret))
358350
if err != nil {
359351
return err
360352
}
@@ -415,13 +407,8 @@ func createAgent(ctx context.Context, cmd *cli.Command) error {
415407
}
416408

417409
regions := cmd.StringSlice("regions")
418-
419-
req := &lkproto.CreateAgentRequest{
420-
Secrets: secrets,
421-
Regions: regions,
422-
}
423-
424-
resp, err := agentsClient.CreateAgent(ctx, req)
410+
excludeFiles := []string{fmt.Sprintf("**/%s", config.LiveKitTOMLFile)}
411+
resp, err := agentsClient.CreateAgent(ctx, workingDir, secrets, regions, excludeFiles)
425412
if err != nil {
426413
if twerr, ok := err.(twirp.Error); ok {
427414
if twerr.Code() == twirp.PermissionDenied {
@@ -436,16 +423,7 @@ func createAgent(ctx context.Context, cmd *cli.Command) error {
436423
return err
437424
}
438425

439-
err = agentfs.UploadTarball(workingDir, resp.PresignedUrl, []string{fmt.Sprintf("**/%s", config.LiveKitTOMLFile)}, projectType)
440-
if err != nil {
441-
return err
442-
}
443-
444426
fmt.Printf("Created agent with ID [%s]\n", util.Accented(resp.AgentId))
445-
err = agentfs.Build(ctx, resp.AgentId, project)
446-
if err != nil {
447-
return err
448-
}
449427

450428
fmt.Println("Build completed - You can view build logs later with `lk agent logs --log-type=build`")
451429

@@ -463,7 +441,7 @@ func createAgent(ctx context.Context, cmd *cli.Command) error {
463441
return err
464442
} else if viewLogs {
465443
fmt.Println("Tailing runtime logs...safe to exit at any time")
466-
return agentfs.LogHelper(ctx, lkConfig.Agent.ID, "deploy", project)
444+
return agentsClient.StreamLogs(ctx, "deploy", lkConfig.Agent.ID, os.Stdout)
467445
}
468446
}
469447
return nil
@@ -578,8 +556,8 @@ func deployAgent(ctx context.Context, cmd *cli.Command) error {
578556
}
579557
}
580558

581-
resp, err := agentsClient.DeployAgent(ctx, req)
582-
if err != nil {
559+
excludeFiles := []string{fmt.Sprintf("**/%s", config.LiveKitTOMLFile)}
560+
if err := agentsClient.DeployAgent(ctx, agentId, workingDir, secrets, excludeFiles); err != nil {
583561
if twerr, ok := err.(twirp.Error); ok {
584562
if twerr.Code() == twirp.PermissionDenied {
585563
return fmt.Errorf("agent hosting is disabled for this project -- join the beta program here [%s]", cloudAgentsBetaSignupURL)
@@ -588,22 +566,6 @@ func deployAgent(ctx context.Context, cmd *cli.Command) error {
588566
return err
589567
}
590568

591-
if !resp.Success {
592-
return fmt.Errorf("failed to deploy agent: %s", resp.Message)
593-
}
594-
595-
presignedUrl := resp.PresignedUrl
596-
err = agentfs.UploadTarball(workingDir, presignedUrl, []string{fmt.Sprintf("**/%s", config.LiveKitTOMLFile)}, projectType)
597-
if err != nil {
598-
return err
599-
}
600-
601-
fmt.Printf("Updated agent [%s]\n", util.Accented(resp.AgentId))
602-
err = agentfs.Build(ctx, resp.AgentId, project)
603-
if err != nil {
604-
return err
605-
}
606-
607569
fmt.Println("Deployed agent")
608570
return nil
609571
}
@@ -776,8 +738,7 @@ func getLogs(ctx context.Context, cmd *cli.Command) error {
776738
if err != nil {
777739
return err
778740
}
779-
err = agentfs.LogHelper(ctx, agentID, cmd.String("log-type"), project)
780-
return err
741+
return agentsClient.StreamLogs(ctx, cmd.String("log-type"), agentID, os.Stdout)
781742
}
782743

783744
func deleteAgent(ctx context.Context, cmd *cli.Command) error {

pkg/agentfs/build.go

Lines changed: 4 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -23,62 +23,26 @@ import (
2323
"net/http"
2424
"net/url"
2525
"os"
26-
"regexp"
2726
"strings"
2827

2928
bkclient "github.com/moby/buildkit/client"
3029
"github.com/moby/buildkit/util/progress/progressui"
3130
"golang.org/x/sync/errgroup"
32-
33-
"github.com/livekit/livekit-cli/v2/pkg/config"
34-
"github.com/livekit/protocol/auth"
35-
"github.com/livekit/protocol/logger"
3631
)
3732

38-
func Build(ctx context.Context, id string, projectConfig *config.ProjectConfig) error {
39-
baseUrl := projectConfig.URL
40-
if strings.HasPrefix(projectConfig.URL, "ws") {
41-
baseUrl = strings.Replace(projectConfig.URL, "ws", "http", 1)
42-
}
43-
44-
var agentsUrl string
45-
if os.Getenv("LK_AGENTS_URL") != "" {
46-
agentsUrl = os.Getenv("LK_AGENTS_URL")
47-
} else if !strings.Contains(baseUrl, "localhost") && !strings.Contains(baseUrl, "127.0.0.1") {
48-
pattern := `^https://[a-zA-Z0-9\-]+\.`
49-
re := regexp.MustCompile(pattern)
50-
agentsUrl = re.ReplaceAllString(baseUrl, "https://agents.")
51-
} else {
52-
agentsUrl = baseUrl
53-
}
54-
55-
logger.Debugw("Connecting to LK hosted agents on", "url", agentsUrl)
56-
33+
func (c *Client) Build(ctx context.Context, id string) error {
5734
params := url.Values{}
5835
params.Add("agent_id", id)
59-
fullUrl := fmt.Sprintf("%s/build?%s", agentsUrl, params.Encode())
60-
61-
at := auth.NewAccessToken(projectConfig.APIKey, projectConfig.APISecret)
62-
at.SetAgentGrant(&auth.AgentGrant{
63-
Admin: true,
64-
})
65-
token, err := at.ToJWT()
66-
if err != nil {
67-
return err
68-
}
69-
70-
req, err := http.NewRequest("POST", fullUrl, nil)
36+
fullUrl := fmt.Sprintf("%s/build?%s", c.agentsURL, params.Encode())
37+
req, err := c.newRequest("POST", fullUrl, nil)
7138
if err != nil {
7239
return err
7340
}
74-
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
75-
client := &http.Client{}
76-
resp, err := client.Do(req)
41+
resp, err := c.httpClient.Do(req)
7742
if err != nil {
7843
return err
7944
}
8045
defer resp.Body.Close()
81-
8246
if resp.StatusCode != http.StatusOK {
8347
return fmt.Errorf("failed to build agent: %s", resp.Status)
8448
}

0 commit comments

Comments
 (0)