From d924494f561bb878a2b3a7ce438d87ecb934b5fb Mon Sep 17 00:00:00 2001 From: Jhon Honce Date: Fri, 1 Nov 2019 13:03:34 -0700 Subject: Initial commit on compatible API Signed-off-by: Jhon Honce Create service command Use cd cmd/service && go build . $ systemd-socket-activate -l 8081 cmd/service/service & $ curl http://localhost:8081/v1.24/images/json Signed-off-by: Jhon Honce Correct Makefile Signed-off-by: Jhon Honce Two more stragglers Signed-off-by: Jhon Honce Report errors back as http headers Signed-off-by: Jhon Honce Split out handlers, updated output Output aligned to docker structures Signed-off-by: Jhon Honce Refactored routing, added more endpoints and types * Encapsulated all the routing information in the handler_* files. * Added more serviceapi/types, including podman additions. See Info Signed-off-by: Jhon Honce Cleaned up code, implemented info content * Move Content-Type check into serviceHandler * Custom 404 handler showing the url, mostly for debugging * Refactored images: better method names and explicit http codes * Added content to /info * Added podman fields to Info struct * Added Container struct Signed-off-by: Jhon Honce Add a bunch of endpoints containers: stop, pause, unpause, wait, rm images: tag, rmi, create (pull only) Signed-off-by: baude Add even more handlers * Add serviceapi/Error() to improve error handling * Better support for API return payloads * Renamed unimplemented to unsupported these are generic endpoints we don't intend to ever support. Swarm broken out since it uses different HTTP codes to signal that the node is not in a swarm. * Added more types * API Version broken out so it can be validated in the future Signed-off-by: Jhon Honce Refactor to introduce ServiceWriter Signed-off-by: Jhon Honce populate pods endpoints /libpod/pods/.. exists, kill, pause, prune, restart, remove, start, stop, unpause Signed-off-by: baude Add components to Version, fix Error body Signed-off-by: Jhon Honce Add images pull output, fix swarm routes * docker-py tests/integration/api_client_test.py pass 100% * docker-py tests/integration/api_image_test.py pass 4/16 + Test failures include services podman does not support Signed-off-by: Jhon Honce pods endpoint submission 2 add create and others; only top and stats is left. Signed-off-by: baude Update pull image to work from empty registry Signed-off-by: Jhon Honce pod create and container create first pass at pod and container create. the container create does not quite work yet but it is very close. pod create needs a partial rewrite. also broken off the DELETE (rm/rmi) to specific handler funcs. Signed-off-by: baude Add docker-py demos, GET .../containers/json * Update serviceapi/types to reflect libpod not podman * Refactored removeImage() to provide non-streaming return Signed-off-by: Jhon Honce create container part2 finished minimal config needed for create container. started demo.py for upcoming talk Signed-off-by: baude Stop server after honoring request * Remove casting for method calls * Improve WriteResponse() * Update Container API type to match docker API Signed-off-by: Jhon Honce fix namespace assumptions cleaned up namespace issues with libpod. Signed-off-by: baude wip Signed-off-by: baude Add sliding window when shutting down server * Added a Timeout rather than closing down service on each call * Added gorilla/schema dependency for Decode'ing query parameters * Improved error handling * Container logs returned and multiplexed for stdout and stderr * .../containers/{name}/logs?stdout=True&stderr=True * Container stats * .../containers/{name}/stats Signed-off-by: Jhon Honce Improve error handling * Add check for at least one std stream required for /containers/{id}/logs * Add check for state in /containers/{id}/top * Fill in more fields for /info * Fixed error checking in service start code Signed-off-by: Jhon Honce get rest of image tests for pass Signed-off-by: baude linting our content Signed-off-by: baude more linting Signed-off-by: baude more linting Signed-off-by: baude pruning Signed-off-by: baude [CI:DOCS]apiv2 pods migrate from using args in the url to using a json struct in body for pod create. Signed-off-by: baude fix handler_images prune prune's api changed slightly to deal with filters. Signed-off-by: baude [CI:DOCS]enabled base container create tests enabling the base container create tests which allow us to get more into the stop, kill, etc tests. many new tests now pass. Signed-off-by: baude serviceapi errors: append error message to API message I dearly hope this is not breaking any other tests but debugging "Internal Server Error" is not helpful to any user. In case, it breaks tests, we can rever the commit - that's why it's a small one. Signed-off-by: Valentin Rothberg serviceAPI: add containers/prune endpoint Signed-off-by: Valentin Rothberg add `service` make target Also remove the non-functional sub-Makefile. Signed-off-by: Valentin Rothberg add make targets for testing the service * `sudo make run-service` for running the service. * `DOCKERPY_TEST="tests/integration/api_container_test.py::ListContainersTest" \ make run-docker-py-tests` for running a specific tests. Run all tests by leaving the env variable empty. Signed-off-by: Valentin Rothberg Split handlers and server packages The files were split to help contain bloat. The api/server package will contain all code related to the functioning of the server while api/handlers will have all the code related to implementing the end points. api/server/register_* will contain the methods for registering endpoints. Additionally, they will have the comments for generating the swagger spec file. See api/handlers/version.go for a small example handler, api/handlers/containers.go contains much more complex handlers. Signed-off-by: Jhon Honce [CI:DOCS]enabled more tests Signed-off-by: baude [CI:DOCS]libpod endpoints small refactor for libpod inclusion and began adding endpoints. Signed-off-by: baude Implement /build and /events * Include crypto libraries for future ssh work Signed-off-by: Jhon Honce [CI:DOCS]more image implementations convert from using for to query structs among other changes including new endpoints. Signed-off-by: baude [CI:DOCS]add bindings for golang Signed-off-by: baude [CI:DOCS]add volume endpoints for libpod create, inspect, ls, prune, and rm Signed-off-by: baude [CI:DOCS]apiv2 healthcheck enablement wire up container healthchecks for the api. Signed-off-by: baude [CI:DOCS]Add mount endpoints via the api, allow ability to mount a container and list container mounts. Signed-off-by: baude [CI:DOCS]Add search endpoint add search endpoint with golang bindings Signed-off-by: baude [CI:DOCS]more apiv2 development misc population of methods, etc Signed-off-by: baude rebase cleanup and epoch reset Signed-off-by: baude [CI:DOCS]add more network endpoints also, add some initial error handling and convenience functions for standard endpoints. Signed-off-by: baude [CI:DOCS]use helper funcs for bindings use the methods developed to make writing bindings less duplicative and easier to use. Signed-off-by: baude [CI:DOCS]add return info for prereview begin to add return info and status codes for errors so that we can review the apiv2 Signed-off-by: baude [CI:DOCS]first pass at adding swagger docs for api Signed-off-by: baude --- pkg/api/handlers/types.go | 534 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 534 insertions(+) create mode 100644 pkg/api/handlers/types.go (limited to 'pkg/api/handlers/types.go') diff --git a/pkg/api/handlers/types.go b/pkg/api/handlers/types.go new file mode 100644 index 000000000..9edbbdccc --- /dev/null +++ b/pkg/api/handlers/types.go @@ -0,0 +1,534 @@ +package handlers + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + "time" + + "github.com/containers/image/v5/manifest" + "github.com/containers/libpod/libpod" + "github.com/containers/libpod/libpod/define" + "github.com/containers/libpod/libpod/events" + libpodImage "github.com/containers/libpod/libpod/image" + docker "github.com/docker/docker/api/types" + dockerContainer "github.com/docker/docker/api/types/container" + dockerEvents "github.com/docker/docker/api/types/events" + dockerNetwork "github.com/docker/docker/api/types/network" + "github.com/docker/go-connections/nat" + "github.com/pkg/errors" +) + +type AuthConfig struct { + docker.AuthConfig +} + +type ImageInspect struct { + docker.ImageInspect +} + +type ContainerConfig struct { + dockerContainer.Config +} + +type ImageSummary struct { + docker.ImageSummary + CreatedTime time.Time `json:"CreatedTime,omitempty"` + ReadOnly bool `json:"ReadOnly,omitempty"` +} + +type ContainersPruneReport struct { + docker.ContainersPruneReport +} + +type Info struct { + docker.Info + BuildahVersion string + CPURealtimePeriod bool + CPURealtimeRuntime bool + CgroupVersion string + Rootless bool + SwapFree int64 + SwapTotal int64 + Uptime string +} + +type Container struct { + docker.Container + docker.ContainerCreateConfig +} + +type ContainerStats struct { + docker.ContainerStats +} + +type Ping struct { + docker.Ping +} + +type Version struct { + docker.Version +} + +type DiskUsage struct { + docker.DiskUsage +} + +type VolumesPruneReport struct { + docker.VolumesPruneReport +} + +type ImagesPruneReport struct { + docker.ImagesPruneReport +} + +type BuildCachePruneReport struct { + docker.BuildCachePruneReport +} + +type NetworkPruneReport struct { + docker.NetworksPruneReport +} + +type ConfigCreateResponse struct { + docker.ConfigCreateResponse +} + +type PushResult struct { + docker.PushResult +} + +type BuildResult struct { + docker.BuildResult +} + +type ContainerWaitOKBody struct { + StatusCode int + Error struct { + Message string + } +} + +type CreateContainerConfig struct { + Name string + dockerContainer.Config + HostConfig dockerContainer.HostConfig + NetworkingConfig dockerNetwork.NetworkingConfig +} + +type VolumeCreateConfig struct { + Name string `json:"name"` + Driver string `schema:"driver"` + Label map[string]string `schema:"label"` + Opts map[string]string `schema:"opts"` +} + +type IDResponse struct { + ID string `json:"id"` +} + +type Stats struct { + docker.StatsJSON +} + +type ContainerTopOKBody struct { + dockerContainer.ContainerTopOKBody + ID string `json:"Id"` +} + +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"` + Labels []string `json:"labels"` + Publish []string `json:"publish"` + Share string `json:"share"` +} + +type ErrorModel struct { + Message string `json:"message"` +} + +type Event struct { + dockerEvents.Message +} + +type HistoryResponse struct { + ID string `json:"Id"` + Created int64 `json:"Created"` + CreatedBy string `json:"CreatedBy"` + Tags []string `json:"Tags"` + Size int64 `json:"Size"` + Comment string `json:"Comment"` +} + +type ImageLayer struct{} + +type ImageTreeResponse struct { + ID string `json:"id"` + Tags []string `json:"tags"` + Size string `json:"size"` + Layers []ImageLayer `json:"layers"` +} + +func EventToApiEvent(e *events.Event) *Event { + return &Event{dockerEvents.Message{ + Type: e.Type.String(), + Action: e.Status.String(), + Actor: dockerEvents.Actor{ + ID: e.ID, + Attributes: map[string]string{ + "image": e.Image, + "name": e.Name, + "containerExitCode": strconv.Itoa(e.ContainerExitCode), + }, + }, + Scope: "local", + Time: e.Time.Unix(), + TimeNano: e.Time.UnixNano(), + }} +} + +func ImageToImageSummary(l *libpodImage.Image) (*ImageSummary, error) { + containers, err := l.Containers() + if err != nil { + return nil, errors.Wrapf(err, "Failed to obtain Containers for image %s", l.ID()) + } + containerCount := len(containers) + + var digests []string + for _, d := range l.Digests() { + digests = append(digests, string(d)) + } + + tags, err := l.RepoTags() + if err != nil { + return nil, errors.Wrapf(err, "Failed to obtain RepoTags for image %s", l.ID()) + } + + // FIXME: GetParent() panics + // parent, err := l.GetParent(context.TODO()) + // if err != nil { + // return nil, errors.Wrapf(err, "Failed to obtain ParentID for image %s", l.ID()) + // } + + labels, err := l.Labels(context.TODO()) + if err != nil { + return nil, errors.Wrapf(err, "Failed to obtain Labels for image %s", l.ID()) + } + + size, err := l.Size(context.TODO()) + if err != nil { + return nil, errors.Wrapf(err, "Failed to obtain Size for image %s", l.ID()) + } + dockerSummary := docker.ImageSummary{ + Containers: int64(containerCount), + Created: l.Created().Unix(), + ID: l.ID(), + Labels: labels, + ParentID: l.Parent, + RepoDigests: digests, + RepoTags: tags, + SharedSize: 0, + Size: int64(*size), + VirtualSize: int64(*size), + } + is := ImageSummary{ + ImageSummary: dockerSummary, + } + return &is, nil +} + +func ImageDataToImageInspect(ctx context.Context, l *libpodImage.Image) (*ImageInspect, error) { + info, err := l.Inspect(context.Background()) + if err != nil { + return nil, err + } + ports, err := portsToPortSet(info.Config.ExposedPorts) + if err != nil { + return nil, err + } + // TODO the rest of these still need wiring! + config := dockerContainer.Config{ + // Hostname: "", + // Domainname: "", + User: info.User, + // AttachStdin: false, + // AttachStdout: false, + // AttachStderr: false, + ExposedPorts: ports, + // Tty: false, + // OpenStdin: false, + // StdinOnce: false, + Env: info.Config.Env, + Cmd: info.Config.Cmd, + // Healthcheck: nil, + // ArgsEscaped: false, + // Image: "", + // Volumes: nil, + // WorkingDir: "", + // Entrypoint: nil, + // NetworkDisabled: false, + // MacAddress: "", + // OnBuild: nil, + // Labels: nil, + // StopSignal: "", + // StopTimeout: nil, + // Shell: nil, + } + ic, err := l.ToImageRef(ctx) + if err != nil { + return nil, err + } + dockerImageInspect := docker.ImageInspect{ + Architecture: l.Architecture, + Author: l.Author, + Comment: info.Comment, + Config: &config, + Created: l.Created().Format(time.RFC3339Nano), + DockerVersion: "", + GraphDriver: docker.GraphDriverData{}, + ID: fmt.Sprintf("sha256:%s", l.ID()), + Metadata: docker.ImageMetadata{}, + Os: l.Os, + OsVersion: l.Version, + Parent: l.Parent, + RepoDigests: info.RepoDigests, + RepoTags: info.RepoTags, + RootFS: docker.RootFS{}, + Size: info.Size, + Variant: "", + VirtualSize: info.VirtualSize, + } + bi := ic.ConfigInfo() + // For docker images, we need to get the Container id and config + // and populate the image with it. + if bi.MediaType == manifest.DockerV2Schema2ConfigMediaType { + d := manifest.Schema2Image{} + b, err := ic.ConfigBlob(ctx) + if err != nil { + return nil, err + } + if err := json.Unmarshal(b, &d); err != nil { + return nil, err + } + // populate the Container id into the image + dockerImageInspect.Container = d.Container + containerConfig := dockerContainer.Config{} + configBytes, err := json.Marshal(d.ContainerConfig) + if err != nil { + return nil, err + } + if err := json.Unmarshal(configBytes, &containerConfig); err != nil { + return nil, err + } + // populate the Container config in the image + dockerImageInspect.ContainerConfig = &containerConfig + // populate parent + dockerImageInspect.Parent = d.Parent.String() + } + return &ImageInspect{dockerImageInspect}, nil + +} + +func LibpodToContainer(l *libpod.Container, infoData []define.InfoData) (*Container, error) { + imageId, imageName := l.Image() + sizeRW, err := l.RWSize() + if err != nil { + return nil, err + } + + SizeRootFs, err := l.RootFsSize() + if err != nil { + return nil, err + } + + state, err := l.State() + if err != nil { + return nil, err + } + + return &Container{docker.Container{ + ID: l.ID(), + Names: []string{l.Name()}, + Image: imageName, + ImageID: imageId, + Command: strings.Join(l.Command(), " "), + Created: l.CreatedTime().Unix(), + Ports: nil, + SizeRw: sizeRW, + SizeRootFs: SizeRootFs, + Labels: l.Labels(), + State: string(state), + Status: "", + HostConfig: struct { + NetworkMode string `json:",omitempty"` + }{ + "host"}, + NetworkSettings: nil, + Mounts: nil, + }, + docker.ContainerCreateConfig{}, + }, nil +} + +func LibpodToContainerJSON(l *libpod.Container) (*docker.ContainerJSON, error) { + _, imageName := l.Image() + inspect, err := l.Inspect(true) + if err != nil { + return nil, err + } + i, err := json.Marshal(inspect.State) + if err != nil { + return nil, err + } + state := docker.ContainerState{} + if err := json.Unmarshal(i, &state); err != nil { + return nil, err + } + + // docker considers paused to be running + if state.Paused { + state.Running = true + } + + h, err := json.Marshal(inspect.HostConfig) + if err != nil { + return nil, err + } + hc := dockerContainer.HostConfig{} + if err := json.Unmarshal(h, &hc); err != nil { + return nil, err + } + g, err := json.Marshal(inspect.GraphDriver) + if err != nil { + return nil, err + } + graphDriver := docker.GraphDriverData{} + if err := json.Unmarshal(g, &graphDriver); err != nil { + return nil, err + } + + cb := docker.ContainerJSONBase{ + ID: l.ID(), + Created: l.CreatedTime().String(), + Path: "", + Args: nil, + State: &state, + Image: imageName, + ResolvConfPath: inspect.ResolvConfPath, + HostnamePath: inspect.HostnamePath, + HostsPath: inspect.HostsPath, + LogPath: l.LogPath(), + Node: nil, + Name: l.Name(), + RestartCount: 0, + Driver: inspect.Driver, + Platform: "linux", + MountLabel: inspect.MountLabel, + ProcessLabel: inspect.ProcessLabel, + AppArmorProfile: inspect.AppArmorProfile, + ExecIDs: inspect.ExecIDs, + HostConfig: &hc, + GraphDriver: graphDriver, + SizeRw: inspect.SizeRw, + SizeRootFs: &inspect.SizeRootFs, + } + + stopTimeout := int(l.StopTimeout()) + + ports := make(nat.PortSet) + for p := range inspect.HostConfig.PortBindings { + splitp := strings.Split(p, "/") + port, err := nat.NewPort(splitp[0], splitp[1]) + if err != nil { + return nil, err + } + ports[port] = struct{}{} + } + + config := dockerContainer.Config{ + Hostname: l.Hostname(), + Domainname: inspect.Config.DomainName, + User: l.User(), + AttachStdin: inspect.Config.AttachStdin, + AttachStdout: inspect.Config.AttachStdout, + AttachStderr: inspect.Config.AttachStderr, + ExposedPorts: ports, + Tty: inspect.Config.Tty, + OpenStdin: inspect.Config.OpenStdin, + StdinOnce: inspect.Config.StdinOnce, + Env: inspect.Config.Env, + Cmd: inspect.Config.Cmd, + Healthcheck: nil, + ArgsEscaped: false, + Image: imageName, + Volumes: nil, + WorkingDir: l.WorkingDir(), + Entrypoint: l.Entrypoint(), + NetworkDisabled: false, + MacAddress: "", + OnBuild: nil, + Labels: l.Labels(), + StopSignal: string(l.StopSignal()), + StopTimeout: &stopTimeout, + Shell: nil, + } + + m, err := json.Marshal(inspect.Mounts) + if err != nil { + return nil, err + } + mounts := []docker.MountPoint{} + if err := json.Unmarshal(m, &mounts); err != nil { + return nil, err + } + + networkSettingsDefault := docker.DefaultNetworkSettings{ + EndpointID: "", + Gateway: "", + GlobalIPv6Address: "", + GlobalIPv6PrefixLen: 0, + IPAddress: "", + IPPrefixLen: 0, + IPv6Gateway: "", + MacAddress: l.Config().StaticMAC.String(), + } + + networkSettings := docker.NetworkSettings{ + NetworkSettingsBase: docker.NetworkSettingsBase{}, + DefaultNetworkSettings: networkSettingsDefault, + Networks: nil, + } + + c := docker.ContainerJSON{ + ContainerJSONBase: &cb, + Mounts: mounts, + Config: &config, + NetworkSettings: &networkSettings, + } + return &c, nil +} + +// portsToPortSet converts libpods exposed ports to dockers structs +func portsToPortSet(input map[string]struct{}) (nat.PortSet, error) { + ports := make(nat.PortSet) + for k := range input { + npTCP, err := nat.NewPort("tcp", k) + if err != nil { + return nil, errors.Wrapf(err, "unable to create tcp port from %s", k) + } + npUDP, err := nat.NewPort("udp", k) + if err != nil { + return nil, errors.Wrapf(err, "unable to create udp port from %s", k) + } + ports[npTCP] = struct{}{} + ports[npUDP] = struct{}{} + } + return ports, nil +} -- cgit v1.2.3-54-g00ecf