Vendor in latest c/common

Pull in updates made to the filters code for
images. Filters now perform an AND operation
except for th reference filter which does an
OR operation for positive case but an AND operation
for negative cases.

Signed-off-by: Urvashi Mohnani <umohnani@redhat.com>
This commit is contained in:
Urvashi Mohnani
2024-01-24 08:11:51 -05:00
parent d66b18f5af
commit 7c8c945496
197 changed files with 1521 additions and 1350 deletions

View File

@@ -20,6 +20,7 @@ linters:
# - typecheck
# - unused
- errorlint # error wrapping (eg, not using `errors.Is`, using `%s` instead of `%w` in `fmt.Errorf`)
- gofmt # whether code was gofmt-ed
- govet # enabled by default, but just to be sure
- nolintlint # ill-formed or insufficient nolint directives
@@ -53,6 +54,12 @@ issues:
text: "^ST1003: should not use underscores in package names$"
source: "^package cri_containerd$"
# don't bother with propper error wrapping in test code
- path: cri-containerd
linters:
- errorlint
text: "non-wrapping format verb for fmt.Errorf"
# This repo has a LOT of generated schema files, operating system bindings, and other
# things that ST1003 from stylecheck won't like (screaming case Windows api constants for example).
# There's also some structs that we *could* change the initialisms to be Go friendly

View File

