spiegel_podman/pkg/bindings/play/play.go
Moritz "WanzenBug" Wanzenböck 5df883e87d bindings: reuse context for API requests
One of the main uses of context.Context is to provide cancellation for
go-routines, including API requests. While all user-facing bindings
already used a context parameter, it was only used to pass the client
information around.

This commit changes the internal DoRequest wrapper to take an additional
context argument, and pass that to the http request. Previously, the context
was derived from context.Background(), which made it impossible to cancel
once started.

All the convenience wrappers already supported the context parameter, so the
only user facing change is that cancelling those context now works as one
would expect.

Signed-off-by: Moritz "WanzenBug" Wanzenböck <moritz@wanzenbug.xyz>
2021-11-15 15:42:39 +01:00

86 lines
1.9 KiB
Go

package play
import (
"context"
"net/http"
"os"
"strconv"
"github.com/containers/podman/v3/pkg/auth"
"github.com/containers/podman/v3/pkg/bindings"
"github.com/containers/podman/v3/pkg/domain/entities"
"github.com/sirupsen/logrus"
)
func Kube(ctx context.Context, path string, options *KubeOptions) (*entities.PlayKubeReport, error) {
var report entities.PlayKubeReport
if options == nil {
options = new(KubeOptions)
}
conn, err := bindings.GetClient(ctx)
if err != nil {
return nil, err
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
params, err := options.ToParams()
if err != nil {
return nil, err
}
if options.SkipTLSVerify != nil {
params.Set("tlsVerify", strconv.FormatBool(options.GetSkipTLSVerify()))
}
if options.Start != nil {
params.Set("start", strconv.FormatBool(options.GetStart()))
}
// TODO: have a global system context we can pass around (1st argument)
header, err := auth.Header(nil, auth.XRegistryAuthHeader, options.GetAuthfile(), options.GetUsername(), options.GetPassword())
if err != nil {
return nil, err
}
response, err := conn.DoRequest(ctx, f, http.MethodPost, "/play/kube", params, header)
if err != nil {
return nil, err
}
defer response.Body.Close()
if err := response.Process(&report); err != nil {
return nil, err
}
return &report, nil
}
func KubeDown(ctx context.Context, path string) (*entities.PlayKubeReport, error) {
var report entities.PlayKubeReport
conn, err := bindings.GetClient(ctx)
if err != nil {
return nil, err
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() {
if err := f.Close(); err != nil {
logrus.Warn(err)
}
}()
response, err := conn.DoRequest(ctx, f, http.MethodDelete, "/play/kube", nil, nil)
if err != nil {
return nil, err
}
if err := response.Process(&report); err != nil {
return nil, err
}
return &report, nil
}