Skip to content

Commit 4026993

Browse files
Merge pull request #695 from jetstack/disable-events-when-not-in-cluster
[VC-43403] Disable events when not in cluster and only require installNamespace when using venafi-connection mode
2 parents d383e3c + 7c60629 commit 4026993

File tree

5 files changed

+66
-51
lines changed

5 files changed

+66
-51
lines changed

cmd/agent_test.go

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,12 @@ import (
1515
// after the first data gathering iteration.
1616
func TestAgentRunOneShot(t *testing.T) {
1717
if _, found := os.LookupEnv("GO_CHILD"); found {
18-
// Silence the warning about missing pod name for event generation
19-
// TODO(wallrj): This should not be required when an `--input-file` has been supplied.
20-
t.Setenv("POD_NAME", "venafi-kubernetes-e2e")
21-
// Silence the error about missing kubeconfig.
22-
// TODO(wallrj): This should not be required when an `--input-file` has been supplied.
23-
t.Setenv("KUBECONFIG", "testdata/agent/one-shot/success/kubeconfig.yaml")
24-
2518
os.Args = []string{
2619
"preflight",
2720
"agent",
2821
"--one-shot",
2922
// TODO(wallrj): This should not be required when an `--input-file` has been supplied.
3023
"--api-token=should-not-be-required",
31-
// TODO(wallrj): This should not be required when an `--input-file` has been supplied.
32-
"--install-namespace=default",
3324
"--agent-config-file=testdata/agent/one-shot/success/config.yaml",
3425
"--input-path=testdata/agent/one-shot/success/input.json",
3526
"--output-path=/dev/null",

cmd/testdata/agent/one-shot/success/kubeconfig.yaml

Lines changed: 0 additions & 15 deletions
This file was deleted.

pkg/agent/config.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -581,22 +581,26 @@ func ValidateAndCombineConfig(log logr.Logger, cfg Config, flags AgentCmdFlags)
581581
}
582582

583583
// Validation of --install-namespace.
584-
installNS := flags.InstallNS
585-
if flags.InstallNS == "" {
586-
var err error
587-
installNS, err = getInClusterNamespace()
588-
if err != nil {
589-
errs = multierror.Append(errs, fmt.Errorf("could not guess which namespace the agent is running in: %w", err))
584+
{
585+
installNS := flags.InstallNS
586+
if installNS == "" {
587+
var err error
588+
installNS, err = getInClusterNamespace()
589+
if err != nil {
590+
if res.TLSPKMode == VenafiCloudVenafiConnection {
591+
errs = multierror.Append(errs, fmt.Errorf("could not guess which namespace the agent is running in: %w", err))
592+
}
593+
}
590594
}
595+
res.InstallNS = installNS
591596
}
592-
res.InstallNS = installNS
593597

594598
// Validation of --venafi-connection and --venafi-connection-namespace.
595599
if res.TLSPKMode == VenafiCloudVenafiConnection {
596600
res.VenConnName = flags.VenConnName
597601
venConnNS := flags.VenConnNS
598602
if flags.VenConnNS == "" {
599-
venConnNS = installNS
603+
venConnNS = res.InstallNS
600604
}
601605
res.VenConnNS = venConnNS
602606
}

pkg/agent/config_test.go

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,15 @@ func Test_ValidateAndCombineConfig(t *testing.T) {
2525
// OAuth mode.
2626
fakeCredsPath := withFile(t, `{"user_id":"foo","user_secret":"bar","client_id": "baz","client_secret": "foobar","auth_server_domain":"bazbar"}`)
2727

28-
t.Run("--install-namespace must be provided if POD_NAMESPACE is not set", func(t *testing.T) {
28+
t.Run("In Venafi Connection mode, --install-namespace must be provided if POD_NAMESPACE is not set", func(t *testing.T) {
2929
_, _, err := ValidateAndCombineConfig(discardLogs(),
3030
withConfig(testutil.Undent(`
3131
server: https://api.venafi.eu
3232
organization_id: foo
3333
cluster_id: bar
3434
period: 5m
3535
`)),
36-
withCmdLineFlags("--credentials-file", fakeCredsPath))
36+
withCmdLineFlags("--venafi-connection", "venafi-components"))
3737
assert.EqualError(t, err, "1 error occurred:\n\t* could not guess which namespace the agent is running in: POD_NAMESPACE env var not set, meaning that you are probably not running in cluster. Please use --install-namespace or POD_NAMESPACE to specify the namespace in which the agent is running.\n\n")
3838
})
3939

@@ -615,6 +615,34 @@ func Test_ValidateAndCombineConfig(t *testing.T) {
615615
require.NoError(t, err)
616616
assert.Equal(t, VenafiCloudVenafiConnection, got.TLSPKMode)
617617
})
618+
619+
// When --input-path is supplied, the data is being read from a local file
620+
// and the agent is probably running outside the cluster and has no access
621+
// to a cluster, so the environment variables which are required for
622+
// generating events attached to the Agent pod should not be required:
623+
// POD_NAME, POD_NAMESPACE, POD_UID, KUBECONFIG, etc.
624+
// This test deliberately does not set those environment variables.
625+
//
626+
// TODO(wallrj): Some other config settings like cluster_id, organization_id
627+
// should also not be required in this situation. We'll fix those in the
628+
// future.
629+
t.Run("--input-path requires no Kubernetes config", func(t *testing.T) {
630+
expectedInputPath := "/foo/bar/baz"
631+
got, _, err := ValidateAndCombineConfig(discardLogs(),
632+
withConfig(testutil.Undent(`
633+
cluster_id: should-not-be-required
634+
organization_id: should-not-be-required
635+
`)),
636+
withCmdLineFlags(
637+
"--one-shot",
638+
"--input-path", expectedInputPath,
639+
"--output-path", "/dev/null",
640+
"--api-token", "should-not-be-required",
641+
),
642+
)
643+
require.NoError(t, err)
644+
assert.Equal(t, expectedInputPath, got.InputPath)
645+
})
618646
}
619647

620648
func Test_ValidateAndCombineConfig_VenafiCloudKeyPair(t *testing.T) {

pkg/agent/run.go

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ func Run(cmd *cobra.Command, args []string) (returnErr error) {
156156

157157
// To help users notice issues with the agent, we show the error messages in
158158
// the agent pod's events.
159-
eventf, err := newEventf(log, config.InstallNS)
159+
eventf, err := newEventf(log)
160160
if err != nil {
161161
return fmt.Errorf("failed to create event recorder: %v", err)
162162
}
@@ -260,7 +260,19 @@ func Run(cmd *cobra.Command, args []string) (returnErr error) {
260260
// POD_NAME to contain the pod name. Note that the RBAC rule allowing sending
261261
// events is attached to the pod's service account, not the impersonated service
262262
// account (venafi-connection).
263-
func newEventf(log logr.Logger, installNS string) (Eventf, error) {
263+
func newEventf(log logr.Logger) (Eventf, error) {
264+
podName := os.Getenv("POD_NAME")
265+
podNode := os.Getenv("POD_NODE")
266+
podUID := os.Getenv("POD_UID")
267+
podNamespace := os.Getenv("POD_NAMESPACE")
268+
if podName == "" || podNode == "" || podUID == "" || podNamespace == "" {
269+
log.Info(
270+
"Pod event recorder disabled",
271+
"reason", "The agent does not appear to be running in a Kubernetes cluster.",
272+
"detail", "When running in a Kubernetes cluster the following environment variables must be set: POD_NAME, POD_NODE, POD_UID, POD_NAMESPACE",
273+
)
274+
return func(eventType, reason, msg string, args ...interface{}) {}, nil
275+
}
264276
restcfg, err := kubeconfig.LoadRESTConfig("")
265277
if err != nil {
266278
return nil, fmt.Errorf("failed to load kubeconfig: %v", err)
@@ -269,22 +281,17 @@ func newEventf(log logr.Logger, installNS string) (Eventf, error) {
269281
_ = corev1.AddToScheme(scheme)
270282

271283
var eventf Eventf
272-
if os.Getenv("POD_NAME") == "" {
273-
eventf = func(eventType, reason, msg string, args ...interface{}) {}
274-
log.Error(nil, "Error messages will not show in the pod's events because the POD_NAME environment variable is empty")
275-
} else {
276-
podName := os.Getenv("POD_NAME")
277284

278-
eventClient, err := kubernetes.NewForConfig(restcfg)
279-
if err != nil {
280-
return eventf, fmt.Errorf("failed to create event client: %v", err)
281-
}
282-
broadcaster := record.NewBroadcaster()
283-
broadcaster.StartRecordingToSink(&clientgocorev1.EventSinkImpl{Interface: eventClient.CoreV1().Events(installNS)})
284-
eventRec := broadcaster.NewRecorder(scheme, corev1.EventSource{Component: "venafi-kubernetes-agent", Host: os.Getenv("POD_NODE")})
285-
eventf = func(eventType, reason, msg string, args ...interface{}) {
286-
eventRec.Eventf(&corev1.Pod{ObjectMeta: v1.ObjectMeta{Name: podName, Namespace: installNS, UID: types.UID(os.Getenv("POD_UID"))}}, eventType, reason, msg, args...)
287-
}
285+
eventClient, err := kubernetes.NewForConfig(restcfg)
286+
if err != nil {
287+
return eventf, fmt.Errorf("failed to create event client: %v", err)
288+
}
289+
broadcaster := record.NewBroadcaster()
290+
broadcaster.StartRecordingToSink(&clientgocorev1.EventSinkImpl{Interface: eventClient.CoreV1().Events(podNamespace)})
291+
eventRec := broadcaster.NewRecorder(scheme, corev1.EventSource{Component: "venafi-kubernetes-agent", Host: podNode})
292+
eventf = func(eventType, reason, msg string, args ...interface{}) {
293+
eventRec.Eventf(&corev1.Pod{ObjectMeta: v1.ObjectMeta{Name: podName, Namespace: podNamespace, UID: types.UID(podUID)}}, eventType, reason, msg, args...)
294+
288295
}
289296

290297
return eventf, nil

0 commit comments

Comments
 (0)