@@ -9,15 +9,18 @@ It is primarily used in the [Moby](https://github.com/moby/moby) and [Containerd
## Building
While this repository can be used as a library of sorts to call the HCS apis, there are a couple binaries built out of the repository as well. The main ones being the Linux guest agent, and an implementation of the [runtime v2 containerd shim api](https://github.com/containerd/containerd/blob/master/runtime/v2/README.md).
### Linux Hyper-V Container Guest Agent
To build the Linux guest agent itself all that's needed is to set your GOOS to "Linux" and build out of ./cmd/gcs.
```powershell
C:\> $env:GOOS="linux"
C:\> go build .\cmd\gcs\
```
or on a Linux machine
```sh
> go build ./cmd/gcs
```
@@ -33,13 +36,15 @@ make all
```
If the build is successful, in the `./out` folder you should see:
```sh
> ls ./out/
delta.tar.gz initrd.img rootfs.tar.gz
```
### Containerd Shim
For info on the Runtime V2 API: https://github.com/containerd/containerd/blob/master/runtime/v2/README.md.
For info on the [Runtime V2 API](https://github.com/containerd/containerd/blob/master/runtime/v2/README.md).
Contrary to the typical Linux architecture of shim -> runc, the runhcs shim is used both to launch and manage the lifetime of containers.
@@ -48,7 +53,9 @@ C:\> $env:GOOS="windows"
C:\> go build .\cmd\containerd-shim-runhcs-v1
```
Then place the binary in the same directory that Containerd is located at in your environment. A default Containerd configuration file can be generated by running:
Then place the binary in the same directory that Containerd is located at in your environment.
A default Containerd configuration file can be generated by running:
```powershell
.\containerd.exe config default | Out-File "C:\Program Files\containerd\config.toml" -Encoding ascii
```
@@ -56,6 +63,7 @@ Then place the binary in the same directory that Containerd is located at in you
This config file will already have the shim set as the default runtime for cri interactions.
To trial using the shim out with ctr.exe:
```powershell
C:\> ctr.exe run --runtime io.containerd.runhcs.v1 --rm mcr.microsoft.com/windows/nanoserver:2004 windows-test cmd /c "echo Hello World!"
```
@@ -64,16 +72,69 @@ C:\> ctr.exe run --runtime io.containerd.runhcs.v1 --rm mcr.microsoft.com/window
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.
the rights to use your contribution. For details, visit [Microsoft CLA](https://cla.microsoft.com).
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
We also require that contributors [sign their commits](https://git-scm.com/docs/git-commit) using `git commit -s` or `git commit --signoff` to
certify they either authored the work themselves or otherwise have permission to use it in this project. Please see https://developercertificate.org/ for
more info, as well as to make sure that you can attest to the rules listed. Our CI uses the [DCO Github app](https://github.com/apps/dco) to ensure
that all commits in a given PR are signed-off.
We require that contributors sign their commits
to certify they either authored the work themselves or otherwise have permission to use it in this project.
We also require that contributors sign their commits using using [`git commit --signoff`][git-commit-s]
to certify they either authored the work themselves or otherwise have permission to use it in this project.
A range of commits can be signed off using [`git rebase --signoff`][git-rebase-s].
Please see [the developer certificate](https://developercertificate.org) for more info,
as well as to make sure that you can attest to the rules listed.
Our CI uses the [DCO Github app](https://github.com/apps/dco) to ensure that all commits in a given PR are signed-off.
### Linting
Code must pass a linting stage, which uses [`golangci-lint`][lint].
Since `./test` is a separate Go module, the linter is run from both the root and the
`test` directories. Additionally, the linter is run with `GOOS` set to both `windows` and
`linux`.
The linting settings are stored in [`.golangci.yaml`](./.golangci.yaml), and can be run
automatically with VSCode by adding the following to your workspace or folder settings:
```json
"go.lintTool": "golangci-lint",
"go.lintOnSave": "package",
```
Additional editor [integrations options are also available][lint-ide].
Alternatively, `golangci-lint` can be [installed][lint-install] and run locally:
```shell
# use . or specify a path to only lint a package
# to show all lint errors, use flags "--max-issues-per-linter=0 --max-same-issues=0"
> golangci-lint run
```
To run across the entire repo for both `GOOS=windows` and `linux`:
```powershell
> foreach ( $goos in ('windows', 'linux') ) {
foreach ( $repo in ('.', 'test') ) {
pwsh -Command "cd $repo && go env -w GOOS=$goos && golangci-lint.exe run --verbose"
}
}
```
### Go Generate
The pipeline checks that auto-generated code, via `go generate`, are up to date.
Similar to the [linting stage](#linting), `go generate` is run in both the root and test Go modules.
This can be done via:
```shell
> go generate ./...
> cd test && go generate ./...
```
## Code of Conduct
@@ -83,7 +144,7 @@ contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additio
## Dependencies
This project requires Golang 1.17 or newer to build.
This project requires Golang 1.18 or newer to build.
For system requirements to run this project, see the Microsoft docs on [Windows Container requirements](https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/system-requirements).
@@ -100,3 +161,10 @@ For additional details, see [Report a Computer Security Vulnerability](https://t
---------------
Copyright (c) 2018 Microsoft Corp. All rights reserved.
[lint]: https://golangci-lint.run/
[lint-ide]: https://golangci-lint.run/usage/integrations/#editor-integration
[lint-install]: https://golangci-lint.run/usage/install/#local-installation
[git-commit-s]: https://git-scm.com/docs/git-commit#Documentation/git-commit.txt--s
[git-rebase-s]: https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---signoff

View File

@@ -38,3 +38,31 @@ func AttachLayerStorageFilter(ctx context.Context, layerPath string, layerData L
}
return nil
}
// AttachOverlayFilter sets up a filter of the given type on a writable container layer. Currently the only
// supported filter types are WCIFS & UnionFS (defined in internal/hcs/schema2/layer.go)
//
// `volumePath` is volume path at which writable layer is mounted. If the
// path does not end in a `\` the platform will append it automatically.
//
// `layerData` is the parent read-only layer data.
func AttachOverlayFilter(ctx context.Context, volumePath string, layerData LayerData) (err error) {
title := "hcsshim::AttachOverlayFilter"
ctx, span := oc.StartSpan(ctx, title) //nolint:ineffassign,staticcheck
defer span.End()
defer func() { oc.SetSpanStatus(span, err) }()
span.AddAttributes(
trace.StringAttribute("volumePath", volumePath),
)
bytes, err := json.Marshal(layerData)
if err != nil {
return err
}
err = hcsAttachOverlayFilter(volumePath, string(bytes))
if err != nil {
return errors.Wrap(err, "failed to attach overlay filter")
}
return nil
}

View File

@@ -4,7 +4,9 @@ package computestorage
import (
"context"
"encoding/json"
hcsschema "github.com/Microsoft/hcsshim/internal/hcs/schema2"
"github.com/Microsoft/hcsshim/internal/oc"
"github.com/pkg/errors"
"go.opencensus.io/trace"
@@ -26,3 +28,27 @@ func DetachLayerStorageFilter(ctx context.Context, layerPath string) (err error)
}
return nil
}
// DetachOverlayFilter detaches the filter on a writable container layer.
//
// `volumePath` is a path to writable container volume.
func DetachOverlayFilter(ctx context.Context, volumePath string, filterType hcsschema.FileSystemFilterType) (err error) {
title := "hcsshim::DetachOverlayFilter"
ctx, span := oc.StartSpan(ctx, title) //nolint:ineffassign,staticcheck
defer span.End()
defer func() { oc.SetSpanStatus(span, err) }()
span.AddAttributes(trace.StringAttribute("volumePath", volumePath))
layerData := LayerData{}
layerData.FilterType = filterType
bytes, err := json.Marshal(layerData)
if err != nil {
return err
}
err = hcsDetachOverlayFilter(volumePath, string(bytes))
if err != nil {
return errors.Wrap(err, "failed to detach overlay filter")
}
return nil
}

View File

@@ -19,14 +19,17 @@ import (
//sys hcsFormatWritableLayerVhd(handle windows.Handle) (hr error) = computestorage.HcsFormatWritableLayerVhd?
//sys hcsGetLayerVhdMountPath(vhdHandle windows.Handle, mountPath **uint16) (hr error) = computestorage.HcsGetLayerVhdMountPath?
//sys hcsSetupBaseOSVolume(layerPath string, volumePath string, options string) (hr error) = computestorage.HcsSetupBaseOSVolume?
//sys hcsAttachOverlayFilter(volumePath string, layerData string) (hr error) = computestorage.HcsAttachOverlayFilter?
//sys hcsDetachOverlayFilter(volumePath string, layerData string) (hr error) = computestorage.HcsDetachOverlayFilter?
type Version = hcsschema.Version
type Layer = hcsschema.Layer
// LayerData is the data used to describe parent layer information.
type LayerData struct {
SchemaVersion Version `json:"SchemaVersion,omitempty"`
Layers []Layer `json:"Layers,omitempty"`
SchemaVersion Version `json:"SchemaVersion,omitempty"`
Layers []Layer `json:"Layers,omitempty"`
FilterType hcsschema.FileSystemFilterType `json:"FilterType,omitempty"`
}
// ExportLayerOptions are the set of options that are used with the `computestorage.HcsExportLayer` syscall.

View File

@@ -43,8 +43,10 @@ var (
modcomputestorage = windows.NewLazySystemDLL("computestorage.dll")
procHcsAttachLayerStorageFilter = modcomputestorage.NewProc("HcsAttachLayerStorageFilter")
procHcsAttachOverlayFilter = modcomputestorage.NewProc("HcsAttachOverlayFilter")
procHcsDestroyLayer = modcomputestorage.NewProc("HcsDestroyLayer")
procHcsDetachLayerStorageFilter = modcomputestorage.NewProc("HcsDetachLayerStorageFilter")
procHcsDetachOverlayFilter = modcomputestorage.NewProc("HcsDetachOverlayFilter")
procHcsExportLayer = modcomputestorage.NewProc("HcsExportLayer")
procHcsFormatWritableLayerVhd = modcomputestorage.NewProc("HcsFormatWritableLayerVhd")
procHcsGetLayerVhdMountPath = modcomputestorage.NewProc("HcsGetLayerVhdMountPath")
@@ -83,6 +85,35 @@ func _hcsAttachLayerStorageFilter(layerPath *uint16, layerData *uint16) (hr erro
return
}
func hcsAttachOverlayFilter(volumePath string, layerData string) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(volumePath)
if hr != nil {
return
}
var _p1 *uint16
_p1, hr = syscall.UTF16PtrFromString(layerData)
if hr != nil {
return
}
return _hcsAttachOverlayFilter(_p0, _p1)
}
func _hcsAttachOverlayFilter(volumePath *uint16, layerData *uint16) (hr error) {
hr = procHcsAttachOverlayFilter.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall(procHcsAttachOverlayFilter.Addr(), 2, uintptr(unsafe.Pointer(volumePath)), uintptr(unsafe.Pointer(layerData)), 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func hcsDestroyLayer(layerPath string) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(layerPath)
@@ -131,6 +162,35 @@ func _hcsDetachLayerStorageFilter(layerPath *uint16) (hr error) {
return
}
func hcsDetachOverlayFilter(volumePath string, layerData string) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(volumePath)
if hr != nil {
return
}
var _p1 *uint16
_p1, hr = syscall.UTF16PtrFromString(layerData)
if hr != nil {
return
}
return _hcsDetachOverlayFilter(_p0, _p1)
}
func _hcsDetachOverlayFilter(volumePath *uint16, layerData *uint16) (hr error) {
hr = procHcsDetachOverlayFilter.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall(procHcsDetachOverlayFilter.Addr(), 2, uintptr(unsafe.Pointer(volumePath)), uintptr(unsafe.Pointer(layerData)), 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func hcsExportLayer(layerPath string, exportFolderPath string, layerData string, options string) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(layerPath)

View File

@@ -75,7 +75,7 @@ func init() {
func CreateContainer(id string, c *ContainerConfig) (Container, error) {
fullConfig, err := mergemaps.MergeJSON(c, createContainerAdditionalJSON)
if err != nil {
return nil, fmt.Errorf("failed to merge additional JSON '%s': %s", createContainerAdditionalJSON, err)
return nil, fmt.Errorf("failed to merge additional JSON '%s': %w", createContainerAdditionalJSON, err)
}
system, err := hcs.CreateComputeSystem(context.Background(), id, fullConfig)

View File

@@ -115,6 +115,7 @@ func (e *ContainerError) Error() string {
s += " encountered an error during " + e.Operation
}
//nolint:errorlint // legacy code
switch e.Err.(type) {
case nil:
break
@@ -145,6 +146,7 @@ func (e *ProcessError) Error() string {
s += " encountered an error during " + e.Operation
}
//nolint:errorlint // legacy code
switch e.Err.(type) {
case nil:
break
@@ -166,10 +168,10 @@ func (e *ProcessError) Error() string {
// already exited, or does not exist. Both IsAlreadyStopped and IsNotExist
// will currently return true when the error is ErrElementNotFound.
func IsNotExist(err error) bool {
if _, ok := err.(EndpointNotFoundError); ok {
if _, ok := err.(EndpointNotFoundError); ok { //nolint:errorlint // legacy code
return true
}
if _, ok := err.(NetworkNotFoundError); ok {
if _, ok := err.(NetworkNotFoundError); ok { //nolint:errorlint // legacy code
return true
}
return hcs.IsNotExist(getInnerError(err))
@@ -224,6 +226,7 @@ func IsAccessIsDenied(err error) bool {
}
func getInnerError(err error) error {
//nolint:errorlint // legacy code
switch pe := err.(type) {
case nil:
return nil
@@ -236,14 +239,14 @@ func getInnerError(err error) error {
}
func convertSystemError(err error, c *container) error {
if serr, ok := err.(*hcs.SystemError); ok {
if serr, ok := err.(*hcs.SystemError); ok { //nolint:errorlint // legacy code
return &ContainerError{Container: c, Operation: serr.Op, Err: serr.Err, Events: serr.Events}
}
return err
}
func convertProcessError(err error, p *process) error {
if perr, ok := err.(*hcs.ProcessError); ok {
if perr, ok := err.(*hcs.ProcessError); ok { //nolint:errorlint // legacy code
return &ProcessError{Process: p, Operation: perr.Op, Err: perr.Err, Events: perr.Events}
}
return err

View File

@@ -63,7 +63,7 @@ func (process *Process) SystemID() string {
}
func (process *Process) processSignalResult(ctx context.Context, err error) (bool, error) {
switch err {
switch err { //nolint:errorlint
case nil:
return true, nil
case ErrVmcomputeOperationInvalidState, ErrComputeSystemDoesNotExist, ErrElementNotFound:

View File

@@ -9,6 +9,13 @@
package hcsschema
type FileSystemFilterType string
const (
UnionFS FileSystemFilterType = "UnionFS"
WCIFS FileSystemFilterType = "WCIFS"
)
type Layer struct {
Id string `json:"Id,omitempty"`

View File

@@ -0,0 +1,13 @@
package hcsschema
// NOTE: manually added
type RegistryHive string
// List of RegistryHive
const (
RegistryHive_SYSTEM RegistryHive = "System"
RegistryHive_SOFTWARE RegistryHive = "Software"
RegistryHive_SECURITY RegistryHive = "Security"
RegistryHive_SAM RegistryHive = "Sam"
)

View File

@@ -10,7 +10,7 @@
package hcsschema
type RegistryKey struct {
Hive string `json:"Hive,omitempty"`
Hive RegistryHive `json:"Hive,omitempty"`
Name string `json:"Name,omitempty"`

View File

@@ -14,7 +14,7 @@ type RegistryValue struct {
Name string `json:"Name,omitempty"`
Type_ string `json:"Type,omitempty"`
Type_ RegistryValueType `json:"Type,omitempty"`
// One and only one value type must be set.
StringValue string `json:"StringValue,omitempty"`

View File

@@ -0,0 +1,17 @@
package hcsschema
// NOTE: manually added
type RegistryValueType string
// List of RegistryValueType
const (
RegistryValueType_NONE RegistryValueType = "None"
RegistryValueType_STRING RegistryValueType = "String"
RegistryValueType_EXPANDED_STRING RegistryValueType = "ExpandedString"
RegistryValueType_MULTI_STRING RegistryValueType = "MultiString"
RegistryValueType_BINARY RegistryValueType = "Binary"
RegistryValueType_D_WORD RegistryValueType = "DWord"
RegistryValueType_Q_WORD RegistryValueType = "QWord"
RegistryValueType_CUSTOM_TYPE RegistryValueType = "CustomType"
)

View File

@@ -97,7 +97,7 @@ func CreateComputeSystem(ctx context.Context, id string, hcsDocumentInterface in
events, err := processAsyncHcsResult(ctx, createError, resultJSON, computeSystem.callbackNumber,
hcsNotificationSystemCreateCompleted, &timeout.SystemCreate)
if err != nil {
if err == ErrTimeout {
if errors.Is(err, ErrTimeout) {
// Terminate the compute system if it still exists. We're okay to
// ignore a failure here.
_ = computeSystem.Terminate(ctx)
@@ -238,7 +238,7 @@ func (computeSystem *System) Shutdown(ctx context.Context) error {
resultJSON, err := vmcompute.HcsShutdownComputeSystem(ctx, computeSystem.handle, "")
events := processHcsResult(ctx, resultJSON)
switch err {
switch err { //nolint:errorlint
case nil, ErrVmcomputeAlreadyStopped, ErrComputeSystemDoesNotExist, ErrVmcomputeOperationPending:
default:
return makeSystemError(computeSystem, operation, err, events)
@@ -259,7 +259,7 @@ func (computeSystem *System) Terminate(ctx context.Context) error {
resultJSON, err := vmcompute.HcsTerminateComputeSystem(ctx, computeSystem.handle, "")
events := processHcsResult(ctx, resultJSON)
switch err {
switch err { //nolint:errorlint
case nil, ErrVmcomputeAlreadyStopped, ErrComputeSystemDoesNotExist, ErrVmcomputeOperationPending:
default:
return makeSystemError(computeSystem, operation, err, events)
@@ -279,7 +279,7 @@ func (computeSystem *System) waitBackground() {
span.AddAttributes(trace.StringAttribute("cid", computeSystem.id))
err := waitForNotification(ctx, computeSystem.callbackNumber, hcsNotificationSystemExited, nil)
switch err {
switch err { //nolint:errorlint
case nil:
log.G(ctx).Debug("system exited")
case ErrVmcomputeUnexpectedExit:

View File

@@ -31,7 +31,7 @@ func hnsCallRawResponse(method, path, request string) (*hnsResponse, error) {
func hnsCall(method, path, request string, returnResponse interface{}) error {
hnsresponse, err := hnsCallRawResponse(method, path, request)
if err != nil {
return fmt.Errorf("failed during hnsCallRawResponse: %v", err)
return fmt.Errorf("failed during hnsCallRawResponse: %w", err)
}
if !hnsresponse.Success {
return fmt.Errorf("hns failed with error : %s", hnsresponse.Error)

View File

@@ -56,7 +56,7 @@ func issueNamespaceRequest(id *string, method, subpath string, request interface
if strings.Contains(err.Error(), "Element not found.") {
return nil, os.ErrNotExist
}
return nil, fmt.Errorf("%s %s: %s", method, hnspath, err)
return nil, fmt.Errorf("%s %s: %w", method, hnspath, err)
}
return &ns, err
}
@@ -86,7 +86,7 @@ func GetNamespaceEndpoints(id string) ([]string, error) {
var endpoint namespaceEndpointRequest
err = json.Unmarshal(rsrc.Data, &endpoint)
if err != nil {
return nil, fmt.Errorf("unmarshal endpoint: %s", err)
return nil, fmt.Errorf("unmarshal endpoint: %w", err)
}
endpoints = append(endpoints, endpoint.ID)
}

View File

@@ -4,6 +4,7 @@ package jobobject
import (
"context"
"errors"
"fmt"
"sync"
"unsafe"
@@ -59,7 +60,7 @@ func pollIOCP(ctx context.Context, iocpHandle windows.Handle) {
}).Warn("failed to parse job object message")
continue
}
if err := msq.Enqueue(notification); err == queue.ErrQueueClosed {
if err := msq.Enqueue(notification); errors.Is(err, queue.ErrQueueClosed) {
// Write will only return an error when the queue is closed.
// The only time a queue would ever be closed is when we call `Close` on
// the job it belongs to which also removes it from the jobMap, so something

View File

@@ -374,7 +374,7 @@ func (job *JobObject) Pids() ([]uint32, error) {
return []uint32{}, nil
}
if err != winapi.ERROR_MORE_DATA {
if err != winapi.ERROR_MORE_DATA { //nolint:errorlint
return nil, fmt.Errorf("failed initial query for PIDs in job object: %w", err)
}

View File

@@ -143,6 +143,13 @@ func (job *JobObject) SetCPUAffinity(affinityBitMask uint64) error {
return err
}
info.BasicLimitInformation.LimitFlags |= uint32(windows.JOB_OBJECT_LIMIT_AFFINITY)
// We really, really shouldn't be running on 32 bit, but just in case (and to satisfy CodeQL) ...
const maxUintptr = ^uintptr(0)
if affinityBitMask > uint64(maxUintptr) {
return fmt.Errorf("affinity bitmask (%d) exceeds max allowable value (%d)", affinityBitMask, maxUintptr)
}
info.BasicLimitInformation.Affinity = uintptr(affinityBitMask)
return job.setExtendedInformation(info)
}

View File

@@ -104,6 +104,7 @@ func encode(v interface{}) (_ []byte, err error) {
if jErr := enc.Encode(v); jErr != nil {
if err != nil {
// TODO (go1.20): use multierror via fmt.Errorf("...: %w; ...: %w", ...)
//nolint:errorlint // non-wrapping format verb for fmt.Errorf
return nil, fmt.Errorf("protojson encoding: %v; json encoding: %w", err, jErr)
}
return nil, fmt.Errorf("json encoding: %w", jErr)

View File

@@ -46,6 +46,7 @@ const (
ExpectedType = "expected-type"
Bool = "bool"
Int32 = "int32"
Uint32 = "uint32"
Uint64 = "uint64"

View File

@@ -126,7 +126,7 @@ func (pa *PoolAllocator) Allocate(size uint64) (MappedRegion, error) {
// this means that there are no more regions for the current class, try expanding
if nextCls != memCls {
if err := pa.split(memCls); err != nil {
if err == ErrInvalidMemoryClass {
if errors.Is(err, ErrInvalidMemoryClass) {
return nil, ErrNotEnoughSpace
}
return nil, err
@@ -147,7 +147,7 @@ func (pa *PoolAllocator) Allocate(size uint64) (MappedRegion, error) {
}
// Release marks a memory region of class `memCls` and offset `offset` as free and tries to merge smaller regions into
// a bigger one
// a bigger one.
func (pa *PoolAllocator) Release(reg MappedRegion) error {
mp := pa.pools[reg.Type()]
if mp == nil {
@@ -164,7 +164,7 @@ func (pa *PoolAllocator) Release(reg MappedRegion) error {
return ErrNotAllocated
}
if err := pa.merge(n.parent); err != nil {
if err != ErrEarlyMerge {
if !errors.Is(err, ErrEarlyMerge) {
return err
}
}

View File

@@ -243,7 +243,7 @@ func RemoveRelative(path string, root *os.File) error {
if err == nil {
defer f.Close()
err = deleteOnClose(f)
if err == syscall.ERROR_ACCESS_DENIED {
if err == syscall.ERROR_ACCESS_DENIED { //nolint:errorlint
// Maybe the file is marked readonly. Clear the bit and retry.
_ = clearReadOnly(f)
err = deleteOnClose(f)

View File

@@ -104,7 +104,7 @@ func execute(ctx gcontext.Context, timeout time.Duration, f func() error) error
}()
select {
case <-ctx.Done():
if ctx.Err() == gcontext.DeadlineExceeded {
if ctx.Err() == gcontext.DeadlineExceeded { //nolint:errorlint
log.G(ctx).WithField(logfields.Timeout, trueTimeout).
Warning("Syscall did not complete within operation timeout. This may indicate a platform issue. " +
"If it appears to be making no forward progress, obtain the stacks and see if there is a syscall " +
@@ -150,7 +150,7 @@ func HcsCreateComputeSystem(ctx gcontext.Context, id string, configuration strin
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@@ -205,7 +205,7 @@ func HcsStartComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, option
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@@ -228,7 +228,7 @@ func HcsShutdownComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, opt
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@@ -251,7 +251,7 @@ func HcsTerminateComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, op
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@@ -274,7 +274,7 @@ func HcsPauseComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, option
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@@ -297,7 +297,7 @@ func HcsResumeComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, optio
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@@ -621,7 +621,7 @@ func HcsSaveComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()

View File

@@ -1,3 +1,5 @@
//go:build windows
package wclayer
import (
@@ -64,7 +66,7 @@ func (r *baseLayerReader) walkUntilCancelled() error {
return nil
})
if err == errorIterationCanceled {
if err == errorIterationCanceled { //nolint:errorlint // explicitly returned
return nil
}
@@ -103,7 +105,7 @@ func (r *baseLayerReader) walkUntilCancelled() error {
return nil
})
if err == errorIterationCanceled {
if err == errorIterationCanceled { //nolint:errorlint // explicitly returned
return nil
}

View File

@@ -1,3 +1,5 @@
//go:build windows
package wclayer
import (

View File

@@ -11,7 +11,6 @@ import (
"github.com/Microsoft/hcsshim/internal/hcserror"
"github.com/Microsoft/hcsshim/internal/oc"
"github.com/Microsoft/hcsshim/osversion"
"go.opencensus.io/trace"
)
@@ -30,14 +29,17 @@ func ExpandScratchSize(ctx context.Context, path string, size uint64) (err error
return hcserror.New(err, title, "")
}
// Manually expand the volume now in order to work around bugs in 19H1 and
// prerelease versions of Vb. Remove once this is fixed in Windows.
if build := osversion.Build(); build >= osversion.V19H1 && build < 19020 {
err = expandSandboxVolume(ctx, path)
if err != nil {
return err
}
// Always expand the volume too. In case of legacy layers not expanding the volume here works because
// the PrepareLayer call internally handles the expansion. However, in other cases (like CimFS) we
// don't call PrepareLayer and so the volume will never be expanded. This also means in case of
// legacy layers, we might have a small perf hit because the VHD is mounted twice for expansion (once
// here and once during the PrepareLayer call). But as long as the perf hit is minimal, we should be
// okay.
err = expandSandboxVolume(ctx, path)
if err != nil {
return err
}
return nil
}

View File

@@ -154,7 +154,7 @@ func (r *legacyLayerReader) walkUntilCancelled() error {
}
return nil
})
if err == errorIterationCanceled {
if err == errorIterationCanceled { //nolint:errorlint // explicitly returned
return nil
}
if err == nil {
@@ -196,7 +196,7 @@ func findBackupStreamSize(r io.Reader) (int64, error) {
for {
hdr, err := br.Next()
if err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
err = nil
}
return 0, err
@@ -428,7 +428,7 @@ func (w *legacyLayerWriter) initUtilityVM() error {
// immutable.
err = cloneTree(w.parentRoots[0], w.destRoot, UtilityVMFilesPath, mutatedUtilityVMFiles)
if err != nil {
return fmt.Errorf("cloning the parent utility VM image failed: %s", err)
return fmt.Errorf("cloning the parent utility VM image failed: %w", err)
}
w.HasUtilityVM = true
}
@@ -451,7 +451,7 @@ func (w *legacyLayerWriter) reset() error {
for {
bhdr, err := br.Next()
if err == io.EOF {
if errors.Is(err, io.EOF) {
// end of backupstream data
break
}

View File

@@ -1,3 +1,5 @@
//go:build windows
package winapi
import (
@@ -34,7 +36,7 @@ type CimFsFileMetadata struct {
//sys CimDismountImage(volumeID *g) (hr error) = cimfs.CimDismountImage?
//sys CimCreateImage(imagePath string, oldFSName *uint16, newFSName *uint16, cimFSHandle *FsHandle) (hr error) = cimfs.CimCreateImage?
//sys CimCloseImage(cimFSHandle FsHandle) (hr error) = cimfs.CimCloseImage?
//sys CimCloseImage(cimFSHandle FsHandle) = cimfs.CimCloseImage?
//sys CimCommitImage(cimFSHandle FsHandle) (hr error) = cimfs.CimCommitImage?
//sys CimCreateFile(cimFSHandle FsHandle, path string, file *CimFsFileMetadata, cimStreamHandle *StreamHandle) (hr error) = cimfs.CimCreateFile?

View File

@@ -184,18 +184,12 @@ func _CMLocateDevNode(pdnDevInst *uint32, pDeviceID *uint16, uFlags uint32) (hr
return
}
func CimCloseImage(cimFSHandle FsHandle) (hr error) {
hr = procCimCloseImage.Find()
if hr != nil {
func CimCloseImage(cimFSHandle FsHandle) (err error) {
err = procCimCloseImage.Find()
if err != nil {
return
}
r0, _, _ := syscall.Syscall(procCimCloseImage.Addr(), 1, uintptr(cimFSHandle), 0, 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
syscall.Syscall(procCimCloseImage.Addr(), 1, uintptr(cimFSHandle), 0, 0)
return
}

View File

@@ -42,8 +42,8 @@ func (a *Slice) Set(values []string) {
}
// UnmarshalTOML is the custom unmarshal method for Slice.
func (a *Slice) UnmarshalTOML(data interface{}) error {
iFaceSlice, ok := data.([]interface{})
func (a *Slice) UnmarshalTOML(data any) error {
iFaceSlice, ok := data.([]any)
if !ok {
return fmt.Errorf("unable to cast to interface array: %v", data)
}
@@ -53,7 +53,7 @@ func (a *Slice) UnmarshalTOML(data interface{}) error {
switch val := x.(type) {
case string: // Strings are directly appended to the slice.
loadedStrings = append(loadedStrings, val)
case map[string]interface{}: // The attribute struct is represented as a map.
case map[string]any: // The attribute struct is represented as a map.
for k, v := range val { // Iterate over all _supported_ keys.
switch k {
case "append":
@@ -81,16 +81,15 @@ func (a *Slice) UnmarshalTOML(data interface{}) error {
// MarshalTOML is the custom marshal method for Slice.
func (a *Slice) MarshalTOML() ([]byte, error) {
iFaceSlice := make([]interface{}, 0, len(a.Values))
iFaceSlice := make([]any, 0, len(a.Values))
for _, x := range a.Values {
iFaceSlice = append(iFaceSlice, x)
}
if a.Attributes.Append != nil {
Attributes := make(map[string]any)
Attributes["append"] = *a.Attributes.Append
iFaceSlice = append(iFaceSlice, Attributes)
attributes := map[string]any{"append": *a.Attributes.Append}
iFaceSlice = append(iFaceSlice, attributes)
}
buf := new(bytes.Buffer)

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -518,8 +517,8 @@ func checkRegistrySourcesAllows(dest types.ImageReference) (insecure *bool, err
return nil, fmt.Errorf("registry %q denied by policy: not in allowed registries list (%s)", reference.Domain(dref), registrySources)
}
for _, inseureDomain := range sources.InsecureRegistries {
if inseureDomain == reference.Domain(dref) {
for _, insecureDomain := range sources.InsecureRegistries {
if insecureDomain == reference.Domain(dref) {
insecure := true
return &insecure, nil
}

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -37,7 +36,7 @@ func (r *Runtime) DiskUsage(ctx context.Context) ([]ImageDiskUsage, int64, error
return nil, -1, err
}
layerTree, err := r.layerTree(images)
layerTree, err := r.layerTree(ctx, images)
if err != nil {
return nil, -1, err
}
@@ -80,7 +79,7 @@ func (r *Runtime) DiskUsage(ctx context.Context) ([]ImageDiskUsage, int64, error
// diskUsageForImage returns the disk-usage baseistics for the specified image.
func diskUsageForImage(ctx context.Context, image *Image, tree *layerTree) ([]ImageDiskUsage, error) {
if err := image.isCorrupted(""); err != nil {
if err := image.isCorrupted(ctx, ""); err != nil {
return nil, err
}

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -21,33 +20,28 @@ import (
// indicates that the image matches the criteria.
type filterFunc func(*Image) (bool, error)
// Apply the specified filters. At least one filter of each key must apply.
func (i *Image) applyFilters(filters map[string][]filterFunc) (bool, error) {
matches := false
for key := range filters { // and
matches = false
for _, filter := range filters[key] { // or
var err error
matches, err = filter(i)
// Apply the specified filters. All filters of each key must apply.
func (i *Image) applyFilters(ctx context.Context, filters map[string][]filterFunc) (bool, error) {
for key := range filters {
for _, filter := range filters[key] {
matches, err := filter(i)
if err != nil {
// Some images may have been corrupted in the
// meantime, so do an extra check and make the
// error non-fatal (see containers/podman/issues/12582).
if errCorrupted := i.isCorrupted(""); errCorrupted != nil {
if errCorrupted := i.isCorrupted(ctx, ""); errCorrupted != nil {
logrus.Errorf(errCorrupted.Error())
return false, nil
}
return false, err
}
if matches {
break
// If any filter within a group doesn't match, return false
if !matches {
return false, nil
}
}
if !matches {
return false, nil
}
}
return matches, nil
return true, nil
}
// filterImages returns a slice of images which are passing all specified
@@ -63,7 +57,7 @@ func (r *Runtime) filterImages(ctx context.Context, images []*Image, options *Li
}
result := []*Image{}
for i := range images {
match, err := images[i].applyFilters(filters)
match, err := images[i].applyFilters(ctx, filters)
if err != nil {
return nil, err
}
@@ -84,7 +78,7 @@ func (r *Runtime) compileImageFilters(ctx context.Context, options *ListImagesOp
var tree *layerTree
getTree := func() (*layerTree, error) {
if tree == nil {
t, err := r.layerTree(nil)
t, err := r.layerTree(ctx, nil)
if err != nil {
return nil, err
}
@@ -93,6 +87,7 @@ func (r *Runtime) compileImageFilters(ctx context.Context, options *ListImagesOp
return tree, nil
}
var wantedReferenceMatches, unwantedReferenceMatches []string
filters := map[string][]filterFunc{}
duplicate := map[string]string{}
for _, f := range options.Filters {
@@ -184,7 +179,12 @@ func (r *Runtime) compileImageFilters(ctx context.Context, options *ListImagesOp
filter = filterManifest(ctx, manifest)
case "reference":
filter = filterReferences(r, value)
if negate {
unwantedReferenceMatches = append(unwantedReferenceMatches, value)
} else {
wantedReferenceMatches = append(wantedReferenceMatches, value)
}
continue
case "until":
until, err := r.until(value)
@@ -202,6 +202,11 @@ func (r *Runtime) compileImageFilters(ctx context.Context, options *ListImagesOp
filters[key] = append(filters[key], filter)
}
// reference filters is a special case as it does an OR for positive matches
// and an AND logic for negative matches
filter := filterReferences(r, wantedReferenceMatches, unwantedReferenceMatches)
filters["reference"] = append(filters["reference"], filter)
return filters, nil
}
@@ -273,57 +278,99 @@ func filterManifest(ctx context.Context, value bool) filterFunc {
}
}
// filterReferences creates a reference filter for matching the specified value.
func filterReferences(r *Runtime, value string) filterFunc {
lookedUp, _, _ := r.LookupImage(value, nil)
// filterReferences creates a reference filter for matching the specified wantedReferenceMatches value (OR logic)
// and for matching the unwantedReferenceMatches values (AND logic)
func filterReferences(r *Runtime, wantedReferenceMatches, unwantedReferenceMatches []string) filterFunc {
return func(img *Image) (bool, error) {
if lookedUp != nil {
if lookedUp.ID() == img.ID() {
// Empty reference filters, return true
if len(wantedReferenceMatches) == 0 && len(unwantedReferenceMatches) == 0 {
return true, nil
}
unwantedMatched := false
// Go through the unwanted matches first
for _, value := range unwantedReferenceMatches {
matches, err := imageMatchesReferenceFilter(r, img, value)
if err != nil {
return false, err
}
if matches {
unwantedMatched = true
}
}
// If there are no wanted match filters, then return false for the image
// that matched the unwanted value otherwise return true
if len(wantedReferenceMatches) == 0 {
return !unwantedMatched, nil
}
// Go through the wanted matches
// If an image matches the wanted filter but it also matches the unwanted
// filter, don't add it to the output
for _, value := range wantedReferenceMatches {
matches, err := imageMatchesReferenceFilter(r, img, value)
if err != nil {
return false, err
}
if matches && !unwantedMatched {
return true, nil
}
}
refs, err := img.NamesReferences()
if err != nil {
return false, err
}
for _, ref := range refs {
refString := ref.String() // FQN with tag/digest
candidates := []string{refString}
// Split the reference into 3 components (twice if digested/tagged):
// 1) Fully-qualified reference
// 2) Without domain
// 3) Without domain and path
if named, isNamed := ref.(reference.Named); isNamed {
candidates = append(candidates,
reference.Path(named), // path/name without tag/digest (Path() removes it)
refString[strings.LastIndex(refString, "/")+1:]) // name with tag/digest
trimmedString := reference.TrimNamed(named).String()
if refString != trimmedString {
tagOrDigest := refString[len(trimmedString):]
candidates = append(candidates,
trimmedString, // FQN without tag/digest
reference.Path(named)+tagOrDigest, // path/name with tag/digest
trimmedString[strings.LastIndex(trimmedString, "/")+1:]) // name without tag/digest
}
}
for _, candidate := range candidates {
// path.Match() is also used by Docker's reference.FamiliarMatch().
matched, _ := path.Match(value, candidate)
if matched {
return true, nil
}
}
}
return false, nil
}
}
// imageMatchesReferenceFilter returns true if an image matches the filter value given
func imageMatchesReferenceFilter(r *Runtime, img *Image, value string) (bool, error) {
lookedUp, _, _ := r.LookupImage(value, nil)
if lookedUp != nil {
if lookedUp.ID() == img.ID() {
return true, nil
}
}
refs, err := img.NamesReferences()
if err != nil {
return false, err
}
for _, ref := range refs {
refString := ref.String() // FQN with tag/digest
candidates := []string{refString}
// Split the reference into 3 components (twice if digested/tagged):
// 1) Fully-qualified reference
// 2) Without domain
// 3) Without domain and path
if named, isNamed := ref.(reference.Named); isNamed {
candidates = append(candidates,
reference.Path(named), // path/name without tag/digest (Path() removes it)
refString[strings.LastIndex(refString, "/")+1:]) // name with tag/digest
trimmedString := reference.TrimNamed(named).String()
if refString != trimmedString {
tagOrDigest := refString[len(trimmedString):]
candidates = append(candidates,
trimmedString, // FQN without tag/digest
reference.Path(named)+tagOrDigest, // path/name with tag/digest
trimmedString[strings.LastIndex(trimmedString, "/")+1:]) // name without tag/digest
}
}
for _, candidate := range candidates {
// path.Match() is also used by Docker's reference.FamiliarMatch().
matched, _ := path.Match(value, candidate)
if matched {
return true, nil
}
}
}
return false, nil
}
// filterLabel creates a label for matching the specified value.
func filterLabel(ctx context.Context, value string) filterFunc {
return func(img *Image) (bool, error) {

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -26,7 +25,7 @@ func (i *Image) History(ctx context.Context) ([]ImageHistory, error) {
return nil, err
}
layerTree, err := i.runtime.layerTree(nil)
layerTree, err := i.runtime.layerTree(ctx, nil)
if err != nil {
return nil, err
}

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -67,7 +66,7 @@ type Image struct {
}
}
// reload the image and pessimitically clear all cached data.
// reload the image and pessimistically clear all cached data.
func (i *Image) reload() error {
logrus.Tracef("Reloading image %s", i.ID())
img, err := i.runtime.store.Image(i.ID())
@@ -85,7 +84,7 @@ func (i *Image) reload() error {
}
// isCorrupted returns an error if the image may be corrupted.
func (i *Image) isCorrupted(name string) error {
func (i *Image) isCorrupted(ctx context.Context, name string) error {
// If it's a manifest list, we're good for now.
if _, err := i.getManifestList(); err == nil {
return nil
@@ -96,7 +95,7 @@ func (i *Image) isCorrupted(name string) error {
return err
}
img, err := ref.NewImage(context.Background(), nil)
img, err := ref.NewImage(ctx, nil)
if err != nil {
if name == "" {
name = i.ID()[:12]
@@ -258,7 +257,7 @@ func (i *Image) TopLayer() string {
// Parent returns the parent image or nil if there is none
func (i *Image) Parent(ctx context.Context) (*Image, error) {
tree, err := i.runtime.layerTree(nil)
tree, err := i.runtime.layerTree(ctx, nil)
if err != nil {
return nil, err
}
@@ -292,7 +291,7 @@ func (i *Image) Children(ctx context.Context) ([]*Image, error) {
// created for this invocation only.
func (i *Image) getChildren(ctx context.Context, all bool, tree *layerTree) ([]*Image, error) {
if tree == nil {
t, err := i.runtime.layerTree(nil)
t, err := i.runtime.layerTree(ctx, nil)
if err != nil {
return nil, err
}
@@ -611,7 +610,7 @@ func (i *Image) Untag(name string) error {
}
// FIXME: this is breaking Podman CI but must be re-enabled once
// c/storage supports alterting the digests of an image. Then,
// c/storage supports altering the digests of an image. Then,
// Podman will do the right thing.
//
// !!! Also make sure to re-enable the tests !!!
@@ -1031,7 +1030,7 @@ func getImageID(ctx context.Context, src types.ImageReference, sys *types.System
// - 2) a bool indicating whether architecture, os or variant were set (some callers need that to decide whether they need to throw an error)
// - 3) a fatal error that occurred prior to check for matches (e.g., storage errors etc.)
func (i *Image) matchesPlatform(ctx context.Context, os, arch, variant string) (error, bool, error) {
if err := i.isCorrupted(""); err != nil {
if err := i.isCorrupted(ctx, ""); err != nil {
return err, false, nil
}
inspectInfo, err := i.inspectInfo(ctx)

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,9 +1,9 @@
//go:build !remote
// +build !remote
package libimage
import (
"context"
"fmt"
"strings"
@@ -38,7 +38,7 @@ func (i *Image) Tree(traverseChildren bool) (string, error) {
fmt.Fprintf(sb, "No Image Layers")
}
layerTree, err := i.runtime.layerTree(nil)
layerTree, err := i.runtime.layerTree(context.Background(), nil)
if err != nil {
return "", err
}
@@ -53,7 +53,7 @@ func (i *Image) Tree(traverseChildren bool) (string, error) {
return tree.Print(), nil
}
// Walk all layers of the image and assemlbe their data. Note that the
// Walk all layers of the image and assemble their data. Note that the
// tree is constructed in reverse order to remain backwards compatible
// with Podman.
contents := []string{}

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -92,14 +91,14 @@ func (l *layerNode) repoTags() ([]string, error) {
// layerTree extracts a layerTree from the layers in the local storage and
// relates them to the specified images.
func (r *Runtime) layerTree(images []*Image) (*layerTree, error) {
func (r *Runtime) layerTree(ctx context.Context, images []*Image) (*layerTree, error) {
layers, err := r.store.Layers()
if err != nil {
return nil, err
}
if images == nil {
images, err = r.ListImages(context.Background(), nil, nil)
images, err = r.ListImages(ctx, nil, nil)
if err != nil {
return nil, err
}

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -314,7 +313,7 @@ func (m *ManifestList) Add(ctx context.Context, name string, options *ManifestLi
return newDigest, nil
}
// Options for annotationg a manifest list.
// Options for annotating a manifest list.
type ManifestListAnnotateOptions struct {
// Add the specified annotations to the added image.
Annotations map[string]string

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -31,7 +30,7 @@ import (
"github.com/sirupsen/logrus"
)
// PullOptions allows for custommizing image pulls.
// PullOptions allows for customizing image pulls.
type PullOptions struct {
CopyOptions
@@ -511,7 +510,7 @@ func (r *Runtime) copySingleImageFromRegistry(ctx context.Context, imageName str
// If the local image is corrupted, we need to repull it.
if localImage != nil {
if err := localImage.isCorrupted(imageName); err != nil {
if err := localImage.isCorrupted(ctx, imageName); err != nil {
logrus.Error(err)
localImage = nil
}

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -13,7 +12,7 @@ import (
"github.com/sirupsen/logrus"
)
// PushOptions allows for custommizing image pushes.
// PushOptions allows for customizing image pushes.
type PushOptions struct {
CopyOptions
}

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage
@@ -162,7 +161,7 @@ func (r *Runtime) storageToImage(storageImage *storage.Image, ref types.ImageRef
}
}
// Exists returns true if the specicifed image exists in the local containers
// Exists returns true if the specified image exists in the local containers
// storage. Note that it may return false if an image corrupted.
func (r *Runtime) Exists(name string) (bool, error) {
image, _, err := r.LookupImage(name, nil)
@@ -172,7 +171,7 @@ func (r *Runtime) Exists(name string) (bool, error) {
if image == nil {
return false, nil
}
if err := image.isCorrupted(name); err != nil {
if err := image.isCorrupted(context.Background(), name); err != nil {
logrus.Error(err)
return false, nil
}
@@ -235,8 +234,12 @@ func (r *Runtime) LookupImage(name string, options *LookupImageOptions) (*Image,
if storageRef.Transport().Name() != storageTransport.Transport.Name() {
return nil, "", fmt.Errorf("unsupported transport %q for looking up local images", storageRef.Transport().Name())
}
img, err := storageTransport.Transport.GetStoreImage(r.store, storageRef)
_, img, err := storageTransport.ResolveReference(storageRef)
if err != nil {
if errors.Is(err, storageTransport.ErrNoSuchImage) {
// backward compatibility
return nil, "", storage.ErrImageUnknown
}
return nil, "", err
}
logrus.Debugf("Found image %q in local containers storage (%s)", name, storageRef.StringWithinTransport())
@@ -347,9 +350,9 @@ func (r *Runtime) lookupImageInLocalStorage(name, candidate string, namedCandida
if err != nil {
return nil, err
}
img, err = storageTransport.Transport.GetStoreImage(r.store, ref)
_, img, err = storageTransport.ResolveReference(ref)
if err != nil {
if errors.Is(err, storage.ErrImageUnknown) {
if errors.Is(err, storageTransport.ErrNoSuchImage) {
return nil, nil
}
return nil, err
@@ -605,7 +608,7 @@ func (r *Runtime) ListImages(ctx context.Context, names []string, options *ListI
// as the layer tree will computed once for all instead of once for
// each individual image (see containers/podman/issues/17828).
tree, err := r.layerTree(images)
tree, err := r.layerTree(ctx, images)
if err != nil {
return nil, err
}

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package libimage

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package cni
@@ -18,8 +17,8 @@ import (
internalutil "github.com/containers/common/libnetwork/internal/util"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util"
pkgutil "github.com/containers/common/pkg/util"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
"golang.org/x/sys/unix"
)
@@ -32,13 +31,13 @@ func createNetworkFromCNIConfigList(conf *libcni.NetworkConfigList, confPath str
IPAMOptions: map[string]string{},
}
cniJSON := make(map[string]interface{})
cniJSON := make(map[string]any)
err := json.Unmarshal(conf.Bytes, &cniJSON)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal network config %s: %w", conf.Name, err)
}
if args, ok := cniJSON["args"]; ok {
if key, ok := args.(map[string]interface{}); ok {
if key, ok := args.(map[string]any); ok {
// read network labels and options from the conf file
network.Labels = getNetworkArgsFromConfList(key, podmanLabelKey)
network.Options = getNetworkArgsFromConfList(key, podmanOptionsKey)
@@ -215,9 +214,9 @@ func convertIPAMConfToNetwork(network *types.Network, ipam *ipamConfig, confPath
}
// getNetworkArgsFromConfList returns the map of args in a conflist, argType should be labels or options
func getNetworkArgsFromConfList(args map[string]interface{}, argType string) map[string]string {
func getNetworkArgsFromConfList(args map[string]any, argType string) map[string]string {
if args, ok := args[argType]; ok {
if labels, ok := args.(map[string]interface{}); ok {
if labels, ok := args.(map[string]any); ok {
result := make(map[string]string, len(labels))
for k, v := range labels {
if v, ok := v.(string); ok {
@@ -299,7 +298,7 @@ func (n *cniNetwork) createCNIConfigListFromNetwork(network *types.Network, writ
// the dnsname plugin also needs to be updated for 1.0.0
// TODO change to 1.0.0 when most distros support it
ncList := newNcList(network.Name, "0.4.0", network.Labels, network.Options)
var plugins []interface{}
var plugins []any
switch network.Driver {
case types.BridgeNetworkDriver:
@@ -359,7 +358,7 @@ func convertSpecgenPortsToCNIPorts(ports []types.PortMapping) ([]cniPortMapEntry
protocols := strings.Split(port.Protocol, ",")
for _, protocol := range protocols {
if !pkgutil.StringInSlice(protocol, []string{"tcp", "udp", "sctp"}) {
if !slices.Contains([]string{"tcp", "udp", "sctp"}, protocol) {
return nil, fmt.Errorf("unknown port protocol %s", protocol)
}
cniPort := cniPortMapEntry{
@@ -421,11 +420,11 @@ func parseOptions(networkOptions map[string]string, networkDriver string) (*opti
case types.ModeOption:
switch networkDriver {
case types.MacVLANNetworkDriver:
if !pkgutil.StringInSlice(v, types.ValidMacVLANModes) {
if !slices.Contains(types.ValidMacVLANModes, v) {
return nil, fmt.Errorf("unknown macvlan mode %q", v)
}
case types.IPVLANNetworkDriver:
if !pkgutil.StringInSlice(v, types.ValidIPVLANModes) {
if !slices.Contains(types.ValidIPVLANModes, v) {
return nil, fmt.Errorf("unknown ipvlan mode %q", v)
}
default:

View File

@@ -17,7 +17,6 @@
// limitations under the License.
//go:build linux || freebsd
// +build linux freebsd
package cni

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package cni
@@ -116,7 +115,7 @@ type dnsNameConfig struct {
}
// ncList describes a generic map
type ncList map[string]interface{}
type ncList map[string]any
// newNcList creates a generic map of values with string
// keys and adds in version and network name
@@ -139,8 +138,6 @@ func newNcList(name, version string, labels, options map[string]string) ncList {
// newHostLocalBridge creates a new LocalBridge for host-local
func newHostLocalBridge(name string, isGateWay, ipMasq bool, mtu, vlan int, ipamConf *ipamConfig) *hostLocalBridge {
caps := make(map[string]bool)
caps["ips"] = true
bridge := hostLocalBridge{
PluginType: "bridge",
BrName: name,
@@ -154,7 +151,7 @@ func newHostLocalBridge(name string, isGateWay, ipMasq bool, mtu, vlan int, ipam
bridge.IPAM = *ipamConf
// if we use host-local set the ips cap to ensure we can set static ips via runtime config
if ipamConf.PluginType == types.HostLocalIPAMDriver {
bridge.Capabilities = caps
bridge.Capabilities = map[string]bool{"ips": true}
}
}
return &bridge
@@ -216,13 +213,10 @@ func newIPAMDefaultRoute(isIPv6 bool) (ipamRoute, error) {
// newPortMapPlugin creates a predefined, default portmapping
// configuration
func newPortMapPlugin() portMapConfig {
caps := make(map[string]bool)
caps["portMappings"] = true
p := portMapConfig{
return portMapConfig{
PluginType: "portmap",
Capabilities: caps,
Capabilities: map[string]bool{"portMappings": true},
}
return p
}
// newFirewallPlugin creates a generic firewall plugin
@@ -246,12 +240,10 @@ func newTuningPlugin() tuningConfig {
// newDNSNamePlugin creates the dnsname config with a given
// domainname
func newDNSNamePlugin(domainName string) dnsNameConfig {
caps := make(map[string]bool, 1)
caps["aliases"] = true
return dnsNameConfig{
PluginType: "dnsname",
DomainName: domainName,
Capabilities: caps,
Capabilities: map[string]bool{"aliases": true},
}
}

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package cni
@@ -11,8 +10,8 @@ import (
internalutil "github.com/containers/common/libnetwork/internal/util"
"github.com/containers/common/libnetwork/types"
pkgutil "github.com/containers/common/pkg/util"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)
func (n *cniNetwork) NetworkUpdate(_ string, _ types.NetworkUpdateOptions) error {
@@ -206,7 +205,7 @@ func createIPMACVLAN(network *types.Network) error {
if err != nil {
return err
}
if !pkgutil.StringInSlice(network.NetworkInterface, interfaceNames) {
if !slices.Contains(interfaceNames, network.NetworkInterface) {
return fmt.Errorf("parent interface %s does not exist", network.NetworkInterface)
}
}

View File

@@ -1,5 +1,4 @@
//go:build freebsd
// +build freebsd
package cni

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cni

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package cni

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package cni
@@ -70,8 +69,9 @@ func (n *cniNetwork) Setup(namespacePath string, options types.SetupOptions) (ma
// If we have more than one static ip we need parse the ips via runtime config,
// make sure to add the ips capability to the first plugin otherwise it doesn't get the ips
if len(netOpts.StaticIPs) > 0 && !network.cniNet.Plugins[0].Network.Capabilities["ips"] {
caps := make(map[string]interface{})
caps["capabilities"] = map[string]bool{"ips": true}
caps := map[string]any{
"capabilities": map[string]bool{"ips": true},
}
network.cniNet.Plugins[0], retErr = libcni.InjectConf(network.cniNet.Plugins[0], caps)
if retErr != nil {
return retErr
@@ -174,7 +174,7 @@ func getRuntimeConfig(netns, conName, conID, networkName string, ports []cniPort
// Only K8S_POD_NAME is used by dnsname to get the container name.
{"K8S_POD_NAME", conName},
},
CapabilityArgs: map[string]interface{}{},
CapabilityArgs: map[string]any{},
}
// Propagate environment CNI_ARGS

View File

@@ -9,7 +9,7 @@ import (
"strings"
"github.com/containers/common/pkg/config"
"github.com/containers/common/pkg/util"
"golang.org/x/exp/slices"
)
const (
@@ -220,7 +220,7 @@ func checkIfEntryExists(current HostEntry, entries HostEntries) bool {
if current.IP == rm.IP {
// it is enough if one of the names match, in this case we remove the full entry
for _, name := range current.Names {
if util.StringInSlice(name, rm.Names) {
if slices.Contains(rm.Names, name) {
return true
}
}

View File

@@ -7,13 +7,13 @@ import (
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/libnetwork/util"
"github.com/containers/common/pkg/config"
pkgutil "github.com/containers/common/pkg/util"
"golang.org/x/exp/slices"
)
func CreateBridge(n NetUtil, network *types.Network, usedNetworks []*net.IPNet, subnetPools []config.SubnetPool) error {
if network.NetworkInterface != "" {
bridges := GetBridgeInterfaceNames(n)
if pkgutil.StringInSlice(network.NetworkInterface, bridges) {
if slices.Contains(bridges, network.NetworkInterface) {
return fmt.Errorf("bridge name %s already in use", network.NetworkInterface)
}
if !types.NameRegex.MatchString(network.NetworkInterface) {

View File

@@ -7,7 +7,7 @@ import "github.com/containers/common/libnetwork/types"
// NetUtil is a helper interface which all network interfaces should implement to allow easy code sharing
type NetUtil interface {
// ForEach eaxecutes the given function for each network
// ForEach executes the given function for each network
ForEach(func(types.Network))
// Len returns the number of networks
Len() int

View File

@@ -7,8 +7,8 @@ import (
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/config"
"github.com/containers/common/pkg/util"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)
// GetBridgeInterfaceNames returns all bridge interface names
@@ -51,7 +51,7 @@ func GetFreeDeviceName(n NetUtil) (string, error) {
// Start by 1, 0 is reserved for the default network
for i := 1; i < 1000000; i++ {
deviceName := fmt.Sprintf("%s%d", n.DefaultInterfaceName(), i)
if !util.StringInSlice(deviceName, names) {
if !slices.Contains(names, deviceName) {
logrus.Debugf("found free device name %s", deviceName)
return deviceName, nil
}

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package netavark
@@ -16,14 +15,14 @@ import (
internalutil "github.com/containers/common/libnetwork/internal/util"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/util"
"github.com/containers/storage/pkg/stringid"
"golang.org/x/exp/slices"
)
func sliceRemoveDuplicates(strList []string) []string {
list := make([]string, 0, len(strList))
for _, item := range strList {
if !util.StringInSlice(item, list) {
if !slices.Contains(list, item) {
list = append(list, item)
}
}
@@ -71,7 +70,7 @@ func (n *netavarkNetwork) NetworkUpdate(name string, options types.NetworkUpdate
networkDNSServersBefore := network.NetworkDNSServers
networkDNSServersAfter := []string{}
for _, server := range networkDNSServersBefore {
if util.StringInSlice(server, options.RemoveDNSServers) {
if slices.Contains(options.RemoveDNSServers, server) {
continue
}
networkDNSServersAfter = append(networkDNSServersAfter, server)
@@ -273,7 +272,7 @@ func createIpvlanOrMacvlan(network *types.Network) error {
if err != nil {
return err
}
if !util.StringInSlice(network.NetworkInterface, interfaceNames) {
if !slices.Contains(interfaceNames, network.NetworkInterface) {
return fmt.Errorf("parent interface %s does not exist", network.NetworkInterface)
}
}
@@ -319,11 +318,11 @@ func createIpvlanOrMacvlan(network *types.Network) error {
switch key {
case types.ModeOption:
if isMacVlan {
if !util.StringInSlice(value, types.ValidMacVLANModes) {
if !slices.Contains(types.ValidMacVLANModes, value) {
return fmt.Errorf("unknown macvlan mode %q", value)
}
} else {
if !util.StringInSlice(value, types.ValidIPVLANModes) {
if !slices.Contains(types.ValidIPVLANModes, value) {
return fmt.Errorf("unknown ipvlan mode %q", value)
}
}
@@ -473,7 +472,7 @@ func getAllPlugins(dirs []string) []string {
if err == nil {
for _, entry := range entries {
name := entry.Name()
if !util.StringInSlice(name, plugins) {
if !slices.Contains(plugins, name) {
plugins = append(plugins, name)
}
}

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package netavark

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package netavark
@@ -77,7 +76,7 @@ func getRustLogEnv() string {
// used to marshal the netavark output into it. This can be nil.
// All errors return by this function should be of the type netavarkError
// to provide a helpful error message.
func (n *netavarkNetwork) execNetavark(args []string, needPlugin bool, stdin, result interface{}) error {
func (n *netavarkNetwork) execNetavark(args []string, needPlugin bool, stdin, result any) error {
// set the netavark log level to the same as the podman
env := append(os.Environ(), getRustLogEnv())
// Netavark need access to iptables in $PATH. As it turns out debian doesn't put
@@ -102,11 +101,11 @@ func (n *netavarkNetwork) execNetavark(args []string, needPlugin bool, stdin, re
return n.execBinary(n.netavarkBinary, append(n.getCommonNetavarkOptions(needPlugin), args...), stdin, result, env)
}
func (n *netavarkNetwork) execPlugin(path string, args []string, stdin, result interface{}) error {
func (n *netavarkNetwork) execPlugin(path string, args []string, stdin, result any) error {
return n.execBinary(path, args, stdin, result, nil)
}
func (n *netavarkNetwork) execBinary(path string, args []string, stdin, result interface{}, env []string) error {
func (n *netavarkNetwork) execBinary(path string, args []string, stdin, result any, env []string) error {
stdinR, stdinW, err := os.Pipe()
if err != nil {
return newNetavarkError("failed to create stdin pipe", err)

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package netavark
@@ -48,7 +47,7 @@ func (e *ipamError) Error() string {
return msg
}
func newIPAMError(cause error, msg string, args ...interface{}) *ipamError {
func newIPAMError(cause error, msg string, args ...any) *ipamError {
return &ipamError{
msg: fmt.Sprintf(msg, args...),
cause: cause,

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package netavark

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package netavark
@@ -11,8 +10,8 @@ import (
"github.com/containers/common/libnetwork/internal/util"
"github.com/containers/common/libnetwork/types"
pkgutil "github.com/containers/common/pkg/util"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)
type netavarkOptions struct {
@@ -175,7 +174,7 @@ func (n *netavarkNetwork) convertNetOpts(opts types.NetworkOptions) (*netavarkOp
return nil, false, err
}
netavarkOptions.Networks[network] = net
if !pkgutil.StringInSlice(net.Driver, builtinDrivers) {
if !slices.Contains(builtinDrivers, net.Driver) {
needsPlugin = true
}
}

View File

@@ -1,5 +1,4 @@
//go:build linux || freebsd
// +build linux freebsd
package network

View File

@@ -7,9 +7,9 @@ import (
"path/filepath"
"strings"
"github.com/containers/common/pkg/util"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)
const (
@@ -111,7 +111,7 @@ func getDefaultResolvConf(params *Params) ([]byte, bool, error) {
// unsetSearchDomainsIfNeeded removes the search domain when they contain a single dot as element.
func unsetSearchDomainsIfNeeded(searches []string) []string {
if util.StringInSlice(".", searches) {
if slices.Contains(searches, ".") {
return nil
}
return searches
@@ -173,7 +173,7 @@ func Remove(path string, nameservers []string) error {
oldNameservers := getNameservers(contents)
newNameserver := make([]string, 0, len(oldNameservers))
for _, ns := range oldNameservers {
if !util.StringInSlice(ns, nameservers) {
if !slices.Contains(nameservers, ns) {
newNameserver = append(newNameserver, ns)
}
}

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package slirp4netns
@@ -706,7 +705,7 @@ func openSlirp4netnsPort(apiSocket, proto, hostip string, hostport, guestport ui
}
// if there is no 'error' key in the received JSON data, then the operation was
// successful.
var y map[string]interface{}
var y map[string]any
if err := json.Unmarshal(buf[0:readLength], &y); err != nil {
return fmt.Errorf("parsing error status from slirp4netns: %w", err)
}

View File

@@ -7,6 +7,7 @@ import (
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/filters"
"github.com/containers/common/pkg/util"
"golang.org/x/exp/slices"
)
func GenerateNetworkFilters(f map[string][]string) ([]types.FilterFunc, error) {
@@ -32,7 +33,7 @@ func createFilterFuncs(key string, filterValues []string) (types.FilterFunc, err
case types.Driver:
// matches network driver
return func(net types.Network) bool {
return util.StringInSlice(net.Driver, filterValues)
return slices.Contains(filterValues, net.Driver)
}, nil
case "id":

View File

@@ -1,5 +1,4 @@
//go:build linux && apparmor
// +build linux,apparmor
package apparmor

View File

@@ -1,5 +1,4 @@
//go:build linux && apparmor
// +build linux,apparmor
package apparmor

View File

@@ -1,5 +1,4 @@
//go:build !linux || !apparmor
// +build !linux !apparmor
package apparmor

View File

@@ -13,6 +13,7 @@ import (
"sync"
"github.com/syndtr/gocapability/capability"
"golang.org/x/exp/slices"
)
var (
@@ -54,16 +55,6 @@ func init() {
}
}
// stringInSlice determines if a string is in a string slice, returns bool
func stringInSlice(s string, sl []string) bool {
for _, i := range sl {
if i == s {
return true
}
}
return false
}
var (
boundingSetOnce sync.Once
boundingSetRet []string
@@ -115,7 +106,7 @@ func NormalizeCapabilities(caps []string) ([]string, error) {
if !strings.HasPrefix(c, "CAP_") {
c = "CAP_" + c
}
if !stringInSlice(c, capabilityList) {
if !slices.Contains(capabilityList, c) {
return nil, fmt.Errorf("%q: %w", c, ErrUnknownCapability)
}
normalized = append(normalized, c)
@@ -127,7 +118,7 @@ func NormalizeCapabilities(caps []string) ([]string, error) {
// ValidateCapabilities validates if caps only contains valid capabilities.
func ValidateCapabilities(caps []string) error {
for _, c := range caps {
if !stringInSlice(c, capabilityList) {
if !slices.Contains(capabilityList, c) {
return fmt.Errorf("%q: %w", c, ErrUnknownCapability)
}
}
@@ -159,8 +150,8 @@ func MergeCapabilities(base, adds, drops []string) ([]string, error) {
return nil, err
}
if stringInSlice(All, capDrop) {
if stringInSlice(All, capAdd) {
if slices.Contains(capDrop, All) {
if slices.Contains(capAdd, All) {
return nil, errors.New("adding all caps and removing all caps not allowed")
}
// "Drop" all capabilities; return what's in capAdd instead
@@ -168,7 +159,7 @@ func MergeCapabilities(base, adds, drops []string) ([]string, error) {
return capAdd, nil
}
if stringInSlice(All, capAdd) {
if slices.Contains(capAdd, All) {
base, err = BoundingSet()
if err != nil {
return nil, err
@@ -176,14 +167,14 @@ func MergeCapabilities(base, adds, drops []string) ([]string, error) {
capAdd = []string{}
} else {
for _, add := range capAdd {
if stringInSlice(add, capDrop) {
if slices.Contains(capDrop, add) {
return nil, fmt.Errorf("capability %q cannot be dropped and added", add)
}
}
}
for _, drop := range capDrop {
if stringInSlice(drop, capAdd) {
if slices.Contains(capAdd, drop) {
return nil, fmt.Errorf("capability %q cannot be dropped and added", drop)
}
}
@@ -191,7 +182,7 @@ func MergeCapabilities(base, adds, drops []string) ([]string, error) {
caps := make([]string, 0, len(base)+len(capAdd))
// Drop any capabilities in capDrop that are in base
for _, cap := range base {
if stringInSlice(cap, capDrop) {
if slices.Contains(capDrop, cap) {
continue
}
caps = append(caps, cap)
@@ -199,7 +190,7 @@ func MergeCapabilities(base, adds, drops []string) ([]string, error) {
// Add any capabilities in capAdd that are not in base
for _, cap := range capAdd {
if stringInSlice(cap, base) {
if slices.Contains(base, cap) {
continue
}
caps = append(caps, cap)

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cgroups
@@ -22,6 +21,7 @@ import (
"github.com/opencontainers/runc/libcontainer/cgroups/fs2"
"github.com/opencontainers/runc/libcontainer/configs"
"github.com/sirupsen/logrus"
"golang.org/x/exp/maps"
)
var (
@@ -73,12 +73,13 @@ const (
var handlers map[string]controllerHandler
func init() {
handlers = make(map[string]controllerHandler)
handlers[CPU] = getCPUHandler()
handlers[CPUset] = getCpusetHandler()
handlers[Memory] = getMemoryHandler()
handlers[Pids] = getPidsHandler()
handlers[Blkio] = getBlkioHandler()
handlers = map[string]controllerHandler{
CPU: getCPUHandler(),
CPUset: getCpusetHandler(),
Memory: getMemoryHandler(),
Pids: getPidsHandler(),
Blkio: getBlkioHandler(),
}
}
// getAvailableControllers get the available controllers
@@ -492,10 +493,7 @@ func (c *CgroupControl) AddPid(pid int) error {
return fs2.CreateCgroupPath(path, c.config)
}
names := make([]string, 0, len(handlers))
for n := range handlers {
names = append(names, n)
}
names := maps.Keys(handlers)
for _, c := range c.additionalControllers {
if !c.symlink {

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build !linux
// +build !linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build !linux
// +build !linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build linux
// +build linux
package cgroups

View File

@@ -1,5 +1,4 @@
//go:build !linux
// +build !linux
package cgroupv2

View File

@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package chown

View File

@@ -13,12 +13,12 @@ import (
"github.com/containers/common/internal/attributedstring"
"github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/capabilities"
"github.com/containers/common/pkg/util"
"github.com/containers/storage/pkg/ioutils"
"github.com/containers/storage/pkg/unshare"
units "github.com/docker/go-units"
selinux "github.com/opencontainers/selinux/go-selinux"
"github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
)
const (
@@ -918,7 +918,7 @@ func (c *Config) GetDefaultEnvEx(envHost, httpProxy bool) []string {
}
// Capabilities returns the capabilities parses the Add and Drop capability
// list from the default capabiltiies for the container
// list from the default capabilities for the container
func (c *Config) Capabilities(user string, addCapabilities, dropCapabilities []string) ([]string, error) {
userNotRoot := func(user string) bool {
if user == "" || user == "root" || user == "0" {
@@ -1228,7 +1228,7 @@ func ValidateImageVolumeMode(mode string) error {
if mode == "" {
return nil
}
if util.StringInSlice(mode, validImageVolumeModes) {
if slices.Contains(validImageVolumeModes, mode) {
return nil
}
@@ -1245,7 +1245,7 @@ func (c *Config) FindInitBinary() (string, error) {
if c.Engine.InitPath != "" {
return c.Engine.InitPath, nil
}
// keep old default working to guarantee backwards comapt
// keep old default working to guarantee backwards compat
if _, err := os.Stat(DefaultInitPath); err == nil {
return DefaultInitPath, nil
}

View File

@@ -1,5 +1,4 @@
//go:build !remote
// +build !remote
package config
@@ -67,6 +66,13 @@ func (c *ContainersConfig) validateTZ() error {
"/etc/zoneinfo",
}
// Allow using TZDIR to override the lookupPaths. Ref:
// https://sourceware.org/git/?p=glibc.git;a=blob;f=time/tzfile.c;h=8a923d0cccc927a106dc3e3c641be310893bab4e;hb=HEAD#l149
tzdir := os.Getenv("TZDIR")
if tzdir != "" {
lookupPaths = []string{tzdir}
}
for _, paths := range lookupPaths {
zonePath := filepath.Join(paths, c.TZ)
if _, err := os.Stat(zonePath); err == nil {

View File

@@ -1,5 +1,4 @@
//go:build remote
// +build remote
package config

View File

@@ -1,5 +1,4 @@
//go:build !linux
// +build !linux
package config

View File

@@ -737,6 +737,15 @@ default_sysctls = [
# "/run/current-system/sw/bin/crun",
#]
#crun-vm = [
# "/usr/bin/crun-vm",
# "/usr/local/bin/crun-vm",
# "/usr/local/sbin/crun-vm",
# "/sbin/crun-vm",
# "/bin/crun-vm",
# "/run/current-system/sw/bin/crun-vm",
#]
#kata = [
# "/usr/bin/kata-runtime",
# "/usr/sbin/kata-runtime",

View File

@@ -295,9 +295,8 @@ func defaultMachineConfig() MachineConfig {
// defaultFarmConfig returns the default farms configuration.
func defaultFarmConfig() FarmConfig {
emptyList := make(map[string][]string)
return FarmConfig{
List: emptyList,
List: map[string][]string{},
}
}
@@ -340,7 +339,7 @@ func defaultEngineConfig() (*EngineConfig, error) {
c.HelperBinariesDir.Set(defaultHelperBinariesDir)
if additionalHelperBinariesDir != "" {
// Prioritize addtionalHelperBinariesDir over defaults.
// Prioritize additionalHelperBinariesDir over defaults.
c.HelperBinariesDir.Set(append([]string{additionalHelperBinariesDir}, c.HelperBinariesDir.Get()...))
}
c.HooksDir.Set(DefaultHooksDirs)
@@ -365,6 +364,14 @@ func defaultEngineConfig() (*EngineConfig, error) {
"/bin/crun",
"/run/current-system/sw/bin/crun",
},
"crun-vm": {
"/usr/bin/crun-vm",
"/usr/local/bin/crun-vm",
"/usr/local/sbin/crun-vm",
"/sbin/crun-vm",
"/bin/crun-vm",
"/run/current-system/sw/bin/crun-vm",
},
"crun-wasm": {
"/usr/bin/crun-wasm",
"/usr/sbin/crun-wasm",
@@ -556,7 +563,7 @@ func (c *Config) DNSServers() []string {
return c.Containers.DNSServers.Get()
}
// DNSSerches returns the default DNS searches to add to resolv.conf in containers.
// DNSSearches returns the default DNS searches to add to resolv.conf in containers.
func (c *Config) DNSSearches() []string {
return c.Containers.DNSSearches.Get()
}

View File

@@ -1,5 +1,4 @@
//go:build !freebsd
// +build !freebsd
package config

View File

@@ -1,5 +1,4 @@
//go:build !linux && !windows
// +build !linux,!windows
package config

Some files were not shown because too many files have changed in this diff Show More