-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Still provide an owner even when /etc/passwd doesn't have the UID (#16)
Especially for using in Docker where USER is otherwise unaccompanied by a `mkuser` or `useradd` or similar RUN call.
- Loading branch information
Showing
2 changed files
with
61 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package tracing | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"os" | ||
"os/user" | ||
|
||
"go.opentelemetry.io/otel/sdk/resource" | ||
semconv "go.opentelemetry.io/otel/semconv/v1.12.0" | ||
) | ||
|
||
type safeProcessOwnerProvider struct{} | ||
|
||
var _ resource.Detector = safeProcessOwnerProvider{} | ||
|
||
func (safeProcessOwnerProvider) Detect(context.Context) (*resource.Resource, error) { | ||
// Re-implement the username logic of | ||
// https://cs.opensource.google/go/go/+/refs/tags/go1.19.5:src/os/user/lookup_stubs.go | ||
// so we can use the same rules in CGO mode as well. | ||
username := os.Getenv("USER") | ||
if u, err := user.Current(); err == nil { | ||
username = u.Username | ||
} | ||
|
||
// Instead of returning an empty user, just convert the ID number to a string | ||
// and use that -- so we always provide some sort of user. (Like the 'id' program | ||
// would do.) This will allow us tostill provide some form of owner attribute | ||
// regardless of any mismatch amongst the Docker USER parameter, the | ||
// /etc/passwd file, the Kubernetes runAsUser setting... | ||
if username == "" { | ||
// ...but on Windows id will be -1: ignore all negatives. | ||
if id := os.Getuid(); id >= 0 { | ||
username = fmt.Sprintf("%d", id) | ||
} else { | ||
// Just give up. | ||
return resource.Empty(), nil | ||
} | ||
} | ||
|
||
return resource.NewWithAttributes(semconv.SchemaURL, semconv.ProcessOwnerKey.String(username)), nil | ||
} | ||
|
||
func WithSafeProcessOwner() resource.Option { | ||
return resource.WithDetectors(safeProcessOwnerProvider{}) | ||
} |