Skip to content

Commit

Permalink
[windows] if elastic-agent run fails, log error to Application Even…
Browse files Browse the repository at this point in the history
…tLog (#4846)

* windows if `elastic-agent run` fails, log error to eventviewer

* linter fixes

* updated fragment and skip cleaning up registry

(cherry picked from commit 6c20730)

# Conflicts:
#	internal/pkg/agent/cmd/run.go
#	internal/pkg/agent/install/install_windows.go
#	internal/pkg/agent/install/uninstall.go
  • Loading branch information
leehinman authored and mergify[bot] committed Jun 13, 2024
1 parent be00750 commit 8142297
Show file tree
Hide file tree
Showing 6 changed files with 146 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Kind can be one of:
# - breaking-change: a change to previously-documented behavior
# - deprecation: functionality that is being removed in a later release
# - bug-fix: fixes a problem in a previous version
# - enhancement: extends functionality but does not break or fix existing behavior
# - feature: new functionality
# - known-issue: problems that we are aware of in a given version
# - security: impacts on the security of a product or a user’s deployment.
# - upgrade: important information for someone upgrading from a prior version
# - other: does not fit into any of the other categories
kind: enhancement

# Change summary; a 80ish characters long description of the change.
summary: Capture early errors on Windows in Application eventlog.

# Long description; in case the summary is not enough to describe the change
# this field accommodate a description without length limits.
# NOTE: This field will be rendered only for breaking-change and known-issue kinds at the moment.
#description:

# Affected component; a word indicating the component this changeset affects.
component: elastic-agent

# PR URL; optional; the PR number that added the changeset.
# If not present is automatically filled by the tooling finding the PR where this changelog fragment has been added.
# NOTE: the tooling supports backports, so it's able to fill the original PR number instead of the backport PR number.
# Please provide it if you are adding a fragment for a different PR.
pr: https://github.com/elastic/elastic-agent/pull/4846

# Issue URL; optional; the GitHub issue related to this changeset (either closes or is part of).
# If not present is automatically filled by the tooling with the issue linked to the PR number.
issue: https://github.com/elastic/elastic-agent/issues/4627
12 changes: 9 additions & 3 deletions internal/pkg/agent/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,10 @@ const (
fleetInitTimeoutName = "FLEET_SERVER_INIT_TIMEOUT"
)

type cfgOverrider func(cfg *configuration.Configuration)
type awaiters []<-chan struct{}
type (
cfgOverrider func(cfg *configuration.Configuration)
awaiters []<-chan struct{}
)

func newRunCommandWithArgs(_ []string, streams *cli.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Expand All @@ -77,7 +79,11 @@ func newRunCommandWithArgs(_ []string, streams *cli.IOStreams) *cobra.Command {
testingMode, _ := cmd.Flags().GetBool("testing-mode")
if err := run(nil, testingMode, fleetInitTimeout); err != nil && !errors.Is(err, context.Canceled) {
fmt.Fprintf(streams.Err, "Error: %v\n%s\n", err, troubleshootMessage())
<<<<<<< HEAD

Check failure on line 82 in internal/pkg/agent/cmd/run.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

expected statement, found '<<' (typecheck)

Check failure on line 82 in internal/pkg/agent/cmd/run.go

View workflow job for this annotation

GitHub Actions / lint (ubuntu-latest)

expected statement, found '<<' (typecheck)

=======
logExternal(fmt.Sprintf("%s run failed: %s", paths.BinaryName, err))
>>>>>>> 6c20730d5c ([windows] if `elastic-agent run` fails, log error to Application EventLog (#4846))

Check failure on line 86 in internal/pkg/agent/cmd/run.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

expected ';', found fails (typecheck)

Check failure on line 86 in internal/pkg/agent/cmd/run.go

View workflow job for this annotation

GitHub Actions / lint (ubuntu-latest)

expected ';', found fails (typecheck)
return err

Check failure on line 87 in internal/pkg/agent/cmd/run.go

View workflow job for this annotation

GitHub Actions / lint (macos-latest)

expected '{', found 'return' (typecheck)

Check failure on line 87 in internal/pkg/agent/cmd/run.go

View workflow job for this annotation

GitHub Actions / lint (ubuntu-latest)

expected '{', found 'return' (typecheck)
}
return nil
Expand Down Expand Up @@ -128,7 +134,7 @@ func run(override cfgOverrider, testingMode bool, fleetInitTimeout time.Duration
// register as a service
stop := make(chan bool)
ctx, cancel := context.WithCancel(context.Background())
var stopBeat = func() {
stopBeat := func() {
close(stop)
}

Expand Down
11 changes: 11 additions & 0 deletions internal/pkg/agent/cmd/run_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.

//go:build !windows

package cmd

// logExternal logs the error to an external log. On non-windows systems this is a no-op.
func logExternal(msg string) {
}
24 changes: 24 additions & 0 deletions internal/pkg/agent/cmd/run_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.

//go:build windows

package cmd

import (
"golang.org/x/sys/windows/svc/eventlog"

"github.com/elastic/elastic-agent/internal/pkg/agent/application/paths"
)

// logExternal logs the error to an external log. On Windows this is
// the Application EventLog. This is a best effort logger and no
// errors are returned.
func logExternal(msg string) {
eLog, err2 := eventlog.Open(paths.ServiceName)
if err2 != nil {
return
}
_ = eLog.Error(1, msg)
}
66 changes: 66 additions & 0 deletions internal/pkg/agent/install/install_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,14 @@ package install
import (
"os"
"path/filepath"
"strings"

<<<<<<< HEAD
=======
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc/eventlog"

>>>>>>> 6c20730d5c ([windows] if `elastic-agent run` fails, log error to Application EventLog (#4846))
"github.com/elastic/elastic-agent/internal/pkg/agent/application/paths"
"github.com/elastic/elastic-agent/pkg/utils"
"github.com/elastic/elastic-agent/version"
Expand Down Expand Up @@ -45,6 +52,65 @@ func postInstall(topPath string) error {
}

func fixInstallMarkerPermissions(markerFilePath string, ownership utils.FileOwner) error {
<<<<<<< HEAD
// TODO(blakerouse): Fix the market permissions on Windows.
=======
return perms.FixPermissions(markerFilePath, perms.WithOwnership(ownership))
}

// withServiceOptions just sets the user/group for the service.
func withServiceOptions(username string, groupName string) ([]serviceOpt, error) {
if username == "" {
// not installed with --unprivileged; nothing to do
return []serviceOpt{}, nil
}

// service requires a password to launch as the user
// this sets it to a random password that is only known by the service
password, err := RandomPassword()
if err != nil {
return nil, fmt.Errorf("failed to generate random password: %w", err)
}
err = SetUserPassword(username, password)
if err != nil {
return nil, fmt.Errorf("failed to set user %s password for service: %w", username, err)
}

// username must be prefixed with `.\` so the service references the local systems users
username = fmt.Sprintf(`.\%s`, username)
return []serviceOpt{withUserGroup(username, groupName), withPassword(password)}, nil
}

// serviceConfigure sets the security descriptor for the service
//
// gives user the ability to control the service, needed when installed with --unprivileged or
// ReExec is not possible on Windows.
func serviceConfigure(ownership utils.FileOwner) error {
// Modify registry to allow logging to eventlog as "Elastic Agent".
err := eventlog.InstallAsEventCreate(paths.ServiceName, eventlog.Info|eventlog.Warning|eventlog.Error)
if err != nil && !strings.Contains(err.Error(), "registry key already exists") {
return fmt.Errorf("unable to create registry key for logging: %w", err)
}
// https://learn.microsoft.com/en-us/windows-hardware/drivers/kernel/sddl-for-device-objects
sddl := "D:(A;;GA;;;SY)" + // SDDL_LOCAL_SYSTEM -> SDDL_GENERIC_ALL
"(A;;GA;;;BA)" + // SDDL_BUILTIN_ADMINISTRATORS -> SDDL_GENERIC_ALL
"(A;;GR;;;WD)" + // SDDL_EVERYONE -> SDDL_GENERIC_READ
"(A;;GRGX;;;NS)" // SDDL_NETWORK_SERVICE -> SDDL_GENERIC_READ|SDDL_GENERIC_EXECUTE
if ownership.UID != "" {
sddl += fmt.Sprintf("(A;;GA;;;%s)", ownership.UID) // Ownership UID -> SDDL_GENERIC_ALL
}
securityDescriptor, err := windows.SecurityDescriptorFromString(sddl)
if err != nil {
return fmt.Errorf("failed to build security descriptor from SSDL: %w", err)
}
dacl, _, err := securityDescriptor.DACL()
if err != nil {
return fmt.Errorf("failed to get DACL from security descriptor: %w", err)
}
err = windows.SetNamedSecurityInfo(paths.ServiceName, windows.SE_SERVICE, windows.DACL_SECURITY_INFORMATION, nil, nil, dacl, nil)
if err != nil {
return fmt.Errorf("failed to set DACL for service(%s): %w", paths.ServiceName, err)
}
>>>>>>> 6c20730d5c ([windows] if `elastic-agent run` fails, log error to Application EventLog (#4846))
return nil
}
4 changes: 4 additions & 0 deletions internal/pkg/agent/install/uninstall.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,12 @@ func containsString(str string, a []string, caseSensitive bool) bool {
return false
}

<<<<<<< HEAD
func uninstallComponents(ctx context.Context, cfgFile string, uninstallToken string, log *logp.Logger, pt *progressbar.ProgressBar) error {

=======
func uninstallComponents(ctx context.Context, cfgFile string, uninstallToken string, log *logp.Logger, pt *progressbar.ProgressBar, unprivileged bool) error {
>>>>>>> 6c20730d5c ([windows] if `elastic-agent run` fails, log error to Application EventLog (#4846))
platform, err := component.LoadPlatformDetail()
if err != nil {
return fmt.Errorf("failed to gather system information: %w", err)
Expand Down

0 comments on commit 8142297

Please sign in to comment.