Skip to content

Commit

Permalink
libct/cap: switch to lazy init
Browse files Browse the repository at this point in the history
A map which is created in func init is only used by capSlice, which is
only used by New, which is only used by runc init. Switch to lazy init
to slightly save on startup time.

Signed-off-by: Kir Kolyshkin <[email protected]>
  • Loading branch information
kolyshkin committed Jul 29, 2024
1 parent 12326b2 commit 2bb6167
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions libcontainer/capabilities/capabilities.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package capabilities
import (
"sort"
"strings"
"sync"

"github.com/opencontainers/runc/libcontainer/configs"
"github.com/sirupsen/logrus"
Expand All @@ -14,25 +15,25 @@ import (
const allCapabilityTypes = capability.CAPS | capability.BOUNDING | capability.AMBIENT

var (
capabilityMap map[string]capability.Cap
capTypes = []capability.CapType{
capTypes = []capability.CapType{
capability.BOUNDING,
capability.PERMITTED,
capability.INHERITABLE,
capability.EFFECTIVE,
capability.AMBIENT,
}
)

func init() {
capabilityMap = make(map[string]capability.Cap, capability.CAP_LAST_CAP+1)
for _, c := range capability.List() {
if c > capability.CAP_LAST_CAP {
continue
capMap = sync.OnceValue(func() map[string]capability.Cap {
cm := make(map[string]capability.Cap, capability.CAP_LAST_CAP+1)
for _, c := range capability.List() {
if c > capability.CAP_LAST_CAP {
continue
}
cm["CAP_"+strings.ToUpper(c.String())] = c
}
capabilityMap["CAP_"+strings.ToUpper(c.String())] = c
}
}
return cm
})
)

// KnownCapabilities returns the list of the known capabilities.
// Used by `runc features`.
Expand Down Expand Up @@ -78,9 +79,10 @@ func New(capConfig *configs.Capabilities) (*Caps, error) {
// equivalent, and returns them as a slice. Unknown or unavailable capabilities
// are not returned, but appended to unknownCaps.
func capSlice(caps []string, unknownCaps map[string]struct{}) []capability.Cap {
cm := capMap()
out := make([]capability.Cap, 0, len(caps))
for _, c := range caps {
if v, ok := capabilityMap[c]; !ok {
if v, ok := cm[c]; !ok {
unknownCaps[c] = struct{}{}
} else {
out = append(out, v)
Expand Down

0 comments on commit 2bb6167

Please sign in to comment.