grafana / xk6-docker

k6 extension for interacting with Docker containers and images from a test script.
Apache License 2.0
15 stars 2 forks source link

Private registries #13

Open diegombeltran opened 2 years ago

diegombeltran commented 2 years ago

Is it possible to pull/push images from/to private registries?

I understand it uses Moby Golang SDK and there is an ImagePullOptions parameter used to "basic-auth", but I struggled for the last few hours and all I get are unauthorized messages.

Here is a small snippet:

import images from 'k6/x/docker/images';
import encoding from 'k6/encoding';

export default function () {
  const registryAuth = encoding.b64encode(JSON.stringify({
    username: 'myUsername',
    password: 'myPassword'
  }), "url")

  const imageName = 'privateRegistry/myImage'
  const imagePullOptions = {
    RegistryAuth: registryAuth
  }

  const result = images.pull(imageName, imagePullOptions)

 console.log(`Image pulling result: ${result}`)
}

Is anything missing?

diegombeltran commented 2 years ago

Hello again,

Just tested with Docker SDK for Golang. It works.

package main

import (
    "context"
    "encoding/base64"
    "encoding/json"
    "io"
    "os"

    "github.com/docker/docker/api/types"
    "github.com/docker/docker/client"
)

func main() {
    ctx := context.Background()
    cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
    if err != nil {
        panic(err)
    }

    authConfig := types.AuthConfig{
        Username: "myUsername",
        Password: "myPassword",
    }
    encodedJSON, err := json.Marshal(authConfig)
    if err != nil {
        panic(err)
    }
    authStr := base64.URLEncoding.EncodeToString(encodedJSON)
    println(authStr)

    out, err := cli.ImagePull(ctx, "myRegistry/myImage", types.ImagePullOptions{RegistryAuth: authStr})
    if err != nil {
        panic(err)
    }

    defer out.Close()
    io.Copy(os.Stdout, out)
}

Base64 authStr is the same as the k6 b64encode output. Looks like imagePullOptions is not right, but I can't debug why.

Any thoughts?

diegombeltran commented 2 years ago

I just found this: https://k6.io/docs/extensions/explanations/go-js-bridge/

_Go field names convert from Pascal to Snake case. For example, the struct field ComparisonResult string becomes comparisonresult in JS.

So the snippet looks like this:

import images from 'k6/x/docker/images';
import encoding from 'k6/encoding';

export default function () {
  const registryAuth = encoding.b64encode(JSON.stringify({
    username: 'myUsername',
    password: 'myPassword'
  }), "url")

  const imageName = 'privateRegistry/myImage'

  const imagePullOptions = {
    registry_auth: registryAuth
  }

  const result = images.pull(imageName, imagePullOptions)

 console.log(`Image pulling result: ${result}`)
}

Working. Just in case someone needs this.