Golang - Docker API - Analyze ImagePull Result

I am developing a Goscript that uses Docker APIfor the purposes of my project. After entering my repository, I pull out the Docker image that I want, but the problem is that the ImagePull function returns an io.ReadCloser instance , which I can only transfer to the system output via:

io.Copy(os.Stdout, pullResp)

It's great that I see the answer, but I can’t find a decent way to parse it and implement logic depending on it, which will do some things if a new version of the image is loaded, and other things if the image has been updated.
I will be glad if you share your experience if you have ever encountered this problem.

+4
source share
3 answers

@ radoslav-stoyanov before using my do example

# docker rmi busybox

then run the code

package main

import (
    "encoding/json"
    "fmt"
    "github.com/docker/distribution/context"
    docker "github.com/docker/engine-api/client"
    "github.com/docker/engine-api/types"
    "io"
    "strings"
)

func main() {
    // DOCKER
    cli, err := docker.NewClient("unix:///var/run/docker.sock", "v1.28", nil, map[string]string{"User-Agent": "engine-api-cli-1.0"})
    if err != nil {
        panic(err)
    }

    imageName := "busybox:latest"

    events, err := cli.ImagePull(context.Background(), imageName, types.ImagePullOptions{})
    if err != nil {
        panic(err)
    }

    d := json.NewDecoder(events)

    type Event struct {
        Status         string `json:"status"`
        Error          string `json:"error"`
        Progress       string `json:"progress"`
        ProgressDetail struct {
            Current int `json:"current"`
            Total   int `json:"total"`
        } `json:"progressDetail"`
    }

    var event *Event
    for {
        if err := d.Decode(&event); err != nil {
            if err == io.EOF {
                break
            }

            panic(err)
        }

        fmt.Printf("EVENT: %+v\n", event)
    }

    // Latest event for new image
    // EVENT: {Status:Status: Downloaded newer image for busybox:latest Error: Progress:[==================================================>]  699.2kB/699.2kB ProgressDetail:{Current:699243 Total:699243}}
    // Latest event for up-to-date image
    // EVENT: {Status:Status: Image is up to date for busybox:latest Error: Progress: ProgressDetail:{Current:0 Total:0}}
    if event != nil {
        if strings.Contains(event.Status, fmt.Sprintf("Downloaded newer image for %s", imageName)) {
            // new
            fmt.Println("new")
        }

        if strings.Contains(event.Status, fmt.Sprintf("Image is up to date for %s", imageName)) {
            // up-to-date
            fmt.Println("up-to-date")
        }
    }
}

You can see the API formats for creating your structures (for example, my Event) for reading them here https://docs.docker.com/engine/api/v1.27/#operation/ImageCreate

I hope this helps you solve your problem, thanks.

0
source

github.com/docker/docker/pkg/jsonmessage JSONMessage JSONProgress , DisplayJSONMessagesToStream: . stderr:

    reader, err := cli.ImagePull(ctx, myImageRef, types.ImagePullOptions{})
    if err != nil {
            return err
    }
    defer reader.Close()

    termFd, isTerm := term.GetFdInfo(os.Stderr)
    jsonmessage.DisplayJSONMessagesStream(reader, os.Stderr, termFd, isTerm, nil)

, : , TTY ( docker pull), , .

+1

( ). , . .

:

reader := bufio.NewReader(pullResp)
defer pullResp.Close()  // pullResp is io.ReadCloser
var resp bytes.Buffer
for {
    line, err := reader.ReadBytes('\n')
    if err != nil {
        // it could be EOF or read error
        // handle it
        break
    }
    resp.Write(line)
    resp.WriteByte('\n')
}

// print it
fmt.Println(resp.String())

JSON. json.Decoder - JSON. -

type ImagePullResponse struct {
   ID             string `json"id"`
   Status         string `json:"status"`
   ProgressDetail struct {
     Current int64 `json:"current"`
     Total   int64 `json:"total"`
   } `json:"progressDetail"`
   Progress string `json:"progress"`
}

d := json.NewDecoder(pullResp)
for {
   var pullResult ImagePullResponse
  if err := d.Decode(&pullResult); err != nil {
    // handle the error
    break
  }
  fmt.Println(pullResult)
}
0

Source: https://habr.com/ru/post/1678855/


All Articles