diff options
Diffstat (limited to 'pkg/api')
23 files changed, 762 insertions, 61 deletions
diff --git a/pkg/api/handlers/compat/containers_archive.go b/pkg/api/handlers/compat/containers_archive.go new file mode 100644 index 000000000..c3a26873e --- /dev/null +++ b/pkg/api/handlers/compat/containers_archive.go @@ -0,0 +1,12 @@ +package compat + +import ( + "errors" + "net/http" + + "github.com/containers/libpod/pkg/api/handlers/utils" +) + +func Archive(w http.ResponseWriter, r *http.Request) { + utils.Error(w, "not implemented", http.StatusNotImplemented, errors.New("not implemented")) +} diff --git a/pkg/api/handlers/compat/containers_attach.go b/pkg/api/handlers/compat/containers_attach.go index 012e20daf..990140ee1 100644 --- a/pkg/api/handlers/compat/containers_attach.go +++ b/pkg/api/handlers/compat/containers_attach.go @@ -90,7 +90,7 @@ func AttachContainer(w http.ResponseWriter, r *http.Request) { // For Docker compatibility, we need to re-initialize containers in these states. if state == define.ContainerStateConfigured || state == define.ContainerStateExited { if err := ctr.Init(r.Context()); err != nil { - utils.InternalServerError(w, errors.Wrapf(err, "error preparing container %s for attach", ctr.ID())) + utils.Error(w, "Container in wrong state", http.StatusConflict, errors.Wrapf(err, "error preparing container %s for attach", ctr.ID())) return } } else if !(state == define.ContainerStateCreated || state == define.ContainerStateRunning) { diff --git a/pkg/api/handlers/compat/containers_stats.go b/pkg/api/handlers/compat/containers_stats.go index 62ccd2b93..048321add 100644 --- a/pkg/api/handlers/compat/containers_stats.go +++ b/pkg/api/handlers/compat/containers_stats.go @@ -45,8 +45,8 @@ func StatsContainer(w http.ResponseWriter, r *http.Request) { utils.InternalServerError(w, err) return } - if state != define.ContainerStateRunning && !query.Stream { - utils.InternalServerError(w, define.ErrCtrStateInvalid) + if state != define.ContainerStateRunning { + utils.Error(w, "Container not running and streaming requested", http.StatusConflict, define.ErrCtrStateInvalid) return } diff --git a/pkg/api/handlers/compat/events.go b/pkg/api/handlers/compat/events.go index 7ebfb0d1e..577ddd0a1 100644 --- a/pkg/api/handlers/compat/events.go +++ b/pkg/api/handlers/compat/events.go @@ -26,7 +26,10 @@ func GetEvents(w http.ResponseWriter, r *http.Request) { Since string `schema:"since"` Until string `schema:"until"` Filters map[string][]string `schema:"filters"` - }{} + Stream bool `schema:"stream"` + }{ + Stream: true, + } if err := decoder.Decode(&query, r.URL.Query()); err != nil { utils.Error(w, "Failed to parse parameters", http.StatusBadRequest, errors.Wrapf(err, "Failed to parse parameters for %s", r.URL.String())) } @@ -41,9 +44,10 @@ func GetEvents(w http.ResponseWriter, r *http.Request) { if len(query.Since) > 0 || len(query.Until) > 0 { fromStart = true } + eventChannel := make(chan *events.Event) go func() { - readOpts := events.ReadOptions{FromStart: fromStart, Stream: true, Filters: libpodFilters, EventChannel: eventChannel, Since: query.Since, Until: query.Until} + readOpts := events.ReadOptions{FromStart: fromStart, Stream: query.Stream, Filters: libpodFilters, EventChannel: eventChannel, Since: query.Since, Until: query.Until} eventsError = runtime.Events(readOpts) }() if eventsError != nil { @@ -55,7 +59,9 @@ func GetEvents(w http.ResponseWriter, r *http.Request) { // If client disappears we need to stop listening for events go func(done <-chan struct{}) { <-done - close(eventChannel) + if _, ok := <-eventChannel; ok { + close(eventChannel) + } }(r.Context().Done()) // Headers need to be written out before turning Writer() over to json encoder diff --git a/pkg/api/handlers/compat/images.go b/pkg/api/handlers/compat/images.go index ea9cbd691..b64ed0036 100644 --- a/pkg/api/handlers/compat/images.go +++ b/pkg/api/handlers/compat/images.go @@ -15,6 +15,7 @@ import ( image2 "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/pkg/api/handlers" "github.com/containers/libpod/pkg/api/handlers/utils" + "github.com/containers/libpod/pkg/auth" "github.com/containers/libpod/pkg/domain/entities" "github.com/containers/libpod/pkg/util" "github.com/docker/docker/api/types" @@ -251,19 +252,32 @@ func CreateImageFromImage(w http.ResponseWriter, r *http.Request) { return } - /* - fromImage – Name of the image to pull. The name may include a tag or digest. This parameter may only be used when pulling an image. The pull is cancelled if the HTTP connection is closed. - repo – Repository name given to an image when it is imported. The repo may include a tag. This parameter may only be used when importing an image. - tag – Tag or digest. If empty when pulling an image, this causes all tags for the given image to be pulled. - */ fromImage := query.FromImage if len(query.Tag) >= 1 { fromImage = fmt.Sprintf("%s:%s", fromImage, query.Tag) } - // TODO - // We are eating the output right now because we haven't talked about how to deal with multiple responses yet - img, err := runtime.ImageRuntime().New(r.Context(), fromImage, "", "", nil, &image2.DockerRegistryOptions{}, image2.SigningOptions{}, nil, util.PullImageMissing) + authConf, authfile, err := auth.GetCredentials(r) + if err != nil { + utils.Error(w, "Something went wrong.", http.StatusBadRequest, errors.Wrapf(err, "Failed to parse %q header for %s", auth.XRegistryAuthHeader, r.URL.String())) + return + } + defer auth.RemoveAuthfile(authfile) + + registryOpts := image2.DockerRegistryOptions{DockerRegistryCreds: authConf} + if sys := runtime.SystemContext(); sys != nil { + registryOpts.DockerCertPath = sys.DockerCertPath + } + img, err := runtime.ImageRuntime().New(r.Context(), + fromImage, + "", // signature policy + authfile, + nil, // writer + ®istryOpts, + image2.SigningOptions{}, + nil, // label + util.PullImageMissing, + ) if err != nil { utils.Error(w, "Something went wrong.", http.StatusInternalServerError, err) return diff --git a/pkg/api/handlers/compat/images_push.go b/pkg/api/handlers/compat/images_push.go index 2260d5557..47976b7c9 100644 --- a/pkg/api/handlers/compat/images_push.go +++ b/pkg/api/handlers/compat/images_push.go @@ -9,6 +9,7 @@ import ( "github.com/containers/libpod/libpod" "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/pkg/api/handlers/utils" + "github.com/containers/libpod/pkg/auth" "github.com/gorilla/schema" "github.com/pkg/errors" ) @@ -48,13 +49,17 @@ func PushImage(w http.ResponseWriter, r *http.Request) { return } - // TODO: the X-Registry-Auth header is not checked yet here nor in any other - // endpoint. Pushing does NOT work with authentication at the moment. - dockerRegistryOptions := &image.DockerRegistryOptions{} - authfile := "" + authConf, authfile, err := auth.GetCredentials(r) + if err != nil { + utils.Error(w, "Something went wrong.", http.StatusBadRequest, errors.Wrapf(err, "Failed to parse %q header for %s", auth.XRegistryAuthHeader, r.URL.String())) + return + } + defer auth.RemoveAuthfile(authfile) + + dockerRegistryOptions := &image.DockerRegistryOptions{DockerRegistryCreds: authConf} if sys := runtime.SystemContext(); sys != nil { dockerRegistryOptions.DockerCertPath = sys.DockerCertPath - authfile = sys.AuthFilePath + dockerRegistryOptions.RegistriesConfPath = sys.SystemRegistriesConfPath } err = newImage.PushImageToHeuristicDestination( diff --git a/pkg/api/handlers/compat/networks.go b/pkg/api/handlers/compat/networks.go new file mode 100644 index 000000000..c52ca093f --- /dev/null +++ b/pkg/api/handlers/compat/networks.go @@ -0,0 +1,301 @@ +package compat + +import ( + "encoding/json" + "net" + "net/http" + "os" + "syscall" + "time" + + "github.com/containernetworking/cni/libcni" + "github.com/containers/libpod/libpod" + "github.com/containers/libpod/pkg/api/handlers/utils" + "github.com/containers/libpod/pkg/domain/entities" + "github.com/containers/libpod/pkg/domain/infra/abi" + "github.com/containers/libpod/pkg/network" + "github.com/docker/docker/api/types" + dockerNetwork "github.com/docker/docker/api/types/network" + "github.com/gorilla/schema" + "github.com/pkg/errors" +) + +type CompatInspectNetwork struct { + types.NetworkResource +} + +func InspectNetwork(w http.ResponseWriter, r *http.Request) { + runtime := r.Context().Value("runtime").(*libpod.Runtime) + + // FYI scope and version are currently unused but are described by the API + // Leaving this for if/when we have to enable these + //query := struct { + // scope string + // verbose bool + //}{ + // // override any golang type defaults + //} + //decoder := r.Context().Value("decoder").(*schema.Decoder) + //if err := decoder.Decode(&query, r.URL.Query()); err != nil { + // utils.Error(w, "Something went wrong.", http.StatusBadRequest, errors.Wrapf(err, "Failed to parse parameters for %s", r.URL.String())) + // return + //} + config, err := runtime.GetConfig() + if err != nil { + utils.InternalServerError(w, err) + return + } + name := utils.GetName(r) + _, err = network.InspectNetwork(config, name) + if err != nil { + // TODO our network package does not distinguish between not finding a + // specific network vs not being able to read it + utils.InternalServerError(w, err) + return + } + report, err := getNetworkResourceByName(name, runtime) + if err != nil { + utils.InternalServerError(w, err) + return + } + utils.WriteResponse(w, http.StatusOK, report) +} + +func getNetworkResourceByName(name string, runtime *libpod.Runtime) (*types.NetworkResource, error) { + var ( + ipamConfigs []dockerNetwork.IPAMConfig + ) + config, err := runtime.GetConfig() + if err != nil { + return nil, err + } + containerEndpoints := map[string]types.EndpointResource{} + // Get the network path so we can get created time + networkConfigPath, err := network.GetCNIConfigPathByName(config, name) + if err != nil { + return nil, err + } + f, err := os.Stat(networkConfigPath) + if err != nil { + return nil, err + } + stat := f.Sys().(*syscall.Stat_t) + cons, err := runtime.GetAllContainers() + if err != nil { + return nil, err + } + conf, err := libcni.ConfListFromFile(networkConfigPath) + if err != nil { + return nil, err + } + + // No Bridge plugin means we bail + bridge, err := genericPluginsToBridge(conf.Plugins, network.DefaultNetworkDriver) + if err != nil { + return nil, err + } + for _, outer := range bridge.IPAM.Ranges { + for _, n := range outer { + ipamConfig := dockerNetwork.IPAMConfig{ + Subnet: n.Subnet, + Gateway: n.Gateway, + } + ipamConfigs = append(ipamConfigs, ipamConfig) + } + } + + for _, con := range cons { + data, err := con.Inspect(false) + if err != nil { + return nil, err + } + if netData, ok := data.NetworkSettings.Networks[name]; ok { + containerEndpoint := types.EndpointResource{ + Name: netData.NetworkID, + EndpointID: netData.EndpointID, + MacAddress: netData.MacAddress, + IPv4Address: netData.IPAddress, + IPv6Address: netData.GlobalIPv6Address, + } + containerEndpoints[con.ID()] = containerEndpoint + } + } + report := types.NetworkResource{ + Name: name, + ID: "", + Created: time.Unix(int64(stat.Ctim.Sec), int64(stat.Ctim.Nsec)), // nolint: unconvert + Scope: "", + Driver: network.DefaultNetworkDriver, + EnableIPv6: false, + IPAM: dockerNetwork.IPAM{ + Driver: "default", + Options: nil, + Config: ipamConfigs, + }, + Internal: false, + Attachable: false, + Ingress: false, + ConfigFrom: dockerNetwork.ConfigReference{}, + ConfigOnly: false, + Containers: containerEndpoints, + Options: nil, + Labels: nil, + Peers: nil, + Services: nil, + } + return &report, nil +} + +func genericPluginsToBridge(plugins []*libcni.NetworkConfig, pluginType string) (network.HostLocalBridge, error) { + var bridge network.HostLocalBridge + generic, err := findPluginByName(plugins, pluginType) + if err != nil { + return bridge, err + } + err = json.Unmarshal(generic, &bridge) + return bridge, err +} + +func findPluginByName(plugins []*libcni.NetworkConfig, pluginType string) ([]byte, error) { + for _, p := range plugins { + if pluginType == p.Network.Type { + return p.Bytes, nil + } + } + return nil, errors.New("unable to find bridge plugin") +} + +func ListNetworks(w http.ResponseWriter, r *http.Request) { + var ( + reports []*types.NetworkResource + ) + runtime := r.Context().Value("runtime").(*libpod.Runtime) + decoder := r.Context().Value("decoder").(*schema.Decoder) + query := struct { + Filters map[string][]string `schema:"filters"` + }{ + // override any golang type defaults + } + if err := decoder.Decode(&query, r.URL.Query()); err != nil { + utils.Error(w, "Something went wrong.", http.StatusBadRequest, errors.Wrapf(err, "Failed to parse parameters for %s", r.URL.String())) + return + } + config, err := runtime.GetConfig() + if err != nil { + utils.InternalServerError(w, err) + return + } + // TODO remove when filters are implemented + if len(query.Filters) > 0 { + utils.InternalServerError(w, errors.New("filters for listing networks is not implemented")) + return + } + netNames, err := network.GetNetworkNamesFromFileSystem(config) + if err != nil { + utils.InternalServerError(w, err) + return + } + for _, name := range netNames { + report, err := getNetworkResourceByName(name, runtime) + if err != nil { + utils.InternalServerError(w, err) + } + reports = append(reports, report) + } + utils.WriteResponse(w, http.StatusOK, reports) +} + +func CreateNetwork(w http.ResponseWriter, r *http.Request) { + var ( + name string + networkCreate types.NetworkCreateRequest + ) + runtime := r.Context().Value("runtime").(*libpod.Runtime) + if err := json.NewDecoder(r.Body).Decode(&networkCreate); err != nil { + utils.Error(w, "Something went wrong.", http.StatusInternalServerError, errors.Wrap(err, "Decode()")) + return + } + + if len(networkCreate.Name) > 0 { + name = networkCreate.Name + } + // At present I think we should just suport the bridge driver + // and allow demand to make us consider more + if networkCreate.Driver != network.DefaultNetworkDriver { + utils.InternalServerError(w, errors.New("network create only supports the bridge driver")) + return + } + ncOptions := entities.NetworkCreateOptions{ + Driver: network.DefaultNetworkDriver, + Internal: networkCreate.Internal, + } + if networkCreate.IPAM != nil && networkCreate.IPAM.Config != nil { + if len(networkCreate.IPAM.Config) > 1 { + utils.InternalServerError(w, errors.New("compat network create can only support one IPAM config")) + return + } + + if len(networkCreate.IPAM.Config[0].Subnet) > 0 { + _, subnet, err := net.ParseCIDR(networkCreate.IPAM.Config[0].Subnet) + if err != nil { + utils.InternalServerError(w, err) + return + } + ncOptions.Subnet = *subnet + } + if len(networkCreate.IPAM.Config[0].Gateway) > 0 { + ncOptions.Gateway = net.ParseIP(networkCreate.IPAM.Config[0].Gateway) + } + if len(networkCreate.IPAM.Config[0].IPRange) > 0 { + _, IPRange, err := net.ParseCIDR(networkCreate.IPAM.Config[0].IPRange) + if err != nil { + utils.InternalServerError(w, err) + return + } + ncOptions.Range = *IPRange + } + } + ce := abi.ContainerEngine{Libpod: runtime} + _, err := ce.NetworkCreate(r.Context(), name, ncOptions) + if err != nil { + utils.InternalServerError(w, err) + } + report := types.NetworkCreate{ + CheckDuplicate: networkCreate.CheckDuplicate, + Driver: networkCreate.Driver, + Scope: networkCreate.Scope, + EnableIPv6: networkCreate.EnableIPv6, + IPAM: networkCreate.IPAM, + Internal: networkCreate.Internal, + Attachable: networkCreate.Attachable, + Ingress: networkCreate.Ingress, + ConfigOnly: networkCreate.ConfigOnly, + ConfigFrom: networkCreate.ConfigFrom, + Options: networkCreate.Options, + Labels: networkCreate.Labels, + } + utils.WriteResponse(w, http.StatusOK, report) +} + +func RemoveNetwork(w http.ResponseWriter, r *http.Request) { + runtime := r.Context().Value("runtime").(*libpod.Runtime) + config, err := runtime.GetConfig() + if err != nil { + utils.InternalServerError(w, err) + return + } + name := utils.GetName(r) + exists, err := network.Exists(config, name) + if err != nil { + utils.InternalServerError(w, err) + return + } + if !exists { + utils.Error(w, "network not found", http.StatusNotFound, err) + return + } + if err := network.RemoveNetwork(config, name); err != nil { + utils.InternalServerError(w, err) + } + utils.WriteResponse(w, http.StatusNoContent, "") +} diff --git a/pkg/api/handlers/compat/resize.go b/pkg/api/handlers/compat/resize.go index 3ead733bc..231b53175 100644 --- a/pkg/api/handlers/compat/resize.go +++ b/pkg/api/handlers/compat/resize.go @@ -1,10 +1,12 @@ package compat import ( + "fmt" "net/http" "strings" "github.com/containers/libpod/libpod" + "github.com/containers/libpod/libpod/define" "github.com/containers/libpod/pkg/api/handlers/utils" "github.com/gorilla/schema" "github.com/pkg/errors" @@ -43,6 +45,14 @@ func ResizeTTY(w http.ResponseWriter, r *http.Request) { utils.ContainerNotFound(w, name, err) return } + if state, err := ctnr.State(); err != nil { + utils.InternalServerError(w, errors.Wrapf(err, "cannot obtain container state")) + return + } else if state != define.ContainerStateRunning { + utils.Error(w, "Container not running", http.StatusConflict, + fmt.Errorf("container %q in wrong state %q", name, state.String())) + return + } if err := ctnr.AttachResize(sz); err != nil { utils.InternalServerError(w, errors.Wrapf(err, "cannot resize container")) return @@ -56,6 +66,14 @@ func ResizeTTY(w http.ResponseWriter, r *http.Request) { utils.SessionNotFound(w, name, err) return } + if state, err := ctnr.State(); err != nil { + utils.InternalServerError(w, errors.Wrapf(err, "cannot obtain session container state")) + return + } else if state != define.ContainerStateRunning { + utils.Error(w, "Container not running", http.StatusConflict, + fmt.Errorf("container %q in wrong state %q", name, state.String())) + return + } if err := ctnr.ExecResize(name, sz); err != nil { utils.InternalServerError(w, errors.Wrapf(err, "cannot resize session")) return diff --git a/pkg/api/handlers/compat/swagger.go b/pkg/api/handlers/compat/swagger.go index ce83aa32f..dc94a7ebd 100644 --- a/pkg/api/handlers/compat/swagger.go +++ b/pkg/api/handlers/compat/swagger.go @@ -3,6 +3,7 @@ package compat import ( "github.com/containers/libpod/pkg/domain/entities" "github.com/containers/storage/pkg/archive" + "github.com/docker/docker/api/types" ) // Create container @@ -35,3 +36,30 @@ type swagChangesResponse struct { Changes []archive.Change } } + +// 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 } +} diff --git a/pkg/api/handlers/compat/types.go b/pkg/api/handlers/compat/types.go index b8d06760f..6d47ede64 100644 --- a/pkg/api/handlers/compat/types.go +++ b/pkg/api/handlers/compat/types.go @@ -48,7 +48,7 @@ type StatsJSON struct { Stats Name string `json:"name,omitempty"` - ID string `json:"id,omitempty"` + ID string `json:"Id,omitempty"` // Networks request version >=1.21 Networks map[string]docker.NetworkStats `json:"networks,omitempty"` diff --git a/pkg/api/handlers/libpod/containers.go b/pkg/api/handlers/libpod/containers.go index 3902bdc9b..50f6b1a38 100644 --- a/pkg/api/handlers/libpod/containers.go +++ b/pkg/api/handlers/libpod/containers.go @@ -66,6 +66,10 @@ func ListContainers(w http.ResponseWriter, r *http.Request) { utils.InternalServerError(w, err) return } + if len(pss) == 0 { + utils.WriteResponse(w, http.StatusOK, "[]") + return + } utils.WriteResponse(w, http.StatusOK, pss) } diff --git a/pkg/api/handlers/libpod/copy.go b/pkg/api/handlers/libpod/copy.go new file mode 100644 index 000000000..a3b404bce --- /dev/null +++ b/pkg/api/handlers/libpod/copy.go @@ -0,0 +1,12 @@ +package libpod + +import ( + "net/http" + + "github.com/containers/libpod/pkg/api/handlers/utils" + "github.com/pkg/errors" +) + +func Archive(w http.ResponseWriter, r *http.Request) { + utils.Error(w, "not implemented", http.StatusNotImplemented, errors.New("not implemented")) +} diff --git a/pkg/api/handlers/libpod/images.go b/pkg/api/handlers/libpod/images.go index 1cbcfb52c..4b277d39c 100644 --- a/pkg/api/handlers/libpod/images.go +++ b/pkg/api/handlers/libpod/images.go @@ -21,6 +21,7 @@ import ( image2 "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/pkg/api/handlers" "github.com/containers/libpod/pkg/api/handlers/utils" + "github.com/containers/libpod/pkg/auth" "github.com/containers/libpod/pkg/domain/entities" "github.com/containers/libpod/pkg/domain/infra/abi" "github.com/containers/libpod/pkg/errorhandling" @@ -28,6 +29,7 @@ import ( utils2 "github.com/containers/libpod/utils" "github.com/gorilla/schema" "github.com/pkg/errors" + "github.com/sirupsen/logrus" ) // Commit @@ -339,7 +341,6 @@ func ImagesPull(w http.ResponseWriter, r *http.Request) { decoder := r.Context().Value("decoder").(*schema.Decoder) query := struct { Reference string `schema:"reference"` - Credentials string `schema:"credentials"` OverrideOS string `schema:"overrideOS"` OverrideArch string `schema:"overrideArch"` TLSVerify bool `schema:"tlsVerify"` @@ -382,20 +383,16 @@ func ImagesPull(w http.ResponseWriter, r *http.Request) { return } - var registryCreds *types.DockerAuthConfig - if len(query.Credentials) != 0 { - creds, err := util.ParseRegistryCreds(query.Credentials) - if err != nil { - utils.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest, - errors.Wrapf(err, "error parsing credentials %q", query.Credentials)) - return - } - registryCreds = creds + authConf, authfile, err := auth.GetCredentials(r) + if err != nil { + utils.Error(w, "Something went wrong.", http.StatusBadRequest, errors.Wrapf(err, "Failed to parse %q header for %s", auth.XRegistryAuthHeader, r.URL.String())) + return } + defer auth.RemoveAuthfile(authfile) // Setup the registry options dockerRegistryOptions := image.DockerRegistryOptions{ - DockerRegistryCreds: registryCreds, + DockerRegistryCreds: authConf, OSChoice: query.OverrideOS, ArchitectureChoice: query.OverrideArch, } @@ -403,6 +400,13 @@ func ImagesPull(w http.ResponseWriter, r *http.Request) { dockerRegistryOptions.DockerInsecureSkipTLSVerify = types.NewOptionalBool(!query.TLSVerify) } + sys := runtime.SystemContext() + if sys == nil { + sys = image.GetSystemContext("", authfile, false) + } + dockerRegistryOptions.DockerCertPath = sys.DockerCertPath + sys.DockerAuthConfig = authConf + // Prepare the images we want to pull imagesToPull := []string{} res := []handlers.LibpodImagesPullReport{} @@ -411,8 +415,7 @@ func ImagesPull(w http.ResponseWriter, r *http.Request) { if !query.AllTags { imagesToPull = append(imagesToPull, imageName) } else { - systemContext := image.GetSystemContext("", "", false) - tags, err := docker.GetRepositoryTags(context.Background(), systemContext, imageRef) + tags, err := docker.GetRepositoryTags(context.Background(), sys, imageRef) if err != nil { utils.InternalServerError(w, errors.Wrap(err, "error getting repository tags")) return @@ -422,12 +425,6 @@ func ImagesPull(w http.ResponseWriter, r *http.Request) { } } - authfile := "" - if sys := runtime.SystemContext(); sys != nil { - dockerRegistryOptions.DockerCertPath = sys.DockerCertPath - authfile = sys.AuthFilePath - } - // Finally pull the images for _, img := range imagesToPull { newImage, err := runtime.ImageRuntime().New( @@ -456,7 +453,6 @@ func PushImage(w http.ResponseWriter, r *http.Request) { runtime := r.Context().Value("runtime").(*libpod.Runtime) query := struct { - Credentials string `schema:"credentials"` Destination string `schema:"destination"` TLSVerify bool `schema:"tlsVerify"` }{ @@ -492,26 +488,20 @@ func PushImage(w http.ResponseWriter, r *http.Request) { return } - var registryCreds *types.DockerAuthConfig - if len(query.Credentials) != 0 { - creds, err := util.ParseRegistryCreds(query.Credentials) - if err != nil { - utils.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest, - errors.Wrapf(err, "error parsing credentials %q", query.Credentials)) - return - } - registryCreds = creds + authConf, authfile, err := auth.GetCredentials(r) + if err != nil { + utils.Error(w, "Something went wrong.", http.StatusBadRequest, errors.Wrapf(err, "Failed to parse %q header for %s", auth.XRegistryAuthHeader, r.URL.String())) + return } + defer auth.RemoveAuthfile(authfile) + logrus.Errorf("AuthConf: %v", authConf) - // TODO: the X-Registry-Auth header is not checked yet here nor in any other - // endpoint. Pushing does NOT work with authentication at the moment. dockerRegistryOptions := &image.DockerRegistryOptions{ - DockerRegistryCreds: registryCreds, + DockerRegistryCreds: authConf, } - authfile := "" if sys := runtime.SystemContext(); sys != nil { dockerRegistryOptions.DockerCertPath = sys.DockerCertPath - authfile = sys.AuthFilePath + dockerRegistryOptions.RegistriesConfPath = sys.SystemRegistriesConfPath } if _, found := r.URL.Query()["tlsVerify"]; found { dockerRegistryOptions.DockerInsecureSkipTLSVerify = types.NewOptionalBool(!query.TLSVerify) diff --git a/pkg/api/handlers/libpod/manifests.go b/pkg/api/handlers/libpod/manifests.go index 93ca367f7..aef92368b 100644 --- a/pkg/api/handlers/libpod/manifests.go +++ b/pkg/api/handlers/libpod/manifests.go @@ -120,6 +120,10 @@ func ManifestRemove(w http.ResponseWriter, r *http.Request) { utils.WriteResponse(w, http.StatusOK, handlers.IDResponse{ID: newID}) } func ManifestPush(w http.ResponseWriter, r *http.Request) { + // FIXME: parameters are missing (tlsVerify, format). + // Also, we should use the ABI function to avoid duplicate code. + // Also, support for XRegistryAuth headers are missing. + runtime := r.Context().Value("runtime").(*libpod.Runtime) decoder := r.Context().Value("decoder").(*schema.Decoder) query := struct { diff --git a/pkg/api/handlers/libpod/play.go b/pkg/api/handlers/libpod/play.go index 26e02bf4f..1cb5cdb6c 100644 --- a/pkg/api/handlers/libpod/play.go +++ b/pkg/api/handlers/libpod/play.go @@ -9,6 +9,7 @@ import ( "github.com/containers/image/v5/types" "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/api/handlers/utils" + "github.com/containers/libpod/pkg/auth" "github.com/containers/libpod/pkg/domain/entities" "github.com/containers/libpod/pkg/domain/infra/abi" "github.com/gorilla/schema" @@ -47,9 +48,26 @@ func PlayKube(w http.ResponseWriter, r *http.Request) { utils.Error(w, "Something went wrong.", http.StatusInternalServerError, errors.Wrap(err, "error closing temporary file")) return } + authConf, authfile, err := auth.GetCredentials(r) + if err != nil { + utils.Error(w, "Something went wrong.", http.StatusBadRequest, errors.Wrapf(err, "Failed to parse %q header for %s", auth.XRegistryAuthHeader, r.URL.String())) + return + } + defer auth.RemoveAuthfile(authfile) + var username, password string + if authConf != nil { + username = authConf.Username + password = authConf.Password + } containerEngine := abi.ContainerEngine{Libpod: runtime} - options := entities.PlayKubeOptions{Network: query.Network, Quiet: true} + options := entities.PlayKubeOptions{ + Authfile: authfile, + Username: username, + Password: password, + Network: query.Network, + Quiet: true, + } if _, found := r.URL.Query()["tlsVerify"]; found { options.SkipTLSVerify = types.NewOptionalBool(!query.TLSVerify) } diff --git a/pkg/api/handlers/types.go b/pkg/api/handlers/types.go index d8cdd9caf..aa3d0fe91 100644 --- a/pkg/api/handlers/types.go +++ b/pkg/api/handlers/types.go @@ -120,7 +120,7 @@ type CreateContainerConfig struct { // swagger:model IDResponse type IDResponse struct { // ID - ID string `json:"id"` + ID string `json:"Id"` } type ContainerTopOKBody struct { diff --git a/pkg/api/server/register_archive.go b/pkg/api/server/register_archive.go new file mode 100644 index 000000000..a1d5941bc --- /dev/null +++ b/pkg/api/server/register_archive.go @@ -0,0 +1,171 @@ +package server + +import ( + "net/http" + + "github.com/containers/libpod/pkg/api/handlers/compat" + "github.com/containers/libpod/pkg/api/handlers/libpod" + "github.com/gorilla/mux" +) + +func (s *APIServer) registerAchiveHandlers(r *mux.Router) error { + // swagger:operation POST /containers/{name}/archive compat putArchive + // --- + // summary: Put files into a container + // description: Put a tar archive of files into a container + // tags: + // - containers (compat) + // produces: + // - application/json + // parameters: + // - in: path + // name: name + // type: string + // description: container name or id + // required: true + // - in: query + // name: path + // type: string + // description: Path to a directory in the container to extract + // required: true + // - in: query + // name: noOverwriteDirNonDir + // type: string + // description: if unpacking the given content would cause an existing directory to be replaced with a non-directory and vice versa (1 or true) + // - in: query + // name: copyUIDGID + // type: string + // description: copy UID/GID maps to the dest file or di (1 or true) + // - in: body + // name: request + // description: tarfile of files to copy into the container + // schema: + // type: string + // responses: + // 200: + // description: no error + // 400: + // $ref: "#/responses/BadParamError" + // 403: + // description: the container rootfs is read-only + // 404: + // $ref: "#/responses/NoSuchContainer" + // 500: + // $ref: "#/responses/InternalError" + + // swagger:operation GET /containers/{name}/archive compat getArchive + // --- + // summary: Get files from a container + // description: Get a tar archive of files from a container + // tags: + // - containers (compat) + // produces: + // - application/json + // parameters: + // - in: path + // name: name + // type: string + // description: container name or id + // required: true + // - in: query + // name: path + // type: string + // description: Path to a directory in the container to extract + // required: true + // responses: + // 200: + // description: no error + // schema: + // type: string + // format: binary + // 400: + // $ref: "#/responses/BadParamError" + // 404: + // $ref: "#/responses/NoSuchContainer" + // 500: + // $ref: "#/responses/InternalError" + r.HandleFunc(VersionedPath("/containers/{name}/archive"), s.APIHandler(compat.Archive)).Methods(http.MethodGet, http.MethodPost) + // Added non version path to URI to support docker non versioned paths + r.HandleFunc("/containers/{name}/archive", s.APIHandler(compat.Archive)).Methods(http.MethodGet, http.MethodPost) + + /* + Libpod + */ + + // swagger:operation POST /libpod/containers/{name}/copy libpod libpodPutArchive + // --- + // summary: Copy files into a container + // description: Copy a tar archive of files into a container + // tags: + // - containers + // produces: + // - application/json + // parameters: + // - in: path + // name: name + // type: string + // description: container name or id + // required: true + // - in: query + // name: path + // type: string + // description: Path to a directory in the container to extract + // required: true + // - in: query + // name: pause + // type: boolean + // description: pause the container while copying (defaults to true) + // default: true + // - in: body + // name: request + // description: tarfile of files to copy into the container + // schema: + // type: string + // responses: + // 200: + // description: no error + // 400: + // $ref: "#/responses/BadParamError" + // 403: + // description: the container rootfs is read-only + // 404: + // $ref: "#/responses/NoSuchContainer" + // 500: + // $ref: "#/responses/InternalError" + + // swagger:operation GET /libpod/containers/{name}/copy libpod libpodGetArchive + // --- + // summary: Copy files from a container + // description: Copy a tar archive of files from a container + // tags: + // - containers (compat) + // produces: + // - application/json + // parameters: + // - in: path + // name: name + // type: string + // description: container name or id + // required: true + // - in: query + // name: path + // type: string + // description: Path to a directory in the container to extract + // required: true + // responses: + // 200: + // description: no error + // schema: + // type: string + // format: binary + // 400: + // $ref: "#/responses/BadParamError" + // 404: + // $ref: "#/responses/NoSuchContainer" + // 500: + // $ref: "#/responses/InternalError" + r.HandleFunc(VersionedPath("/libpod/containers/{name}/copy"), s.APIHandler(libpod.Archive)).Methods(http.MethodGet, http.MethodPost) + r.HandleFunc(VersionedPath("/libpod/containers/{name}/archive"), s.APIHandler(libpod.Archive)).Methods(http.MethodGet, http.MethodPost) + + return nil +} diff --git a/pkg/api/server/register_events.go b/pkg/api/server/register_events.go index e909303da..2b85eb169 100644 --- a/pkg/api/server/register_events.go +++ b/pkg/api/server/register_events.go @@ -58,6 +58,11 @@ func (s *APIServer) registerEventsHandlers(r *mux.Router) error { // type: string // in: query // description: JSON encoded map[string][]string of constraints + // - name: stream + // type: boolean + // in: query + // default: true + // description: when false, do not follow events // responses: // 200: // description: returns a string of json data describing an event diff --git a/pkg/api/server/register_images.go b/pkg/api/server/register_images.go index c885dc81a..83584d0f3 100644 --- a/pkg/api/server/register_images.go +++ b/pkg/api/server/register_images.go @@ -8,6 +8,10 @@ import ( "github.com/gorilla/mux" ) +// TODO +// +// * /images/create is missing the "message" and "platform" parameters + func (s *APIServer) registerImagesHandlers(r *mux.Router) error { // swagger:operation POST /images/create compat createImage // --- @@ -631,13 +635,14 @@ func (s *APIServer) registerImagesHandlers(r *mux.Router) error { // required: true // description: Name of image to push. // - in: query - // name: tag + // name: destination // type: string - // description: The tag to associate with the image on the registry. + // description: Allows for pushing the image to a different destintation than the image refers to. // - in: query - // name: credentials - // description: username:password for the registry. - // type: string + // name: tlsVerify + // description: Require TLS verification. + // type: boolean + // default: true // - in: header // name: X-Registry-Auth // type: string diff --git a/pkg/api/server/register_networks.go b/pkg/api/server/register_networks.go index b1189c1f4..2c60b2b27 100644 --- a/pkg/api/server/register_networks.go +++ b/pkg/api/server/register_networks.go @@ -3,11 +3,96 @@ package server import ( "net/http" + "github.com/containers/libpod/pkg/api/handlers/compat" "github.com/containers/libpod/pkg/api/handlers/libpod" "github.com/gorilla/mux" ) func (s *APIServer) registerNetworkHandlers(r *mux.Router) error { + // swagger:operation DELETE /networks/{name} compat compatRemoveNetwork + // --- + // tags: + // - networks (compat) + // summary: Remove a network + // description: Remove a network + // parameters: + // - in: path + // name: name + // type: string + // required: true + // description: the name of the network + // produces: + // - application/json + // responses: + // 204: + // description: no error + // 404: + // $ref: "#/responses/NoSuchNetwork" + // 500: + // $ref: "#/responses/InternalError" + r.HandleFunc(VersionedPath("/networks/{name}"), s.APIHandler(compat.RemoveNetwork)).Methods(http.MethodDelete) + r.HandleFunc("/networks/{name}", s.APIHandler(compat.RemoveNetwork)).Methods(http.MethodDelete) + // swagger:operation GET /networks/{name}/json compat compatInspectNetwork + // --- + // tags: + // - networks (compat) + // summary: Inspect a network + // description: Display low level configuration network + // parameters: + // - in: path + // name: name + // type: string + // required: true + // description: the name of the network + // produces: + // - application/json + // responses: + // 200: + // $ref: "#/responses/CompatNetworkInspect" + // 404: + // $ref: "#/responses/NoSuchNetwork" + // 500: + // $ref: "#/responses/InternalError" + r.HandleFunc(VersionedPath("/networks/{name}/json"), s.APIHandler(compat.InspectNetwork)).Methods(http.MethodGet) + r.HandleFunc("/networks/{name}/json", s.APIHandler(compat.InspectNetwork)).Methods(http.MethodGet) + // swagger:operation GET /networks/json compat compatListNetwork + // --- + // tags: + // - networks (compat) + // summary: List networks + // description: Display summary of network configurations + // produces: + // - application/json + // responses: + // 200: + // $ref: "#/responses/CompatNetworkList" + // 500: + // $ref: "#/responses/InternalError" + r.HandleFunc(VersionedPath("/networks/json"), s.APIHandler(compat.ListNetworks)).Methods(http.MethodGet) + r.HandleFunc("/networks", s.APIHandler(compat.ListNetworks)).Methods(http.MethodGet) + // swagger:operation POST /networks/create compat compatCreateNetwork + // --- + // tags: + // - networks (compat) + // summary: Create network + // description: Create a network configuration + // produces: + // - application/json + // parameters: + // - in: body + // name: create + // description: attributes for creating a container + // schema: + // $ref: "#/definitions/NetworkCreateRequest" + // responses: + // 200: + // $ref: "#/responses/CompatNetworkCreate" + // 400: + // $ref: "#/responses/BadParamError" + // 500: + // $ref: "#/responses/InternalError" + r.HandleFunc(VersionedPath("/networks/create"), s.APIHandler(compat.CreateNetwork)).Methods(http.MethodPost) + r.HandleFunc("/networks/create", s.APIHandler(compat.CreateNetwork)).Methods(http.MethodPost) // swagger:operation DELETE /libpod/networks/{name} libpod libpodRemoveNetwork // --- // tags: @@ -33,6 +118,11 @@ func (s *APIServer) registerNetworkHandlers(r *mux.Router) error { // $ref: "#/responses/NoSuchNetwork" // 500: // $ref: "#/responses/InternalError" + + /* + Libpod + */ + r.HandleFunc(VersionedPath("/libpod/networks/{name}"), s.APIHandler(libpod.RemoveNetwork)).Methods(http.MethodDelete) // swagger:operation GET /libpod/networks/{name}/json libpod libpodInspectNetwork // --- diff --git a/pkg/api/server/server.go b/pkg/api/server/server.go index d39528f45..499a4c58a 100644 --- a/pkg/api/server/server.go +++ b/pkg/api/server/server.go @@ -92,8 +92,17 @@ func newServer(runtime *libpod.Runtime, duration time.Duration, listener *net.Li }, ) + router.MethodNotAllowedHandler = http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + // We can track user errors... + logrus.Infof("Failed Request: (%d:%s) for %s:'%s'", http.StatusMethodNotAllowed, http.StatusText(http.StatusMethodNotAllowed), r.Method, r.URL.String()) + http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + }, + ) + for _, fn := range []func(*mux.Router) error{ server.registerAuthHandlers, + server.registerAchiveHandlers, server.registerContainersHandlers, server.registerDistributionHandlers, server.registerEventsHandlers, diff --git a/pkg/api/server/swagger.go b/pkg/api/server/swagger.go index ebd99ba27..c463f809e 100644 --- a/pkg/api/server/swagger.go +++ b/pkg/api/server/swagger.go @@ -139,6 +139,13 @@ type swagImageSummary struct { Body []entities.ImageSummary } +// Registries summary +// swagger:response DocsRegistriesList +type swagRegistriesList struct { + // in:body + Body entities.ListRegistriesReport +} + // List Containers // swagger:response DocsListContainer type swagListContainers struct { diff --git a/pkg/api/tags.yaml b/pkg/api/tags.yaml index 1ffb5e940..f86f8dbea 100644 --- a/pkg/api/tags.yaml +++ b/pkg/api/tags.yaml @@ -21,5 +21,7 @@ tags: description: Actions related to exec for the compatibility endpoints - name: images (compat) description: Actions related to images for the compatibility endpoints + - name: networks (compat) + description: Actions related to compatibility networks - name: system (compat) description: Actions related to Podman and compatibility engines |