Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/main' into becca/display-from-…
Browse files Browse the repository at this point in the history
…socket
  • Loading branch information
RebeccaMahany committed Feb 8, 2024
2 parents 926766d + 18ea1da commit ccbd41d
Show file tree
Hide file tree
Showing 22 changed files with 334 additions and 144 deletions.
82 changes: 43 additions & 39 deletions cmd/launcher/desktop.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@ import (
"flag"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"os/user"
"runtime"
"time"

"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/kolide/kit/logutil"
"github.com/kolide/kit/ulid"
"github.com/kolide/launcher/ee/agent"
runnerserver "github.com/kolide/launcher/ee/desktop/runner/server"
Expand Down Expand Up @@ -75,61 +73,67 @@ func runDesktop(args []string) error {
return fmt.Errorf("parsing flags: %w", err)
}

// set up logging
logger := logutil.NewServerLogger(*fldebug)
logger = log.With(logger,
logLevel := slog.LevelInfo
if *fldebug {
logLevel = slog.LevelDebug
}

slogger := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
AddSource: true,
Level: logLevel,
})).With(
"subprocess", "desktop",
"session_pid", os.Getpid(),
)

// Try to get the current user, so we can use the UID for logging. Not a fatal error if we can't, though
user, err := user.Current()
if err != nil {
level.Debug(logger).Log(
"msg", "error getting current user",
slogger.Log(context.TODO(), slog.LevelDebug,
"error getting current user",
"err", err,
)
} else {
logger = log.With(logger,
"uid", user.Uid,
)
slogger = slogger.With("uid", user.Uid)
}

level.Info(logger).Log("msg", "starting")
slogger.Log(context.TODO(), slog.LevelInfo,
"starting",
)

if *flUserServerSocketPath == "" {
*flUserServerSocketPath = defaultUserServerSocketPath()
level.Info(logger).Log(
"msg", "using default socket path since none was provided",
slogger.Log(context.TODO(), slog.LevelInfo,
"using default socket path since none was provided",
"socket_path", *flUserServerSocketPath,
)
}

runGroup := rungroup.NewRunGroup(logger)
runGroup := rungroup.NewRunGroup(slogger)

// listen for signals
runGroup.Add("desktopSignalListener", func() error {
listenSignals(logger)
listenSignals(slogger)
return nil
}, func(error) {})

// Set up notification sending and listening
notifier := notify.NewDesktopNotifier(logger, *flIconPath)
notifier := notify.NewDesktopNotifier(slogger, *flIconPath)
runGroup.Add("desktopNotifier", notifier.Listen, notifier.Interrupt)

// monitor parent
runGroup.Add("desktopMonitorParentProcess", func() error {
monitorParentProcess(logger, *flRunnerServerUrl, *flRunnerServerAuthToken, 2*time.Second)
monitorParentProcess(slogger, *flRunnerServerUrl, *flRunnerServerAuthToken, 2*time.Second)
return nil
}, func(error) {})

shutdownChan := make(chan struct{})
server, err := userserver.New(logger, *flUserServerAuthToken, *flUserServerSocketPath, shutdownChan, notifier)
server, err := userserver.New(slogger, *flUserServerAuthToken, *flUserServerSocketPath, shutdownChan, notifier)
if err != nil {
return err
}

m := menu.New(logger, *flhostname, *flmenupath)
m := menu.New(slogger, *flhostname, *flmenupath)
refreshMenu := func() {
m.Build()
}
Expand All @@ -140,8 +144,8 @@ func runDesktop(args []string) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
level.Error(logger).Log(
"msg", "shutting down server",
slogger.Log(context.TODO(), slog.LevelError,
"shutting down server",
"err", err,
)
}
Expand All @@ -157,16 +161,16 @@ func runDesktop(args []string) error {

// notify runner server when menu opened
runGroup.Add("desktopMenuOpenedListener", func() error {
notifyRunnerServerMenuOpened(logger, *flRunnerServerUrl, *flRunnerServerAuthToken)
notifyRunnerServerMenuOpened(slogger, *flRunnerServerUrl, *flRunnerServerAuthToken)
return nil
}, func(err error) {})

// run run group
go func() {
// have to run this in a goroutine because menu needs the main thread
if err := runGroup.Run(); err != nil {
level.Error(logger).Log(
"msg", "running run group",
slogger.Log(context.TODO(), slog.LevelError,
"running run group",
"err", err,
)
}
Expand All @@ -178,20 +182,20 @@ func runDesktop(args []string) error {
return nil
}

func listenSignals(logger log.Logger) {
func listenSignals(slogger *slog.Logger) {
signalsToHandle := []os.Signal{os.Interrupt, os.Kill}
signals := make(chan os.Signal, len(signalsToHandle))
signal.Notify(signals, signalsToHandle...)

sig := <-signals

level.Debug(logger).Log(
"msg", "received signal",
slogger.Log(context.TODO(), slog.LevelDebug,
"received signal",
"signal", sig,
)
}

func notifyRunnerServerMenuOpened(logger log.Logger, rootServerUrl, authToken string) {
func notifyRunnerServerMenuOpened(slogger *slog.Logger, rootServerUrl, authToken string) {
client := authedclient.New(authToken, 2*time.Second)
menuOpendUrl := fmt.Sprintf("%s%s", rootServerUrl, runnerserver.MenuOpenedEndpoint)

Expand All @@ -200,8 +204,8 @@ func notifyRunnerServerMenuOpened(logger log.Logger, rootServerUrl, authToken st

response, err := client.Get(menuOpendUrl)
if err != nil {
level.Error(logger).Log(
"msg", "sending menu opened request to root server",
slogger.Log(context.TODO(), slog.LevelError,
"sending menu opened request to root server",
"err", err,
)
}
Expand All @@ -213,7 +217,7 @@ func notifyRunnerServerMenuOpened(logger log.Logger, rootServerUrl, authToken st
}

// monitorParentProcess continuously checks to see if parent is a live and sends on provided channel if it is not
func monitorParentProcess(logger log.Logger, runnerServerUrl, runnerServerAuthToken string, interval time.Duration) {
func monitorParentProcess(slogger *slog.Logger, runnerServerUrl, runnerServerAuthToken string, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()

Expand All @@ -227,8 +231,8 @@ func monitorParentProcess(logger log.Logger, runnerServerUrl, runnerServerAuthTo
for ; true; <-ticker.C {
// check to to ensure that the ppid is still legit
if os.Getppid() < 2 {
level.Debug(logger).Log(
"msg", "ppid is 0 or 1, exiting",
slogger.Log(context.TODO(), slog.LevelDebug,
"ppid is 0 or 1, exiting",
)
break
}
Expand All @@ -255,8 +259,8 @@ func monitorParentProcess(logger log.Logger, runnerServerUrl, runnerServerAuthTo

// retry
if errCount < maxErrCount {
level.Debug(logger).Log(
"msg", "could not connect to parent, will retry",
slogger.Log(context.TODO(), slog.LevelDebug,
"could not connect to parent, will retry",
"err", err,
"attempts", errCount,
"max_attempts", maxErrCount,
Expand All @@ -265,9 +269,9 @@ func monitorParentProcess(logger log.Logger, runnerServerUrl, runnerServerAuthTo
continue
}

// errCount => maxErrCount, exit
level.Debug(logger).Log(
"msg", "could not connect to parent, max attempts reached, exiting",
// errCount >= maxErrCount, exit
slogger.Log(context.TODO(), slog.LevelDebug,
"could not connect to parent, max attempts reached, exiting",
"err", err,
"attempts", errCount,
"max_attempts", maxErrCount,
Expand Down
9 changes: 7 additions & 2 deletions cmd/launcher/desktop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package main
import (
"context"
"io"
"log/slog"
"net/http"
"testing"
"time"

"github.com/go-kit/kit/log"
runnerserver "github.com/kolide/launcher/ee/desktop/runner/server"
"github.com/kolide/launcher/pkg/log/multislogger"
"github.com/kolide/launcher/pkg/threadsafebuffer"
Expand All @@ -24,8 +24,13 @@ func Test_desktopMonitorParentProcess(t *testing.T) { //nolint:paralleltest
monitorInterval := 250 * time.Millisecond
var logBytes threadsafebuffer.ThreadSafeBuffer

slogger := slog.New(slog.NewTextHandler(&logBytes, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelDebug,
}))

go func() {
monitorParentProcess(log.NewLogfmtLogger(&logBytes), runnerServer.Url(), token, monitorInterval)
monitorParentProcess(slogger, runnerServer.Url(), token, monitorInterval)
}()

time.Sleep(monitorInterval * 2)
Expand Down
2 changes: 1 addition & 1 deletion cmd/launcher/launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func runLauncher(ctx context.Context, cancel func(), multiSlogger, systemMultiSl
}

// create a rungroup for all the actors we create to allow for easy start/stop
runGroup := rungroup.NewRunGroup(logger)
runGroup := rungroup.NewRunGroup(slogger)

// Need to set up the log shipper so that we can get the logger early
// and pass it to the various systems.
Expand Down
7 changes: 7 additions & 0 deletions ee/debug/checkups/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"os"
"path/filepath"
"runtime"

"github.com/kolide/launcher/ee/agent/types"
)
Expand Down Expand Up @@ -46,6 +47,12 @@ func (c *Logs) Run(_ context.Context, fullFH io.Writer) error {
defer logZip.Close()

matches, _ := filepath.Glob(filepath.Join(c.k.RootDirectory(), "debug*"))

if runtime.GOOS == "darwin" {
stdMatches, _ := filepath.Glob("/var/log/kolide-k2/*")
matches = append(matches, stdMatches...)
}

for _, f := range matches {
out, err := logZip.Create(filepath.Base(f))
if err != nil {
Expand Down
5 changes: 2 additions & 3 deletions ee/desktop/user/client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ import (
"strings"
"testing"

"github.com/go-kit/kit/log"

"github.com/kolide/launcher/ee/desktop/user/server"
"github.com/kolide/launcher/pkg/log/multislogger"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -43,7 +42,7 @@ func TestClient_GetAndShutdown(t *testing.T) {

socketPath := testSocketPath(t)
shutdownChan := make(chan struct{})
server, err := server.New(log.NewNopLogger(), validAuthToken, socketPath, shutdownChan, nil)
server, err := server.New(multislogger.New().Logger, validAuthToken, socketPath, shutdownChan, nil)
require.NoError(t, err)

go func() {
Expand Down
8 changes: 6 additions & 2 deletions ee/desktop/user/menu/action_flare.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package menu

import (
"github.com/go-kit/kit/log/level"
"context"
"log/slog"
)

// actionFlare performs the launcher flare action. This will make more sense once flare is uploading
Expand All @@ -11,7 +12,10 @@ type actionFlare struct {

func (a actionFlare) Perform(m *menu) {
if err := runFlare(); err != nil {
level.Error(m.logger).Log("msg", "error creating flare", "err", err)
m.slogger.Log(context.TODO(), slog.LevelError,
"error creating flare",
"err", err,
)
}
}

Expand Down
24 changes: 13 additions & 11 deletions ee/desktop/user/menu/action_message.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ package menu

import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"time"

"github.com/go-kit/kit/log/level"
"github.com/kolide/launcher/ee/desktop/runner/server"
"github.com/kolide/launcher/pkg/authedclient"
)
Expand All @@ -22,16 +23,16 @@ type actionMessage struct {
func (a actionMessage) Perform(m *menu) {
runnerServerUrl := os.Getenv("RUNNER_SERVER_URL")
if runnerServerUrl == "" {
level.Error(m.logger).Log(
"msg", "runner server url not set",
m.slogger.Log(context.TODO(), slog.LevelError,
"runner server url not set",
)
return
}

runnerServerAuthToken := os.Getenv("RUNNER_SERVER_AUTH_TOKEN")
if runnerServerAuthToken == "" {
level.Error(m.logger).Log(
"msg", "runner server auth token not set",
m.slogger.Log(context.TODO(), slog.LevelError,
"runner server auth token not set",
)
return
}
Expand All @@ -41,17 +42,18 @@ func (a actionMessage) Perform(m *menu) {

jsonBody, err := json.Marshal(a)
if err != nil {
level.Error(m.logger).Log(
"msg", "failed to marshal message body",
m.slogger.Log(context.TODO(), slog.LevelError,
"failed to marshal message body",
"err", err,
)

return
}

response, err := client.Post(runnerMessageUrl, "application/json", bytes.NewReader(jsonBody))
if err != nil {
level.Error(m.logger).Log(
"msg", "failed to perform message action",
m.slogger.Log(context.TODO(), slog.LevelError,
"failed to perform message action",
"method", a.Method,
"params", a.Params,
"err", err,
Expand All @@ -65,8 +67,8 @@ func (a actionMessage) Perform(m *menu) {
}

if response.StatusCode != http.StatusOK {
level.Error(m.logger).Log(
"msg", "failed to perform message action",
m.slogger.Log(context.TODO(), slog.LevelError,
"failed to perform message action",
"method", a.Method,
"params", a.Params,
"status_code", response.StatusCode,
Expand Down
Loading

0 comments on commit ccbd41d

Please sign in to comment.