Skip to content

Instantly share code, notes, and snippets.

@jwhonce
Created Sep 15, 2021
Embed
What would you like to do?
package main
import (
"context"
"fmt"
"math/rand"
"os"
"os/user"
"sync"
"time"
"github.com/containers/podman/v3/libpod/define"
"github.com/containers/podman/v3/pkg/bindings"
"github.com/containers/podman/v3/pkg/bindings/containers"
"github.com/containers/podman/v3/pkg/bindings/images"
"github.com/containers/podman/v3/pkg/domain/entities"
"github.com/containers/podman/v3/pkg/specgen"
"github.com/sirupsen/logrus"
)
func main() {
rand.Seed(time.Now().UnixNano())
logrus.SetLevel(logrus.WarnLevel)
current, err := user.Current()
if err != nil {
panic(err)
}
uri := fmt.Sprintf("unix://run/user/%s/podman/podman.sock", current.Uid)
conn, err := bindings.NewConnection(context.Background(), uri)
if err != nil {
panic(err)
}
if _, err := images.Pull(conn, "quay.io/libpod/busybox", nil); err != nil {
panic(err)
}
spec := specgen.NewSpecGenerator("quay.io/libpod/busybox", false)
spec.Command = []string{"/bin/true"}
var waitGroup sync.WaitGroup
for i := 1; i <= 5; i++ {
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
spec.Name = "busybox_" + RandomID()
ctnr, err := containers.CreateWithSpec(conn, spec, nil)
if err != nil {
panic(err)
}
fmt.Println("ID", spec.Name, ctnr.ID)
if err := containers.Start(conn, ctnr.ID, nil); err != nil {
panic(err)
}
state := new(containers.WaitOptions).
WithCondition([]define.ContainerStatus{define.ContainerStateExited}).
WithInterval("5s")
if _, err := containers.Wait(conn, ctnr.ID, state); err != nil {
panic(err)
}
}()
}
waitGroup.Wait()
List(conn)
return
}
func List(conn context.Context) {
ctnrs, err := containers.List(conn, nil)
if err != nil {
panic(err)
}
for _, c := range ctnrs {
fmt.Println("Ctnr ID", c.ID)
}
return
}
func Build(conn context.Context) {
options := entities.BuildOptions{}
options.ContextDirectory = "./fixtures"
options.Registry = "quay.io"
options.Out = os.Stdout
options.Err = os.Stderr
options.ReportWriter = os.Stdout
report, err := images.Build(conn, []string{"Containerfile"}, options)
if err != nil {
panic(err)
}
fmt.Println(report.ID)
return
}
func RandomID() string {
n := 16
b := make([]byte, n)
rand.Read(b)
return fmt.Sprintf("%x", b)[:n]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment