Do not try to create an audit log file named "-"

That PR fixes --audit-log-path=- support.
It now logs to stdout as in 1.21.
This commit is contained in:
Andrew Rynhard 2021-07-23 14:26:28 +00:00
parent 9b84e473b2
commit 7728428f01
No known key found for this signature in database
GPG Key ID: 176858DA5CB2AF65
2 changed files with 38 additions and 12 deletions

View File

@ -511,21 +511,21 @@ func (o *AuditLogOptions) getWriter() (io.Writer, error) {
return nil, nil
}
if err := o.ensureLogFile(); err != nil {
return nil, err
if o.Path == "-" {
return os.Stdout, nil
}
var w io.Writer = os.Stdout
if o.Path != "-" {
w = &lumberjack.Logger{
Filename: o.Path,
MaxAge: o.MaxAge,
MaxBackups: o.MaxBackups,
MaxSize: o.MaxSize,
Compress: o.Compress,
}
if err := o.ensureLogFile(); err != nil {
return nil, fmt.Errorf("ensureLogFile: %w", err)
}
return w, nil
return &lumberjack.Logger{
Filename: o.Path,
MaxAge: o.MaxAge,
MaxBackups: o.MaxBackups,
MaxSize: o.MaxSize,
Compress: o.Compress,
}, nil
}
func (o *AuditLogOptions) ensureLogFile() error {

View File

@ -27,6 +27,7 @@ import (
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/natefinch/lumberjack.v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
"k8s.io/apiserver/pkg/server"
@ -59,6 +60,15 @@ func TestAuditValidOptions(t *testing.T) {
return o
},
expected: "ignoreErrors<log>",
}, {
name: "stdout log",
options: func() *AuditOptions {
o := NewAuditOptions()
o.LogOptions.Path = "-"
o.PolicyFile = policy
return o
},
expected: "ignoreErrors<log>",
}, {
name: "default log no policy",
options: func() *AuditOptions {
@ -147,6 +157,22 @@ func TestAuditValidOptions(t *testing.T) {
} else {
assert.Equal(t, tc.expected, fmt.Sprintf("%s", config.AuditBackend))
}
w, err := options.LogOptions.getWriter()
require.NoError(t, err, "Writer creation should not fail.")
// Don't check writer if logging is disabled.
if w == nil {
return
}
if options.LogOptions.Path == "-" {
assert.Equal(t, os.Stdout, w)
assert.NoFileExists(t, options.LogOptions.Path)
} else {
assert.IsType(t, (*lumberjack.Logger)(nil), w)
assert.FileExists(t, options.LogOptions.Path)
}
})
}
}