diff options
Diffstat (limited to 'pkg/api/handlers')
28 files changed, 1267 insertions, 609 deletions
diff --git a/pkg/api/handlers/compat/containers.go b/pkg/api/handlers/compat/containers.go index e3d51fadf..616f0a138 100644 --- a/pkg/api/handlers/compat/containers.go +++ b/pkg/api/handlers/compat/containers.go @@ -369,26 +369,28 @@ func LibpodToContainer(l *libpod.Container, sz bool) (*handlers.Container, error return nil, err } - return &handlers.Container{Container: types.Container{ - ID: l.ID(), - Names: []string{fmt.Sprintf("/%s", l.Name())}, - Image: imageName, - ImageID: "sha256:" + imageID, - Command: strings.Join(l.Command(), " "), - Created: l.CreatedTime().Unix(), - Ports: ports, - SizeRw: sizeRW, - SizeRootFs: sizeRootFs, - Labels: l.Labels(), - State: stateStr, - Status: status, - HostConfig: struct { - NetworkMode string `json:",omitempty"` - }{ - "host"}, - NetworkSettings: &networkSettings, - Mounts: mounts, - }, + return &handlers.Container{ + Container: types.Container{ + ID: l.ID(), + Names: []string{fmt.Sprintf("/%s", l.Name())}, + Image: imageName, + ImageID: "sha256:" + imageID, + Command: strings.Join(l.Command(), " "), + Created: l.CreatedTime().Unix(), + Ports: ports, + SizeRw: sizeRW, + SizeRootFs: sizeRootFs, + Labels: l.Labels(), + State: stateStr, + Status: status, + HostConfig: struct { + NetworkMode string `json:",omitempty"` + }{ + "host", + }, + NetworkSettings: &networkSettings, + Mounts: mounts, + }, ContainerCreateConfig: types.ContainerCreateConfig{}, }, nil } diff --git a/pkg/api/handlers/compat/containers_create.go b/pkg/api/handlers/compat/containers_create.go index cd592a975..b9b7f6708 100644 --- a/pkg/api/handlers/compat/containers_create.go +++ b/pkg/api/handlers/compat/containers_create.go @@ -2,18 +2,29 @@ package compat import ( "encoding/json" + "fmt" + "net" "net/http" + "os" + "path/filepath" + "strconv" + "strings" - "github.com/containers/podman/v4/cmd/podman/common" + "github.com/containers/common/libnetwork/types" + "github.com/containers/common/pkg/cgroups" + "github.com/containers/common/pkg/config" "github.com/containers/podman/v4/libpod" + "github.com/containers/podman/v4/libpod/define" "github.com/containers/podman/v4/pkg/api/handlers" "github.com/containers/podman/v4/pkg/api/handlers/utils" api "github.com/containers/podman/v4/pkg/api/types" "github.com/containers/podman/v4/pkg/domain/entities" "github.com/containers/podman/v4/pkg/domain/infra/abi" + "github.com/containers/podman/v4/pkg/rootless" "github.com/containers/podman/v4/pkg/specgen" "github.com/containers/podman/v4/pkg/specgenutil" "github.com/containers/storage" + "github.com/docker/docker/api/types/mount" "github.com/gorilla/schema" "github.com/pkg/errors" ) @@ -70,7 +81,7 @@ func CreateContainer(w http.ResponseWriter, r *http.Request) { } // Take body structure and convert to cliopts - cliOpts, args, err := common.ContainerCreateToContainerCLIOpts(body, rtc) + cliOpts, args, err := cliOpts(body, rtc) if err != nil { utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "make cli opts()")) return @@ -107,3 +118,456 @@ func CreateContainer(w http.ResponseWriter, r *http.Request) { } utils.WriteResponse(w, http.StatusCreated, createResponse) } + +func stringMaptoArray(m map[string]string) []string { + a := make([]string, 0, len(m)) + for k, v := range m { + a = append(a, fmt.Sprintf("%s=%s", k, v)) + } + return a +} + +// cliOpts converts a compat input struct to cliopts +func cliOpts(cc handlers.CreateContainerConfig, rtc *config.Config) (*entities.ContainerCreateOptions, []string, error) { + var ( + capAdd []string + cappDrop []string + entrypoint *string + init bool + specPorts []types.PortMapping + ) + + if cc.HostConfig.Init != nil { + init = *cc.HostConfig.Init + } + + // Iterate devices and convert to CLI expected string + devices := make([]string, 0, len(cc.HostConfig.Devices)) + for _, dev := range cc.HostConfig.Devices { + devices = append(devices, fmt.Sprintf("%s:%s:%s", dev.PathOnHost, dev.PathInContainer, dev.CgroupPermissions)) + } + + // iterate blkreaddevicebps + readBps := make([]string, 0, len(cc.HostConfig.BlkioDeviceReadBps)) + for _, dev := range cc.HostConfig.BlkioDeviceReadBps { + readBps = append(readBps, dev.String()) + } + + // iterate blkreaddeviceiops + readIops := make([]string, 0, len(cc.HostConfig.BlkioDeviceReadIOps)) + for _, dev := range cc.HostConfig.BlkioDeviceReadIOps { + readIops = append(readIops, dev.String()) + } + + // iterate blkwritedevicebps + writeBps := make([]string, 0, len(cc.HostConfig.BlkioDeviceWriteBps)) + for _, dev := range cc.HostConfig.BlkioDeviceWriteBps { + writeBps = append(writeBps, dev.String()) + } + + // iterate blkwritedeviceiops + writeIops := make([]string, 0, len(cc.HostConfig.BlkioDeviceWriteIOps)) + for _, dev := range cc.HostConfig.BlkioDeviceWriteIOps { + writeIops = append(writeIops, dev.String()) + } + + // entrypoint + // can be a string or slice. if it is a slice, we need to + // marshall it to json; otherwise it should just be the string + // value + if len(cc.Config.Entrypoint) > 0 { + entrypoint = &cc.Config.Entrypoint[0] + if len(cc.Config.Entrypoint) > 1 { + b, err := json.Marshal(cc.Config.Entrypoint) + if err != nil { + return nil, nil, err + } + jsonString := string(b) + entrypoint = &jsonString + } + } + + // expose ports + expose := make([]string, 0, len(cc.Config.ExposedPorts)) + for p := range cc.Config.ExposedPorts { + expose = append(expose, fmt.Sprintf("%s/%s", p.Port(), p.Proto())) + } + + // mounts type=tmpfs/bind,source=...,target=...=,opt=val + volSources := make(map[string]bool) + volDestinations := make(map[string]bool) + mounts := make([]string, 0, len(cc.HostConfig.Mounts)) + var builder strings.Builder + for _, m := range cc.HostConfig.Mounts { + addField(&builder, "type", string(m.Type)) + addField(&builder, "source", m.Source) + addField(&builder, "target", m.Target) + + // Store source/dest so we don't add duplicates if a volume is + // also mentioned in cc.Volumes. + // Which Docker Compose v2.0 does, for unclear reasons... + volSources[m.Source] = true + volDestinations[m.Target] = true + + if m.ReadOnly { + addField(&builder, "ro", "true") + } + addField(&builder, "consistency", string(m.Consistency)) + // Map any specialized mount options that intersect between *Options and cli options + switch m.Type { + case mount.TypeBind: + if m.BindOptions != nil { + addField(&builder, "bind-propagation", string(m.BindOptions.Propagation)) + addField(&builder, "bind-nonrecursive", strconv.FormatBool(m.BindOptions.NonRecursive)) + } + case mount.TypeTmpfs: + if m.TmpfsOptions != nil { + addField(&builder, "tmpfs-size", strconv.FormatInt(m.TmpfsOptions.SizeBytes, 10)) + addField(&builder, "tmpfs-mode", strconv.FormatUint(uint64(m.TmpfsOptions.Mode), 8)) + } + case mount.TypeVolume: + // All current VolumeOpts are handled above + // See vendor/github.com/containers/common/pkg/parse/parse.go:ValidateVolumeOpts() + } + mounts = append(mounts, builder.String()) + builder.Reset() + } + + // dns + dns := make([]net.IP, 0, len(cc.HostConfig.DNS)) + for _, d := range cc.HostConfig.DNS { + dns = append(dns, net.ParseIP(d)) + } + + // publish + for port, pbs := range cc.HostConfig.PortBindings { + for _, pb := range pbs { + var hostport int + var err error + if pb.HostPort != "" { + hostport, err = strconv.Atoi(pb.HostPort) + } + if err != nil { + return nil, nil, err + } + tmpPort := types.PortMapping{ + HostIP: pb.HostIP, + ContainerPort: uint16(port.Int()), + HostPort: uint16(hostport), + Range: 0, + Protocol: port.Proto(), + } + specPorts = append(specPorts, tmpPort) + } + } + + // netMode + nsmode, networks, netOpts, err := specgen.ParseNetworkFlag([]string{string(cc.HostConfig.NetworkMode)}) + if err != nil { + return nil, nil, err + } + + // network + // Note: we cannot emulate compat exactly here. we only allow specifics of networks to be + // defined when there is only one network. + netInfo := entities.NetOptions{ + AddHosts: cc.HostConfig.ExtraHosts, + DNSOptions: cc.HostConfig.DNSOptions, + DNSSearch: cc.HostConfig.DNSSearch, + DNSServers: dns, + Network: nsmode, + PublishPorts: specPorts, + NetworkOptions: netOpts, + } + + // network names + switch { + case len(cc.NetworkingConfig.EndpointsConfig) > 0: + endpointsConfig := cc.NetworkingConfig.EndpointsConfig + networks := make(map[string]types.PerNetworkOptions, len(endpointsConfig)) + for netName, endpoint := range endpointsConfig { + netOpts := types.PerNetworkOptions{} + if endpoint != nil { + netOpts.Aliases = endpoint.Aliases + + // if IP address is provided + if len(endpoint.IPAddress) > 0 { + staticIP := net.ParseIP(endpoint.IPAddress) + if staticIP == nil { + return nil, nil, errors.Errorf("failed to parse the ip address %q", endpoint.IPAddress) + } + netOpts.StaticIPs = append(netOpts.StaticIPs, staticIP) + } + + if endpoint.IPAMConfig != nil { + // if IPAMConfig.IPv4Address is provided + if len(endpoint.IPAMConfig.IPv4Address) > 0 { + staticIP := net.ParseIP(endpoint.IPAMConfig.IPv4Address) + if staticIP == nil { + return nil, nil, errors.Errorf("failed to parse the ipv4 address %q", endpoint.IPAMConfig.IPv4Address) + } + netOpts.StaticIPs = append(netOpts.StaticIPs, staticIP) + } + // if IPAMConfig.IPv6Address is provided + if len(endpoint.IPAMConfig.IPv6Address) > 0 { + staticIP := net.ParseIP(endpoint.IPAMConfig.IPv6Address) + if staticIP == nil { + return nil, nil, errors.Errorf("failed to parse the ipv6 address %q", endpoint.IPAMConfig.IPv6Address) + } + netOpts.StaticIPs = append(netOpts.StaticIPs, staticIP) + } + } + // If MAC address is provided + if len(endpoint.MacAddress) > 0 { + staticMac, err := net.ParseMAC(endpoint.MacAddress) + if err != nil { + return nil, nil, errors.Errorf("failed to parse the mac address %q", endpoint.MacAddress) + } + netOpts.StaticMAC = types.HardwareAddr(staticMac) + } + } + + networks[netName] = netOpts + } + + netInfo.Networks = networks + case len(cc.HostConfig.NetworkMode) > 0: + netInfo.Networks = networks + } + + parsedTmp := make([]string, 0, len(cc.HostConfig.Tmpfs)) + for path, options := range cc.HostConfig.Tmpfs { + finalString := path + if options != "" { + finalString += ":" + options + } + parsedTmp = append(parsedTmp, finalString) + } + + // Note: several options here are marked as "don't need". this is based + // on speculation by Matt and I. We think that these come into play later + // like with start. We believe this is just a difference in podman/compat + cliOpts := entities.ContainerCreateOptions{ + // Attach: nil, // don't need? + Authfile: "", + CapAdd: append(capAdd, cc.HostConfig.CapAdd...), + CapDrop: append(cappDrop, cc.HostConfig.CapDrop...), + CgroupParent: cc.HostConfig.CgroupParent, + CIDFile: cc.HostConfig.ContainerIDFile, + CPUPeriod: uint64(cc.HostConfig.CPUPeriod), + CPUQuota: cc.HostConfig.CPUQuota, + CPURTPeriod: uint64(cc.HostConfig.CPURealtimePeriod), + CPURTRuntime: cc.HostConfig.CPURealtimeRuntime, + CPUShares: uint64(cc.HostConfig.CPUShares), + // CPUS: 0, // don't need? + CPUSetCPUs: cc.HostConfig.CpusetCpus, + CPUSetMems: cc.HostConfig.CpusetMems, + // Detach: false, // don't need + // DetachKeys: "", // don't need + Devices: devices, + DeviceCgroupRule: nil, + DeviceReadBPs: readBps, + DeviceReadIOPs: readIops, + DeviceWriteBPs: writeBps, + DeviceWriteIOPs: writeIops, + Entrypoint: entrypoint, + Env: cc.Config.Env, + Expose: expose, + GroupAdd: cc.HostConfig.GroupAdd, + Hostname: cc.Config.Hostname, + ImageVolume: "bind", + Init: init, + Interactive: cc.Config.OpenStdin, + IPC: string(cc.HostConfig.IpcMode), + Label: stringMaptoArray(cc.Config.Labels), + LogDriver: cc.HostConfig.LogConfig.Type, + LogOptions: stringMaptoArray(cc.HostConfig.LogConfig.Config), + Name: cc.Name, + OOMScoreAdj: &cc.HostConfig.OomScoreAdj, + Arch: "", + OS: "", + Variant: "", + PID: string(cc.HostConfig.PidMode), + PIDsLimit: cc.HostConfig.PidsLimit, + Privileged: cc.HostConfig.Privileged, + PublishAll: cc.HostConfig.PublishAllPorts, + Quiet: false, + ReadOnly: cc.HostConfig.ReadonlyRootfs, + ReadOnlyTmpFS: true, // podman default + Rm: cc.HostConfig.AutoRemove, + SecurityOpt: cc.HostConfig.SecurityOpt, + StopSignal: cc.Config.StopSignal, + StorageOpts: stringMaptoArray(cc.HostConfig.StorageOpt), + Sysctl: stringMaptoArray(cc.HostConfig.Sysctls), + Systemd: "true", // podman default + TmpFS: parsedTmp, + TTY: cc.Config.Tty, + UnsetEnv: cc.UnsetEnv, + UnsetEnvAll: cc.UnsetEnvAll, + User: cc.Config.User, + UserNS: string(cc.HostConfig.UsernsMode), + UTS: string(cc.HostConfig.UTSMode), + Mount: mounts, + VolumesFrom: cc.HostConfig.VolumesFrom, + Workdir: cc.Config.WorkingDir, + Net: &netInfo, + HealthInterval: define.DefaultHealthCheckInterval, + HealthRetries: define.DefaultHealthCheckRetries, + HealthTimeout: define.DefaultHealthCheckTimeout, + HealthStartPeriod: define.DefaultHealthCheckStartPeriod, + } + if !rootless.IsRootless() { + var ulimits []string + if len(cc.HostConfig.Ulimits) > 0 { + for _, ul := range cc.HostConfig.Ulimits { + ulimits = append(ulimits, ul.String()) + } + cliOpts.Ulimit = ulimits + } + } + if cc.HostConfig.Resources.NanoCPUs > 0 { + if cliOpts.CPUPeriod != 0 || cliOpts.CPUQuota != 0 { + return nil, nil, errors.Errorf("NanoCpus conflicts with CpuPeriod and CpuQuota") + } + cliOpts.CPUPeriod = 100000 + cliOpts.CPUQuota = cc.HostConfig.Resources.NanoCPUs / 10000 + } + + // volumes + for _, vol := range cc.HostConfig.Binds { + cliOpts.Volume = append(cliOpts.Volume, vol) + // Extract the destination so we don't add duplicate mounts in + // the volumes phase. + splitVol := strings.SplitN(vol, ":", 3) + switch len(splitVol) { + case 1: + volDestinations[vol] = true + default: + volSources[splitVol[0]] = true + volDestinations[splitVol[1]] = true + } + } + // Anonymous volumes are added differently from other volumes, in their + // own special field, for reasons known only to Docker. Still use the + // format of `-v` so we can just append them in there. + // Unfortunately, these may be duplicates of existing mounts in Binds. + // So... We need to catch that. + // This also handles volumes duplicated between cc.HostConfig.Mounts and + // cc.Volumes, as seen in compose v2.0. + for vol := range cc.Volumes { + if _, ok := volDestinations[filepath.Clean(vol)]; ok { + continue + } + cliOpts.Volume = append(cliOpts.Volume, vol) + } + // Make mount points for compat volumes + for vol := range volSources { + // This might be a named volume. + // Assume it is if it's not an absolute path. + if !filepath.IsAbs(vol) { + continue + } + // If volume already exists, there is nothing to do + if _, err := os.Stat(vol); err == nil { + continue + } + if err := os.MkdirAll(vol, 0o755); err != nil { + if !os.IsExist(err) { + return nil, nil, errors.Wrapf(err, "error making volume mountpoint for volume %s", vol) + } + } + } + if len(cc.HostConfig.BlkioWeightDevice) > 0 { + devices := make([]string, 0, len(cc.HostConfig.BlkioWeightDevice)) + for _, d := range cc.HostConfig.BlkioWeightDevice { + devices = append(devices, d.String()) + } + cliOpts.BlkIOWeightDevice = devices + } + if cc.HostConfig.BlkioWeight > 0 { + cliOpts.BlkIOWeight = strconv.Itoa(int(cc.HostConfig.BlkioWeight)) + } + + if cc.HostConfig.Memory > 0 { + cliOpts.Memory = strconv.Itoa(int(cc.HostConfig.Memory)) + } + + if cc.HostConfig.MemoryReservation > 0 { + cliOpts.MemoryReservation = strconv.Itoa(int(cc.HostConfig.MemoryReservation)) + } + + cgroupsv2, err := cgroups.IsCgroup2UnifiedMode() + if err != nil { + return nil, nil, err + } + if cc.HostConfig.MemorySwap > 0 && (!rootless.IsRootless() || (rootless.IsRootless() && cgroupsv2)) { + cliOpts.MemorySwap = strconv.Itoa(int(cc.HostConfig.MemorySwap)) + } + + if cc.Config.StopTimeout != nil { + cliOpts.StopTimeout = uint(*cc.Config.StopTimeout) + } + + if cc.HostConfig.ShmSize > 0 { + cliOpts.ShmSize = strconv.Itoa(int(cc.HostConfig.ShmSize)) + } + + if len(cc.HostConfig.RestartPolicy.Name) > 0 { + policy := cc.HostConfig.RestartPolicy.Name + // only add restart count on failure + if cc.HostConfig.RestartPolicy.IsOnFailure() { + policy += fmt.Sprintf(":%d", cc.HostConfig.RestartPolicy.MaximumRetryCount) + } + cliOpts.Restart = policy + } + + if cc.HostConfig.MemorySwappiness != nil && (!rootless.IsRootless() || rootless.IsRootless() && cgroupsv2 && rtc.Engine.CgroupManager == "systemd") { + cliOpts.MemorySwappiness = *cc.HostConfig.MemorySwappiness + } else { + cliOpts.MemorySwappiness = -1 + } + if cc.HostConfig.OomKillDisable != nil { + cliOpts.OOMKillDisable = *cc.HostConfig.OomKillDisable + } + if cc.Config.Healthcheck != nil { + finCmd := "" + for _, str := range cc.Config.Healthcheck.Test { + finCmd = finCmd + str + " " + } + if len(finCmd) > 1 { + finCmd = finCmd[:len(finCmd)-1] + } + cliOpts.HealthCmd = finCmd + if cc.Config.Healthcheck.Interval > 0 { + cliOpts.HealthInterval = cc.Config.Healthcheck.Interval.String() + } + if cc.Config.Healthcheck.Retries > 0 { + cliOpts.HealthRetries = uint(cc.Config.Healthcheck.Retries) + } + if cc.Config.Healthcheck.StartPeriod > 0 { + cliOpts.HealthStartPeriod = cc.Config.Healthcheck.StartPeriod.String() + } + if cc.Config.Healthcheck.Timeout > 0 { + cliOpts.HealthTimeout = cc.Config.Healthcheck.Timeout.String() + } + } + + // specgen assumes the image name is arg[0] + cmd := []string{cc.Config.Image} + cmd = append(cmd, cc.Config.Cmd...) + return &cliOpts, cmd, nil +} + +// addField is a helper function to populate mount options +func addField(b *strings.Builder, name, value string) { + if value == "" { + return + } + + if b.Len() > 0 { + b.WriteRune(',') + } + b.WriteString(name) + b.WriteRune('=') + b.WriteString(value) +} diff --git a/pkg/api/handlers/compat/events.go b/pkg/api/handlers/compat/events.go index 03b3d54bc..6bcb7bd32 100644 --- a/pkg/api/handlers/compat/events.go +++ b/pkg/api/handlers/compat/events.go @@ -63,7 +63,7 @@ func GetEvents(w http.ResponseWriter, r *http.Request) { errorChannel <- runtime.Events(r.Context(), readOpts) }() - var flush = func() {} + flush := func() {} if flusher, ok := w.(http.Flusher); ok { flush = flusher.Flush } diff --git a/pkg/api/handlers/compat/exec.go b/pkg/api/handlers/compat/exec.go index def16d1b5..a8b45c685 100644 --- a/pkg/api/handlers/compat/exec.go +++ b/pkg/api/handlers/compat/exec.go @@ -11,6 +11,7 @@ import ( "github.com/containers/podman/v4/pkg/api/handlers/utils" "github.com/containers/podman/v4/pkg/api/server/idle" api "github.com/containers/podman/v4/pkg/api/types" + "github.com/containers/podman/v4/pkg/domain/entities" "github.com/containers/podman/v4/pkg/specgenutil" "github.com/gorilla/mux" "github.com/pkg/errors" @@ -93,10 +94,7 @@ func ExecCreateHandler(w http.ResponseWriter, r *http.Request) { return } - resp := new(handlers.ExecCreateResponse) - resp.ID = sessID - - utils.WriteResponse(w, http.StatusCreated, resp) + utils.WriteResponse(w, http.StatusCreated, entities.IDResponse{ID: sessID}) } // ExecInspectHandler inspects a given exec session. diff --git a/pkg/api/handlers/compat/images.go b/pkg/api/handlers/compat/images.go index a690cdd40..8c4dea327 100644 --- a/pkg/api/handlers/compat/images.go +++ b/pkg/api/handlers/compat/images.go @@ -165,7 +165,7 @@ func CommitContainer(w http.ResponseWriter, r *http.Request) { utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "CommitFailure")) return } - utils.WriteResponse(w, http.StatusCreated, handlers.IDResponse{ID: commitImage.ID()}) // nolint + utils.WriteResponse(w, http.StatusCreated, entities.IDResponse{ID: commitImage.ID()}) // nolint } func CreateImageFromSrc(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/api/handlers/compat/images_build.go b/pkg/api/handlers/compat/images_build.go index 1a0ac6801..bcd102901 100644 --- a/pkg/api/handlers/compat/images_build.go +++ b/pkg/api/handlers/compat/images_build.go @@ -776,7 +776,7 @@ func extractTarFile(r *http.Request) (string, error) { } path := filepath.Join(anchorDir, "tarBall") - tarBall, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) + tarBall, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return "", err } @@ -790,7 +790,7 @@ func extractTarFile(r *http.Request) (string, error) { } buildDir := filepath.Join(anchorDir, "build") - err = os.Mkdir(buildDir, 0700) + err = os.Mkdir(buildDir, 0o700) if err != nil { return "", err } diff --git a/pkg/api/handlers/compat/images_prune.go b/pkg/api/handlers/compat/images_prune.go index 46524fcff..02cadbbbe 100644 --- a/pkg/api/handlers/compat/images_prune.go +++ b/pkg/api/handlers/compat/images_prune.go @@ -17,9 +17,7 @@ import ( ) func PruneImages(w http.ResponseWriter, r *http.Request) { - var ( - filters []string - ) + var filters []string runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) filterMap, err := util.PrepareFilters(r) diff --git a/pkg/api/handlers/compat/info.go b/pkg/api/handlers/compat/info.go index 6286fdaee..85547570a 100644 --- a/pkg/api/handlers/compat/info.go +++ b/pkg/api/handlers/compat/info.go @@ -53,75 +53,76 @@ func GetInfo(w http.ResponseWriter, r *http.Request) { // FIXME: Need to expose if runtime supports Checkpointing // liveRestoreEnabled := criu.CheckForCriu() && configInfo.RuntimeSupportsCheckpoint() - info := &handlers.Info{Info: docker.Info{ - Architecture: goRuntime.GOARCH, - BridgeNfIP6tables: !sysInfo.BridgeNFCallIP6TablesDisabled, - BridgeNfIptables: !sysInfo.BridgeNFCallIPTablesDisabled, - CPUCfsPeriod: sysInfo.CPUCfsPeriod, - CPUCfsQuota: sysInfo.CPUCfsQuota, - CPUSet: sysInfo.Cpuset, - CPUShares: sysInfo.CPUShares, - CgroupDriver: configInfo.Engine.CgroupManager, - ClusterAdvertise: "", - ClusterStore: "", - ContainerdCommit: docker.Commit{}, - Containers: infoData.Store.ContainerStore.Number, - ContainersPaused: stateInfo[define.ContainerStatePaused], - ContainersRunning: stateInfo[define.ContainerStateRunning], - ContainersStopped: stateInfo[define.ContainerStateStopped] + stateInfo[define.ContainerStateExited], - Debug: log.IsLevelEnabled(log.DebugLevel), - DefaultRuntime: configInfo.Engine.OCIRuntime, - DockerRootDir: infoData.Store.GraphRoot, - Driver: infoData.Store.GraphDriverName, - DriverStatus: getGraphStatus(infoData.Store.GraphStatus), - ExperimentalBuild: true, - GenericResources: nil, - HTTPProxy: getEnv("http_proxy"), - HTTPSProxy: getEnv("https_proxy"), - ID: uuid.New().String(), - IPv4Forwarding: !sysInfo.IPv4ForwardingDisabled, - Images: infoData.Store.ImageStore.Number, - IndexServerAddress: "", - InitBinary: "", - InitCommit: docker.Commit{}, - Isolation: "", - KernelMemoryTCP: false, - KernelVersion: infoData.Host.Kernel, - Labels: nil, - LiveRestoreEnabled: false, - LoggingDriver: "", - MemTotal: infoData.Host.MemTotal, - MemoryLimit: sysInfo.MemoryLimit, - NCPU: goRuntime.NumCPU(), - NEventsListener: 0, - NFd: getFdCount(), - NGoroutines: goRuntime.NumGoroutine(), - Name: infoData.Host.Hostname, - NoProxy: getEnv("no_proxy"), - OSType: goRuntime.GOOS, - OSVersion: infoData.Host.Distribution.Version, - OomKillDisable: sysInfo.OomKillDisable, - OperatingSystem: infoData.Host.Distribution.Distribution, - PidsLimit: sysInfo.PidsLimit, - Plugins: docker.PluginsInfo{ - Volume: infoData.Plugins.Volume, - Network: infoData.Plugins.Network, - Log: infoData.Plugins.Log, + info := &handlers.Info{ + Info: docker.Info{ + Architecture: goRuntime.GOARCH, + BridgeNfIP6tables: !sysInfo.BridgeNFCallIP6TablesDisabled, + BridgeNfIptables: !sysInfo.BridgeNFCallIPTablesDisabled, + CPUCfsPeriod: sysInfo.CPUCfsPeriod, + CPUCfsQuota: sysInfo.CPUCfsQuota, + CPUSet: sysInfo.Cpuset, + CPUShares: sysInfo.CPUShares, + CgroupDriver: configInfo.Engine.CgroupManager, + ClusterAdvertise: "", + ClusterStore: "", + ContainerdCommit: docker.Commit{}, + Containers: infoData.Store.ContainerStore.Number, + ContainersPaused: stateInfo[define.ContainerStatePaused], + ContainersRunning: stateInfo[define.ContainerStateRunning], + ContainersStopped: stateInfo[define.ContainerStateStopped] + stateInfo[define.ContainerStateExited], + Debug: log.IsLevelEnabled(log.DebugLevel), + DefaultRuntime: configInfo.Engine.OCIRuntime, + DockerRootDir: infoData.Store.GraphRoot, + Driver: infoData.Store.GraphDriverName, + DriverStatus: getGraphStatus(infoData.Store.GraphStatus), + ExperimentalBuild: true, + GenericResources: nil, + HTTPProxy: getEnv("http_proxy"), + HTTPSProxy: getEnv("https_proxy"), + ID: uuid.New().String(), + IPv4Forwarding: !sysInfo.IPv4ForwardingDisabled, + Images: infoData.Store.ImageStore.Number, + IndexServerAddress: "", + InitBinary: "", + InitCommit: docker.Commit{}, + Isolation: "", + KernelMemoryTCP: false, + KernelVersion: infoData.Host.Kernel, + Labels: nil, + LiveRestoreEnabled: false, + LoggingDriver: "", + MemTotal: infoData.Host.MemTotal, + MemoryLimit: sysInfo.MemoryLimit, + NCPU: goRuntime.NumCPU(), + NEventsListener: 0, + NFd: getFdCount(), + NGoroutines: goRuntime.NumGoroutine(), + Name: infoData.Host.Hostname, + NoProxy: getEnv("no_proxy"), + OSType: goRuntime.GOOS, + OSVersion: infoData.Host.Distribution.Version, + OomKillDisable: sysInfo.OomKillDisable, + OperatingSystem: infoData.Host.Distribution.Distribution, + PidsLimit: sysInfo.PidsLimit, + Plugins: docker.PluginsInfo{ + Volume: infoData.Plugins.Volume, + Network: infoData.Plugins.Network, + Log: infoData.Plugins.Log, + }, + ProductLicense: "Apache-2.0", + RegistryConfig: getServiceConfig(runtime), + RuncCommit: docker.Commit{}, + Runtimes: getRuntimes(configInfo), + SecurityOptions: getSecOpts(sysInfo), + ServerVersion: versionInfo.Version, + SwapLimit: sysInfo.SwapLimit, + Swarm: swarm.Info{ + LocalNodeState: swarm.LocalNodeStateInactive, + }, + SystemStatus: nil, + SystemTime: time.Now().Format(time.RFC3339Nano), + Warnings: []string{}, }, - ProductLicense: "Apache-2.0", - RegistryConfig: getServiceConfig(runtime), - RuncCommit: docker.Commit{}, - Runtimes: getRuntimes(configInfo), - SecurityOptions: getSecOpts(sysInfo), - ServerVersion: versionInfo.Version, - SwapLimit: sysInfo.SwapLimit, - Swarm: swarm.Info{ - LocalNodeState: swarm.LocalNodeStateInactive, - }, - SystemStatus: nil, - SystemTime: time.Now().Format(time.RFC3339Nano), - Warnings: []string{}, - }, BuildahVersion: infoData.Host.BuildahVersion, CPURealtimePeriod: sysInfo.CPURealtimePeriod, CPURealtimeRuntime: sysInfo.CPURealtimeRuntime, @@ -186,7 +187,7 @@ func getSecOpts(sysInfo *sysinfo.SysInfo) []string { } func getRuntimes(configInfo *config.Config) map[string]docker.Runtime { - var runtimes = map[string]docker.Runtime{} + runtimes := map[string]docker.Runtime{} for name, paths := range configInfo.Engine.OCIRuntimes { runtimes[name] = docker.Runtime{ Path: paths[0], @@ -206,7 +207,7 @@ func getFdCount() (count int) { // Just ignoring Container errors here... func getContainersState(r *libpod.Runtime) map[define.ContainerStatus]int { - var states = map[define.ContainerStatus]int{} + states := map[define.ContainerStatus]int{} ctnrs, err := r.GetAllContainers() if err == nil { for _, ctnr := range ctnrs { diff --git a/pkg/api/handlers/compat/networks.go b/pkg/api/handlers/compat/networks.go index 89d914e0a..6fdd5c6a7 100644 --- a/pkg/api/handlers/compat/networks.go +++ b/pkg/api/handlers/compat/networks.go @@ -298,9 +298,7 @@ func RemoveNetwork(w http.ResponseWriter, r *http.Request) { func Connect(w http.ResponseWriter, r *http.Request) { runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - var ( - netConnect types.NetworkConnect - ) + var netConnect types.NetworkConnect if err := json.NewDecoder(r.Body).Decode(&netConnect); err != nil { utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "Decode()")) return diff --git a/pkg/api/handlers/compat/secrets.go b/pkg/api/handlers/compat/secrets.go index 0c2306dc8..5031bf76b 100644 --- a/pkg/api/handlers/compat/secrets.go +++ b/pkg/api/handlers/compat/secrets.go @@ -16,9 +16,7 @@ import ( ) func ListSecrets(w http.ResponseWriter, r *http.Request) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) filtersMap, err := util.PrepareFilters(r) if err != nil { utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String())) @@ -51,9 +49,7 @@ func ListSecrets(w http.ResponseWriter, r *http.Request) { } func InspectSecret(w http.ResponseWriter, r *http.Request) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) name := utils.GetName(r) names := []string{name} ic := abi.ContainerEngine{Libpod: runtime} @@ -84,9 +80,7 @@ func InspectSecret(w http.ResponseWriter, r *http.Request) { } func RemoveSecret(w http.ResponseWriter, r *http.Request) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) opts := entities.SecretRmOptions{} name := utils.GetName(r) @@ -104,9 +98,7 @@ func RemoveSecret(w http.ResponseWriter, r *http.Request) { } func CreateSecret(w http.ResponseWriter, r *http.Request) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) opts := entities.SecretCreateOptions{} createParams := struct { *entities.SecretCreateRequest diff --git a/pkg/api/handlers/compat/swagger.go b/pkg/api/handlers/compat/swagger.go deleted file mode 100644 index 86527da6e..000000000 --- a/pkg/api/handlers/compat/swagger.go +++ /dev/null @@ -1,67 +0,0 @@ -package compat - -import ( - "github.com/containers/podman/v4/pkg/domain/entities" - "github.com/docker/docker/api/types" -) - -// Create container -// swagger:response ContainerCreateResponse -type swagCtrCreateResponse struct { - // in:body - Body struct { - entities.ContainerCreateResponse - } -} - -// Wait container -// swagger:response ContainerWaitResponse -type swagCtrWaitResponse struct { - // in:body - Body struct { - // container exit code - StatusCode int - Error struct { - Message string - } - } -} - -// Network inspect -// swagger:response CompatNetworkInspect -type swagCompatNetworkInspect struct { - // in:body - Body types.NetworkResource -} - -// Network list -// swagger:response CompatNetworkList -type swagCompatNetworkList struct { - // in:body - Body []types.NetworkResource -} - -// Network create -// swagger:model NetworkCreateRequest -type NetworkCreateRequest struct { - types.NetworkCreateRequest -} - -// Network create -// swagger:response CompatNetworkCreate -type swagCompatNetworkCreateResponse struct { - // in:body - Body struct{ types.NetworkCreate } -} - -// Network disconnect -// swagger:model NetworkCompatConnectRequest -type swagCompatNetworkConnectRequest struct { - types.NetworkConnect -} - -// Network disconnect -// swagger:model NetworkCompatDisconnectRequest -type swagCompatNetworkDisconnectRequest struct { - types.NetworkDisconnect -} diff --git a/pkg/api/handlers/compat/version.go b/pkg/api/handlers/compat/version.go index b113fbc90..cfc3468c2 100644 --- a/pkg/api/handlers/compat/version.go +++ b/pkg/api/handlers/compat/version.go @@ -57,13 +57,15 @@ func VersionHandler(w http.ResponseWriter, r *http.Request) { Version: conmon.Version, Details: map[string]string{ "Package": conmon.Package, - }}, + }, + }, { Name: fmt.Sprintf("OCI Runtime (%s)", oci.Name), Version: oci.Version, Details: map[string]string{ "Package": oci.Package, - }}, + }, + }, } components = append(components, additional...) } @@ -89,5 +91,6 @@ func VersionHandler(w http.ResponseWriter, r *http.Request) { MinAPIVersion: fmt.Sprintf("%d.%d", minVersion.Major, minVersion.Minor), Os: components[0].Details["Os"], Version: components[0].Version, - }}) + }, + }) } diff --git a/pkg/api/handlers/compat/volumes.go b/pkg/api/handlers/compat/volumes.go index c8e4339b0..ff0a7af02 100644 --- a/pkg/api/handlers/compat/volumes.go +++ b/pkg/api/handlers/compat/volumes.go @@ -180,9 +180,7 @@ func CreateVolume(w http.ResponseWriter, r *http.Request) { } func InspectVolume(w http.ResponseWriter, r *http.Request) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) name := utils.GetName(r) vol, err := runtime.GetVolume(name) if err != nil { @@ -263,9 +261,7 @@ func RemoveVolume(w http.ResponseWriter, r *http.Request) { } func PruneVolumes(w http.ResponseWriter, r *http.Request) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) filterMap, err := util.PrepareFilters(r) if err != nil { utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "Decode()")) diff --git a/pkg/api/handlers/libpod/containers.go b/pkg/api/handlers/libpod/containers.go index 03dd436f6..6b5bee403 100644 --- a/pkg/api/handlers/libpod/containers.go +++ b/pkg/api/handlers/libpod/containers.go @@ -168,6 +168,7 @@ func UnmountContainer(w http.ResponseWriter, r *http.Request) { } utils.WriteResponse(w, http.StatusNoContent, "") } + func MountContainer(w http.ResponseWriter, r *http.Request) { runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) name := utils.GetName(r) diff --git a/pkg/api/handlers/libpod/generate.go b/pkg/api/handlers/libpod/generate.go index 28785b00d..b1ac6a65a 100644 --- a/pkg/api/handlers/libpod/generate.go +++ b/pkg/api/handlers/libpod/generate.go @@ -41,17 +41,17 @@ func GenerateSystemd(w http.ResponseWriter, r *http.Request) { return } - var ContainerPrefix = "container" + ContainerPrefix := "container" if query.ContainerPrefix != nil { ContainerPrefix = *query.ContainerPrefix } - var PodPrefix = "pod" + PodPrefix := "pod" if query.PodPrefix != nil { PodPrefix = *query.PodPrefix } - var Separator = "-" + Separator := "-" if query.Separator != nil { Separator = *query.Separator } @@ -106,5 +106,7 @@ func GenerateKube(w http.ResponseWriter, r *http.Request) { return } + // FIXME: Content-Type is being set as application/x-tar NOT text/vnd.yaml + // https://mailarchive.ietf.org/arch/msg/media-types/e9ZNC0hDXKXeFlAVRWxLCCaG9GI/ utils.WriteResponse(w, http.StatusOK, report.Reader) } diff --git a/pkg/api/handlers/libpod/images.go b/pkg/api/handlers/libpod/images.go index cddf4c205..efcbe9d77 100644 --- a/pkg/api/handlers/libpod/images.go +++ b/pkg/api/handlers/libpod/images.go @@ -102,9 +102,7 @@ func GetImage(w http.ResponseWriter, r *http.Request) { } func PruneImages(w http.ResponseWriter, r *http.Request) { - var ( - err error - ) + var err error runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) decoder := r.Context().Value(api.DecoderKey).(*schema.Decoder) query := struct { @@ -129,7 +127,7 @@ func PruneImages(w http.ResponseWriter, r *http.Request) { return } - var libpodFilters = []string{} + libpodFilters := []string{} if _, found := r.URL.Query()["filters"]; found { dangling := (*filterMap)["all"] if len(dangling) > 0 { @@ -162,9 +160,7 @@ func PruneImages(w http.ResponseWriter, r *http.Request) { } func ExportImage(w http.ResponseWriter, r *http.Request) { - var ( - output string - ) + var output string runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) decoder := r.Context().Value(api.DecoderKey).(*schema.Decoder) query := struct { @@ -243,9 +239,7 @@ func ExportImage(w http.ResponseWriter, r *http.Request) { } func ExportImages(w http.ResponseWriter, r *http.Request) { - var ( - output string - ) + var output string runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) decoder := r.Context().Value(api.DecoderKey).(*schema.Decoder) query := struct { @@ -566,7 +560,7 @@ func CommitContainer(w http.ResponseWriter, r *http.Request) { utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "CommitFailure")) return } - utils.WriteResponse(w, http.StatusOK, handlers.IDResponse{ID: commitImage.ID()}) // nolint + utils.WriteResponse(w, http.StatusOK, entities.IDResponse{ID: commitImage.ID()}) // nolint } func UntagImage(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/api/handlers/libpod/manifests.go b/pkg/api/handlers/libpod/manifests.go index 8dc7c57d5..65b9d6cb5 100644 --- a/pkg/api/handlers/libpod/manifests.go +++ b/pkg/api/handlers/libpod/manifests.go @@ -88,7 +88,7 @@ func ManifestCreate(w http.ResponseWriter, r *http.Request) { // Treat \r\n as empty body if len(buffer) < 3 { - utils.WriteResponse(w, status, handlers.IDResponse{ID: manID}) + utils.WriteResponse(w, status, entities.IDResponse{ID: manID}) return } @@ -113,7 +113,7 @@ func ManifestCreate(w http.ResponseWriter, r *http.Request) { return } - utils.WriteResponse(w, status, handlers.IDResponse{ID: id}) + utils.WriteResponse(w, status, entities.IDResponse{ID: id}) } // ManifestExists return true if manifest list exists. @@ -204,7 +204,7 @@ func ManifestAddV3(w http.ResponseWriter, r *http.Request) { utils.InternalServerError(w, err) return } - utils.WriteResponse(w, http.StatusOK, handlers.IDResponse{ID: newID}) + utils.WriteResponse(w, http.StatusOK, entities.IDResponse{ID: newID}) } // ManifestRemoveDigestV3 remove digest from manifest list @@ -238,7 +238,7 @@ func ManifestRemoveDigestV3(w http.ResponseWriter, r *http.Request) { utils.InternalServerError(w, err) return } - utils.WriteResponse(w, http.StatusOK, handlers.IDResponse{ID: manifestList.ID()}) + utils.WriteResponse(w, http.StatusOK, entities.IDResponse{ID: manifestList.ID()}) } // ManifestPushV3 push image to registry @@ -294,7 +294,7 @@ func ManifestPushV3(w http.ResponseWriter, r *http.Request) { utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "error pushing image %q", query.Destination)) return } - utils.WriteResponse(w, http.StatusOK, handlers.IDResponse{ID: digest}) + utils.WriteResponse(w, http.StatusOK, entities.IDResponse{ID: digest}) } // ManifestPush push image to registry @@ -353,7 +353,7 @@ func ManifestPush(w http.ResponseWriter, r *http.Request) { utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "error pushing image %q", destination)) return } - utils.WriteResponse(w, http.StatusOK, handlers.IDResponse{ID: digest}) + utils.WriteResponse(w, http.StatusOK, entities.IDResponse{ID: digest}) } // ManifestModify efficiently updates the named manifest list diff --git a/pkg/api/handlers/libpod/pods.go b/pkg/api/handlers/libpod/pods.go index d522631b7..5b92358fa 100644 --- a/pkg/api/handlers/libpod/pods.go +++ b/pkg/api/handlers/libpod/pods.go @@ -81,7 +81,7 @@ func PodCreate(w http.ResponseWriter, r *http.Request) { utils.Error(w, httpCode, errors.Wrap(err, "failed to make pod")) return } - utils.WriteResponse(w, http.StatusCreated, handlers.IDResponse{ID: pod.ID()}) + utils.WriteResponse(w, http.StatusCreated, entities.IDResponse{ID: pod.ID()}) } func Pods(w http.ResponseWriter, r *http.Request) { @@ -290,9 +290,7 @@ func PodPrune(w http.ResponseWriter, r *http.Request) { } func PodPruneHelper(r *http.Request) ([]*entities.PodPruneReport, error) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) responses, err := runtime.PrunePods(r.Context()) if err != nil { return nil, err @@ -414,7 +412,7 @@ loop: // break out of for/select infinite` loop } if len(output) > 0 { - var body = handlers.PodTopOKBody{} + body := handlers.PodTopOKBody{} body.Titles = strings.Split(output[0], "\t") for i := range body.Titles { body.Titles[i] = strings.TrimSpace(body.Titles[i]) diff --git a/pkg/api/handlers/libpod/swagger.go b/pkg/api/handlers/libpod/swagger.go deleted file mode 100644 index 5f33e6c01..000000000 --- a/pkg/api/handlers/libpod/swagger.go +++ /dev/null @@ -1,157 +0,0 @@ -package libpod - -import ( - "net/http" - "os" - - "github.com/containers/common/libnetwork/types" - "github.com/containers/image/v5/manifest" - "github.com/containers/podman/v4/libpod/define" - "github.com/containers/podman/v4/pkg/api/handlers/utils" - "github.com/containers/podman/v4/pkg/domain/entities" - "github.com/pkg/errors" -) - -// DefaultPodmanSwaggerSpec provides the default path to the podman swagger spec file -const DefaultPodmanSwaggerSpec = "/usr/share/containers/podman/swagger.yaml" - -// List Containers -// swagger:response ListContainers -type swagInspectPodResponse struct { - // in:body - Body []entities.ListContainer -} - -// Inspect Manifest -// swagger:response InspectManifest -type swagInspectManifestResponse struct { - // in:body - Body manifest.Schema2List -} - -// Kill Pod -// swagger:response PodKillReport -type swagKillPodResponse struct { - // in:body - Body entities.PodKillReport -} - -// Pause pod -// swagger:response PodPauseReport -type swagPausePodResponse struct { - // in:body - Body entities.PodPauseReport -} - -// Unpause pod -// swagger:response PodUnpauseReport -type swagUnpausePodResponse struct { - // in:body - Body entities.PodUnpauseReport -} - -// Stop pod -// swagger:response PodStopReport -type swagStopPodResponse struct { - // in:body - Body entities.PodStopReport -} - -// Restart pod -// swagger:response PodRestartReport -type swagRestartPodResponse struct { - // in:body - Body entities.PodRestartReport -} - -// Start pod -// swagger:response PodStartReport -type swagStartPodResponse struct { - // in:body - Body entities.PodStartReport -} - -// Prune pod -// swagger:response PodPruneReport -type swagPrunePodResponse struct { - // in:body - Body entities.PodPruneReport -} - -// Rm pod -// swagger:response PodRmReport -type swagRmPodResponse struct { - // in:body - Body entities.PodRmReport -} - -// Info -// swagger:response InfoResponse -type swagInfoResponse struct { - // in:body - Body define.Info -} - -// Network rm -// swagger:response NetworkRmReport -type swagNetworkRmReport struct { - // in:body - Body []entities.NetworkRmReport -} - -// Network inspect -// swagger:response NetworkInspectReport -type swagNetworkInspectReport struct { - // in:body - Body types.Network -} - -// Network list -// swagger:response NetworkListReport -type swagNetworkListReport struct { - // in:body - Body []types.Network -} - -// Network create -// swagger:model NetworkCreateLibpod -type swagNetworkCreateLibpod struct { - types.Network -} - -// Network create -// swagger:response NetworkCreateReport -type swagNetworkCreateReport struct { - // in:body - Body types.Network -} - -// Network prune -// swagger:response NetworkPruneResponse -type swagNetworkPruneResponse struct { - // in:body - Body []entities.NetworkPruneReport -} - -// Network connect -// swagger:model NetworkConnectRequest -type swagNetworkConnectRequest struct { - entities.NetworkConnectOptions -} - -func ServeSwagger(w http.ResponseWriter, r *http.Request) { - path := DefaultPodmanSwaggerSpec - if p, found := os.LookupEnv("PODMAN_SWAGGER_SPEC"); found { - path = p - } - if _, err := os.Stat(path); err != nil { - if os.IsNotExist(err) { - utils.InternalServerError(w, errors.Errorf("file %q does not exist", path)) - return - } - utils.InternalServerError(w, err) - return - } - w.Header().Set("Content-Type", "text/yaml") - http.ServeFile(w, r, path) -} diff --git a/pkg/api/handlers/libpod/swagger_spec.go b/pkg/api/handlers/libpod/swagger_spec.go new file mode 100644 index 000000000..8eeb041d2 --- /dev/null +++ b/pkg/api/handlers/libpod/swagger_spec.go @@ -0,0 +1,29 @@ +package libpod + +import ( + "net/http" + "os" + + "github.com/containers/podman/v4/pkg/api/handlers/utils" + "github.com/pkg/errors" +) + +// DefaultPodmanSwaggerSpec provides the default path to the podman swagger spec file +const DefaultPodmanSwaggerSpec = "/usr/share/containers/podman/swagger.yaml" + +func ServeSwagger(w http.ResponseWriter, r *http.Request) { + path := DefaultPodmanSwaggerSpec + if p, found := os.LookupEnv("PODMAN_SWAGGER_SPEC"); found { + path = p + } + if _, err := os.Stat(path); err != nil { + if errors.Is(err, os.ErrNotExist) { + utils.InternalServerError(w, errors.Errorf("swagger spec %q does not exist", path)) + return + } + utils.InternalServerError(w, err) + return + } + w.Header().Set("Content-Type", "text/yaml") + http.ServeFile(w, r, path) +} diff --git a/pkg/api/handlers/libpod/volumes.go b/pkg/api/handlers/libpod/volumes.go index e0ea16d82..e792dea35 100644 --- a/pkg/api/handlers/libpod/volumes.go +++ b/pkg/api/handlers/libpod/volumes.go @@ -25,8 +25,7 @@ func CreateVolume(w http.ResponseWriter, r *http.Request) { runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) decoder = r.Context().Value(api.DecoderKey).(*schema.Decoder) ) - query := struct { - }{ + query := struct{}{ // override any golang type defaults } if err := decoder.Decode(&query, r.URL.Query()); err != nil { @@ -86,9 +85,7 @@ func CreateVolume(w http.ResponseWriter, r *http.Request) { } func InspectVolume(w http.ResponseWriter, r *http.Request) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) name := utils.GetName(r) vol, err := runtime.GetVolume(name) if err != nil { @@ -107,9 +104,7 @@ func InspectVolume(w http.ResponseWriter, r *http.Request) { } func ListVolumes(w http.ResponseWriter, r *http.Request) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) filterMap, err := util.PrepareFilters(r) if err != nil { utils.Error(w, http.StatusInternalServerError, @@ -153,9 +148,7 @@ func PruneVolumes(w http.ResponseWriter, r *http.Request) { } func pruneVolumesHelper(r *http.Request) ([]*reports.PruneReport, error) { - var ( - runtime = r.Context().Value(api.RuntimeKey).(*libpod.Runtime) - ) + runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime) filterMap, err := util.PrepareFilters(r) if err != nil { return nil, err diff --git a/pkg/api/handlers/swagger/doc.go b/pkg/api/handlers/swagger/doc.go new file mode 100644 index 000000000..67ede275a --- /dev/null +++ b/pkg/api/handlers/swagger/doc.go @@ -0,0 +1,17 @@ +// Package swagger defines the payloads used by the Podman API +// +// - errors.go: declares the errors used in the API. By embedding errors.ErrorModel, more meaningful +// comments can be provided for the developer documentation. +// - models.go: declares the models used in API requests. +// - responses.go: declares the responses used in the API responses. +// +// +// Notes: +// 1. As a developer of the Podman API, you are responsible for maintaining the associations between +// these models and responses, and the handler code. +// 2. There are a number of warnings produces when compiling the swagger yaml file. This is expected. +// Most are because embedded structs have been discovered but not used in the API declarations. +// 3. Response and model references that are exported (start with upper-case letter) imply that they +// exist outside this package and should be found in the entities package. +// +package swagger diff --git a/pkg/api/handlers/swagger/errors.go b/pkg/api/handlers/swagger/errors.go new file mode 100644 index 000000000..28e11c9fb --- /dev/null +++ b/pkg/api/handlers/swagger/errors.go @@ -0,0 +1,116 @@ +//nolint:deadcode,unused // these types are used to wire generated swagger to API code +package swagger + +import ( + "github.com/containers/podman/v4/pkg/errorhandling" +) + +// Error model embedded in swagger:response to aid in documentation generation + +// No such image +// swagger:response +type imageNotFound struct { + // in:body + Body errorhandling.ErrorModel +} + +// No such container +// swagger:response +type containerNotFound struct { + // in:body + Body errorhandling.ErrorModel +} + +// No such network +// swagger:response +type networkNotFound struct { + // in:body + Body errorhandling.ErrorModel +} + +// No such exec instance +// swagger:response +type execSessionNotFound struct { + // in:body + Body errorhandling.ErrorModel +} + +// No such volume +// swagger:response +type volumeNotFound struct { + // in:body + Body errorhandling.ErrorModel +} + +// No such pod +// swagger:response +type podNotFound struct { + // in:body + Body errorhandling.ErrorModel +} + +// No such manifest +// swagger:response +type manifestNotFound struct { + // in:body + Body errorhandling.ErrorModel +} + +// Internal server error +// swagger:response +type internalError struct { + // in:body + Body errorhandling.ErrorModel +} + +// Conflict error in operation +// swagger:response +type conflictError struct { + // in:body + Body errorhandling.ErrorModel +} + +// Bad parameter in request +// swagger:response +type badParamError struct { + // in:body + Body errorhandling.ErrorModel +} + +// Container already started +// swagger:response +type containerAlreadyStartedError struct { + // in:body + Body errorhandling.ErrorModel +} + +// Container already stopped +// swagger:response +type containerAlreadyStoppedError struct { + // in:body + Body errorhandling.ErrorModel +} + +// Pod already started +// swagger:response +type podAlreadyStartedError struct { + // in:body + Body errorhandling.ErrorModel +} + +// Pod already stopped +// swagger:response +type podAlreadyStoppedError struct { + // in:body + Body errorhandling.ErrorModel +} + +// Success +// swagger:response +type ok struct { + // in:body + Body struct { + // example: OK + ok string + } +} diff --git a/pkg/api/handlers/swagger/models.go b/pkg/api/handlers/swagger/models.go new file mode 100644 index 000000000..a05e57dff --- /dev/null +++ b/pkg/api/handlers/swagger/models.go @@ -0,0 +1,46 @@ +//nolint:deadcode,unused // these types are used to wire generated swagger to API code +package swagger + +import ( + "github.com/containers/podman/v4/pkg/domain/entities" + "github.com/docker/docker/api/types" +) + +// Details for creating a volume +// swagger:model +type volumeCreate struct { + // Name of the volume driver to use. + // Required: true + Driver string `json:"Driver"` + + // A mapping of driver options and values. These options are + // passed directly to the driver and are driver specific. + // + // Required: true + DriverOpts map[string]string `json:"DriverOpts"` + + // User-defined key/value metadata. + // Required: true + Labels map[string]string `json:"Labels"` + + // The new volume's name. If not specified, Docker generates a name. + // + // Required: true + Name string `json:"Name"` +} + +// Network create +// swagger:model +type networkCreate types.NetworkCreateRequest + +// Network connect +// swagger:model +type networkConnectRequest types.NetworkConnect + +// Network disconnect +// swagger:model +type networkDisconnectRequest types.NetworkDisconnect + +// Network connect +// swagger:model +type networkConnectRequestLibpod entities.NetworkConnectOptions diff --git a/pkg/api/handlers/swagger/responses.go b/pkg/api/handlers/swagger/responses.go new file mode 100644 index 000000000..55fc1a77f --- /dev/null +++ b/pkg/api/handlers/swagger/responses.go @@ -0,0 +1,453 @@ +//nolint:deadcode,unused // these types are used to wire generated swagger to API code +package swagger + +import ( + "github.com/containers/common/libnetwork/types" + "github.com/containers/image/v5/manifest" + "github.com/containers/podman/v4/libpod/define" + "github.com/containers/podman/v4/pkg/api/handlers" + "github.com/containers/podman/v4/pkg/domain/entities" + "github.com/containers/podman/v4/pkg/domain/entities/reports" + "github.com/containers/podman/v4/pkg/inspect" + dockerAPI "github.com/docker/docker/api/types" + dockerVolume "github.com/docker/docker/api/types/volume" +) + +// Image Tree +// swagger:response +type treeResponse struct { + // in:body + Body entities.ImageTreeReport +} + +// Image History +// swagger:response +type history struct { + // in:body + Body handlers.HistoryResponse +} + +// Image Inspect +// swagger:response +type imageInspect struct { + // in:body + Body handlers.ImageInspect +} + +// Image Load +// swagger:response +type imagesLoadResponseLibpod struct { + // in:body + Body entities.ImageLoadReport +} + +// Image Import +// swagger:response +type imagesImportResponseLibpod struct { + // in:body + Body entities.ImageImportReport +} + +// Image Pull +// swagger:response +type imagesPullResponseLibpod struct { + // in:body + Body handlers.LibpodImagesPullReport +} + +// Image Remove +// swagger:response +type imagesRemoveResponseLibpod struct { + // in:body + Body handlers.LibpodImagesRemoveReport +} + +// PlayKube response +// swagger:response +type playKubeResponseLibpod struct { + // in:body + Body entities.PlayKubeReport +} + +// Image Delete +// swagger:response +type imageDeleteResponse struct { + // in:body + Body []struct { + Untagged []string `json:"untagged"` + Deleted string `json:"deleted"` + } +} + +// Registry Search +// swagger:response +type registrySearchResponse struct { + // in:body + Body struct { + // Index is the image index + // example: quay.io + Index string + // Name is the canonical name of the image + // example: docker.io/library/alpine" + Name string + // Description of the image. + Description string + // Stars is the number of stars of the image. + Stars int + // Official indicates if it's an official image. + Official string + // Automated indicates if the image was created by an automated build. + Automated string + // Tag is the image tag + Tag string + } +} + +// Inspect Image +// swagger:response +type inspectImageResponseLibpod struct { + // in:body + Body inspect.ImageData +} + +// Inspect container +// swagger:response +type containerInspectResponse struct { + // in:body + Body dockerAPI.ContainerJSON +} + +// List processes in container +// swagger:response +type containerTopResponse struct { + // in:body + Body handlers.ContainerTopOKBody +} + +// List processes in pod +// swagger:response +type podTopResponse struct { + // in:body + Body handlers.PodTopOKBody +} + +// Pod Statistics +// swagger:response +type podStatsResponse struct { + // in:body + Body []entities.PodStatsReport +} + +// Inspect container +// swagger:response +type containerInspectResponseLibpod struct { + // in:body + Body define.InspectContainerData +} + +// List pods +// swagger:response +type podsListResponse struct { + // in:body + Body []entities.ListPodsReport +} + +// Inspect pod +// swagger:response +type podInspectResponse struct { + // in:body + Body define.InspectPodData +} + +// Volume details +// swagger:response +type volumeCreateResponse struct { + // in:body + Body entities.VolumeConfigResponse +} + +// Healthcheck Results +// swagger:response +type healthCheck struct { + // in:body + Body define.HealthCheckResults +} + +// Version +// swagger:response +type versionResponse struct { + // in:body + Body entities.ComponentVersion +} + +// Disk usage +// swagger:response +type systemDiskUsage struct { + // in:body + Body entities.SystemDfReport +} + +// System Prune results +// swagger:response +type systemPruneResponse struct { + // in:body + Body entities.SystemPruneReport +} + +// Auth response +// swagger:response +type systemAuthResponse struct { + // in:body + Body entities.AuthReport +} + +// Exec Session Inspect +// swagger:response +type execSessionInspect struct { + // in:body + Body define.InspectExecSession +} + +// Image summary for compat API +// swagger:response +type imageList struct { + // in:body + Body []dockerAPI.ImageSummary +} + +// Image summary for libpod API +// swagger:response +type imageListLibpod struct { + // in:body + Body []entities.ImageSummary +} + +// List Containers +// swagger:response +type containersList struct { + // in:body + Body []handlers.Container +} + +// This response definition is used for both the create and inspect endpoints +// swagger:response +type volumeInspect struct { + // in:body + Body dockerAPI.Volume +} + +// Volume prune +// swagger:response +type volumePruneResponse struct { + // in:body + Body dockerAPI.VolumesPruneReport +} + +// Volume List +// swagger:response +type volumeList struct { + // in:body + Body dockerVolume.VolumeListOKBody +} + +// Volume list +// swagger:response +type volumeListLibpod struct { + // in:body + Body []entities.VolumeConfigResponse +} + +// Image Prune +// swagger:response +type imagesPruneLibpod struct { + // in:body + Body []reports.PruneReport +} + +// Remove Containers +// swagger:response +type containerRemoveLibpod struct { + // in: body + Body []handlers.LibpodContainersRmReport +} + +// Prune Containers +// swagger:response +type containersPrune struct { + // in: body + Body []handlers.ContainersPruneReport +} + +// Prune Containers +// swagger:response +type containersPruneLibpod struct { + // in: body + Body []handlers.ContainersPruneReportLibpod +} + +// Get stats for one or more containers +// swagger:response +type containerStats struct { + // in:body + Body define.ContainerStats +} + +// Volume Prune +// swagger:response +type volumePruneLibpod struct { + // in:body + Body []reports.PruneReport +} + +// Create container +// swagger:response +type containerCreateResponse struct { + // in:body + Body entities.ContainerCreateResponse +} + +// Wait container +// swagger:response +type containerWaitResponse struct { + // in:body + Body struct { + // container exit code + StatusCode int + Error struct { + Message string + } + } +} + +// Network inspect +// swagger:response +type networkInspectCompat struct { + // in:body + Body dockerAPI.NetworkResource +} + +// Network list +// swagger:response +type networkListCompat struct { + // in:body + Body []dockerAPI.NetworkResource +} + +// List Containers +// swagger:response +type containersListLibpod struct { + // in:body + Body []entities.ListContainer +} + +// Inspect Manifest +// swagger:response +type manifestInspect struct { + // in:body + Body manifest.Schema2List +} + +// Kill Pod +// swagger:response +type podKillResponse struct { + // in:body + Body entities.PodKillReport +} + +// Pause pod +// swagger:response +type podPauseResponse struct { + // in:body + Body entities.PodPauseReport +} + +// Unpause pod +// swagger:response +type podUnpauseResponse struct { + // in:body + Body entities.PodUnpauseReport +} + +// Stop pod +// swagger:response +type podStopResponse struct { + // in:body + Body entities.PodStopReport +} + +// Restart pod +// swagger:response +type podRestartResponse struct { + // in:body + Body entities.PodRestartReport +} + +// Start pod +// swagger:response +type podStartResponse struct { + // in:body + Body entities.PodStartReport +} + +// Prune pod +// swagger:response +type podPruneResponse struct { + // in:body + Body entities.PodPruneReport +} + +// Rm pod +// swagger:response +type podRmResponse struct { + // in:body + Body entities.PodRmReport +} + +// Info +// swagger:response +type infoResponse struct { + // in:body + Body define.Info +} + +// Network Delete +// swagger:response +type networkRmResponse struct { + // in:body + Body []entities.NetworkRmReport +} + +// Network inspect +// swagger:response +type networkInspectResponse struct { + // in:body + Body types.Network +} + +// Network list +// swagger:response +type networkListLibpod struct { + // in:body + Body []types.Network +} + +// Network create +// swagger:model +type networkCreateLibpod struct { + // in:body + types.Network +} + +// Network create +// swagger:response +type networkCreateResponse struct { + // in:body + Body types.Network +} + +// Network prune +// swagger:response +type networkPruneResponse struct { + // in:body + Body []entities.NetworkPruneReport +} diff --git a/pkg/api/handlers/swagger/swagger.go b/pkg/api/handlers/swagger/swagger.go deleted file mode 100644 index 7446d901e..000000000 --- a/pkg/api/handlers/swagger/swagger.go +++ /dev/null @@ -1,194 +0,0 @@ -package swagger - -import ( - "github.com/containers/podman/v4/libpod/define" - "github.com/containers/podman/v4/pkg/api/handlers" - "github.com/containers/podman/v4/pkg/domain/entities" - "github.com/containers/podman/v4/pkg/inspect" - "github.com/docker/docker/api/types" -) - -// Tree response -// swagger:response TreeResponse -type swagTree struct { - // in:body - Body struct { - entities.ImageTreeReport - } -} - -// History response -// swagger:response DocsHistory -type swagHistory struct { - // in:body - Body struct { - handlers.HistoryResponse - } -} - -// Inspect response -// swagger:response DocsImageInspect -type swagImageInspect struct { - // in:body - Body struct { - handlers.ImageInspect - } -} - -// Load response -// swagger:response DocsLibpodImagesLoadResponse -type swagLibpodImagesLoadResponse struct { - // in:body - Body entities.ImageLoadReport -} - -// Import response -// swagger:response DocsLibpodImagesImportResponse -type swagLibpodImagesImportResponse struct { - // in:body - Body entities.ImageImportReport -} - -// Pull response -// swagger:response DocsLibpodImagesPullResponse -type swagLibpodImagesPullResponse struct { - // in:body - Body handlers.LibpodImagesPullReport -} - -// Remove response -// swagger:response DocsLibpodImagesRemoveResponse -type swagLibpodImagesRemoveResponse struct { - // in:body - Body handlers.LibpodImagesRemoveReport -} - -// PlayKube response -// swagger:response DocsLibpodPlayKubeResponse -type swagLibpodPlayKubeResponse struct { - // in:body - Body entities.PlayKubeReport -} - -// Delete response -// swagger:response DocsImageDeleteResponse -type swagImageDeleteResponse struct { - // in:body - Body []struct { - Untagged []string `json:"untagged"` - Deleted string `json:"deleted"` - } -} - -// Search results -// swagger:response DocsSearchResponse -type swagSearchResponse struct { - // in:body - Body struct { - // Index is the image index (e.g., "docker.io" or "quay.io") - Index string - // Name is the canonical name of the image (e.g., "docker.io/library/alpine"). - Name string - // Description of the image. - Description string - // Stars is the number of stars of the image. - Stars int - // Official indicates if it's an official image. - Official string - // Automated indicates if the image was created by an automated build. - Automated string - // Tag is the image tag - Tag string - } -} - -// Inspect image -// swagger:response DocsLibpodInspectImageResponse -type swagLibpodInspectImageResponse struct { - // in:body - Body struct { - inspect.ImageData - } -} - -// Rm containers -// swagger:response DocsLibpodContainerRmReport -type swagLibpodContainerRmReport struct { - // in: body - Body []handlers.LibpodContainersRmReport -} - -// Prune containers -// swagger:response DocsContainerPruneReport -type swagContainerPruneReport struct { - // in: body - Body []handlers.ContainersPruneReport -} - -// Prune containers -// swagger:response DocsLibpodPruneResponse -type swagLibpodContainerPruneReport struct { - // in: body - Body []handlers.LibpodContainersPruneReport -} - -// Inspect container -// swagger:response DocsContainerInspectResponse -type swagContainerInspectResponse struct { - // in:body - Body struct { - types.ContainerJSON - } -} - -// List processes in container -// swagger:response DocsContainerTopResponse -type swagContainerTopResponse struct { - // in:body - Body struct { - handlers.ContainerTopOKBody - } -} - -// List processes in pod -// swagger:response DocsPodTopResponse -type swagPodTopResponse struct { - // in:body - Body struct { - handlers.PodTopOKBody - } -} - -// Inspect container -// swagger:response LibpodInspectContainerResponse -type swagLibpodInspectContainerResponse struct { - // in:body - Body struct { - define.InspectContainerData - } -} - -// List pods -// swagger:response ListPodsResponse -type swagListPodsResponse struct { - // in:body - Body []entities.ListPodsReport -} - -// Inspect pod -// swagger:response InspectPodResponse -type swagInspectPodResponse struct { - // in:body - Body struct { - define.InspectPodData - } -} - -// Get stats for one or more containers -// swagger:response ContainerStats -type swagContainerStatsResponse struct { - // in:body - Body struct { - define.ContainerStats - } -} diff --git a/pkg/api/handlers/types.go b/pkg/api/handlers/types.go index 07eebb4f4..9eb712c30 100644 --- a/pkg/api/handlers/types.go +++ b/pkg/api/handlers/types.go @@ -41,7 +41,7 @@ type ContainersPruneReport struct { docker.ContainersPruneReport } -type LibpodContainersPruneReport struct { +type ContainersPruneReportLibpod struct { ID string `json:"Id"` SpaceReclaimed int64 `json:"Size"` // Error which occurred during prune operation (if any). @@ -121,7 +121,7 @@ type ContainerWaitOKBody struct { } // CreateContainerConfig used when compatible endpoint creates a container -// swagger:model CreateContainerConfig +// swagger:model type CreateContainerConfig struct { Name string // container name dockerContainer.Config // desired container configuration @@ -131,12 +131,6 @@ type CreateContainerConfig struct { UnsetEnvAll bool // unset all default environment variables } -// swagger:model IDResponse -type IDResponse struct { - // ID - ID string `json:"Id"` -} - type ContainerTopOKBody struct { dockerContainer.ContainerTopOKBody } @@ -145,20 +139,6 @@ type PodTopOKBody struct { dockerContainer.ContainerTopOKBody } -// swagger:model PodCreateConfig -type PodCreateConfig struct { - Name string `json:"name"` - CgroupParent string `json:"cgroup-parent"` - Hostname string `json:"hostname"` - Infra bool `json:"infra"` - InfraCommand string `json:"infra-command"` - InfraImage string `json:"infra-image"` - InfraName string `json:"infra-name"` - Labels []string `json:"labels"` - Publish []string `json:"publish"` - Share string `json:"share"` -} - // HistoryResponse provides details on image layers type HistoryResponse struct { ID string `json:"Id"` @@ -173,10 +153,6 @@ type ExecCreateConfig struct { docker.ExecConfig } -type ExecCreateResponse struct { - docker.IDResponse -} - type ExecStartConfig struct { Detach bool `json:"Detach"` Tty bool `json:"Tty"` @@ -250,7 +226,7 @@ func ImageDataToImageInspect(ctx context.Context, l *libimage.Image) (*ImageInsp return &ImageInspect{dockerImageInspect}, nil } -// portsToPortSet converts libpods exposed ports to dockers structs +// portsToPortSet converts libpod's exposed ports to docker's structs func portsToPortSet(input map[string]struct{}) (nat.PortSet, error) { ports := make(nat.PortSet) for k := range input { diff --git a/pkg/api/handlers/utils/containers.go b/pkg/api/handlers/utils/containers.go index 3a5488a4a..8588b49ba 100644 --- a/pkg/api/handlers/utils/containers.go +++ b/pkg/api/handlers/utils/containers.go @@ -57,7 +57,6 @@ func WaitContainerDocker(w http.ResponseWriter, r *http.Request) { name := GetName(r) exists, err := containerExists(ctx, name) - if err != nil { InternalServerError(w, err) return |