package main
import (
"fmt"
"net/http"
"net/http/httputil"
"os"
buildv1client "github.com/openshift/client-go/build/clientset/versioned/typed/build/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/clientcmd"
)
// Tracer implements http.RoundTripper. It prints each request and
// response/error to os.Stderr. WARNING: this may output sensitive information
// including bearer tokens.
type Tracer struct {
http.RoundTripper
}
// RoundTrip calls the nested RoundTripper while printing each request and
// response/error to os.Stderr on either side of the nested call. WARNING: this
// may output sensitive information including bearer tokens.
func (t *Tracer) RoundTrip(req *http.Request) (*http.Response, error) {
// Dump the request to os.Stderr.
b, err := httputil.DumpRequestOut(req, true)
if err != nil {
return nil, err
}
os.Stderr.Write(b)
os.Stderr.Write([]byte{'\n'})
// Call the nested RoundTripper.
resp, err := t.RoundTripper.RoundTrip(req)
// If an error was returned, dump it to os.Stderr.
if err != nil {
fmt.Fprintln(os.Stderr, err)
return resp, err
}
// Dump the response to os.Stderr.
b, err = httputil.DumpResponse(resp, req.URL.Query().Get("watch") != "true")
if err != nil {
return nil, err
}
os.Stderr.Write(b)
os.Stderr.Write([]byte{'\n'})
return resp, err
}
func main() {
// Instantiate loader for kubeconfig file.
kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
clientcmd.NewDefaultClientConfigLoadingRules(),
&clientcmd.ConfigOverrides{},
)
// Determine the namespace referenced by the current context in the
// kubeconfig file.
namespace, _, err := kubeconfig.Namespace()
if err != nil {
panic(err)
}
// Get a rest.Config from the kubeconfig file. This will be passed into all
// the client objects we create.
restconfig, err := kubeconfig.ClientConfig()
if err != nil {
panic(err)
}
// Wrap the default RoundTripper with an instance of Tracer.
restconfig.WrapTransport = func(rt http.RoundTripper) http.RoundTripper {
return &Tracer{rt}
}
// Create a Kubernetes core/v1 client.
coreclient, err := corev1client.NewForConfig(restconfig)
if err != nil {
panic(err)
}
// Create an OpenShift build/v1 client.
buildclient, err := buildv1client.NewForConfig(restconfig)
if err != nil {
panic(err)
}
// List all pods in our current namespace.
pods, err := coreclient.Pods(namespace).List(metav1.ListOptions{})
if err != nil {
panic(err)
}
fmt.Printf("Pods in namespace %s:\n", namespace)
for _, pod := range pods.Items {
fmt.Printf(" %s\n", pod.Name)
}
// List all builds in our current namespace.
builds, err := buildclient.Builds(namespace).List(metav1.ListOptions{})
if err != nil {
panic(err)
}
fmt.Printf("Builds in namespace %s:\n", namespace)
for _, build := range builds.Items {
fmt.Printf(" %s\n", build.Name)
}
}