Created
October 23, 2016 21:51
-
-
Save cescoferraro/7b43d3f1c26c13097e7726f9a8f3716f to your computer and use it in GitHub Desktop.
docker & kubernetes client example golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cmd | |
import ( | |
"bitbucket.org/cescoferraro/api/util" | |
"github.com/fatih/color" | |
"github.com/spf13/cobra" | |
) | |
var ( | |
logger = util.Block{ | |
Title: "DOCKER", | |
Color: color.FgRed}.Now() | |
) | |
// dockerCmd represents the docker command | |
var dockerCmd = &cobra.Command{ | |
Use: "docker", | |
Short: "A brief description", | |
Long: `A longer description`, | |
Run: func(cmd *cobra.Command, args []string) { | |
imageName := "cescoferraro/bruninha" | |
tagVersion := "0.1.2" | |
logger.Print("Creating Docker Client...") | |
client := util.DockerClient() | |
logger.Print("Building Docker Image...") | |
client.Build(imageName) | |
logger.Print("Inpecting Docker Image...") | |
client.Inspect(imageName) | |
logger.Print("Tagging Docker Image...") | |
client.Tag(imageName, tagVersion) | |
logger.Print("Pushing Docker Image...") | |
client.Push(imageName, tagVersion) | |
}, | |
} | |
func init() { | |
RootCmd.AddCommand(dockerCmd) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cmd | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"k8s.io/client-go/1.4/kubernetes" | |
"k8s.io/client-go/1.4/pkg/api" | |
"k8s.io/client-go/1.4/pkg/apis/extensions/v1beta1" | |
"k8s.io/client-go/1.4/tools/clientcmd" | |
"github.com/spf13/cobra" | |
) | |
// kubectlCmd represents the kubectl command | |
var kubectlCmd = &cobra.Command{ | |
Use: "kubectl", | |
Short: "A brief description of your command", | |
Long: `A longer description that spans multiple lines and likely contains examples | |
and usage of using your command. For example: | |
Cobra is a CLI library for Go that empowers applications. | |
This application is a tool to generate the needed files | |
to quickly create a Cobra application.`, | |
Run: func(cmd *cobra.Command, args []string) { | |
// TODO: Work your own magic here | |
fmt.Println("kubectl called") | |
kubeconfig := os.Getenv("HOME") + "/.kube/config" | |
// uses the current context in kubeconfig | |
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) | |
if err != nil { | |
panic(err.Error()) | |
} | |
// creates the clientset | |
clientset, err := kubernetes.NewForConfig(config) | |
if err != nil { | |
panic(err.Error()) | |
} | |
// List all pod on iot namespace | |
pods, err := clientset.Core().Pods("iot").List(api.ListOptions{}) | |
if err != nil { | |
panic(err.Error()) | |
} | |
// Delete all pods in iot namespace | |
for _, pod := range pods.Items { | |
fmt.Println(pod.ObjectMeta.Name) | |
err = clientset.Core().Pods("iot").Delete(pod.ObjectMeta.Name, &api.DeleteOptions{}) | |
if err != nil { | |
panic(err.Error()) | |
} | |
} | |
deploySpec := v1beta1.Deployment{} | |
deploy, err := clientset.Extensions().Deployments("iot").Create(&deploySpec) | |
if err != nil { | |
panic(err.Error()) | |
} | |
log.Println(deploy) | |
}, | |
} | |
func init() { | |
RootCmd.AddCommand(kubectlCmd) | |
// Here you will define your flags and configuration settings. | |
// Cobra supports Persistent Flags which will work for this command | |
// and all subcommands, e.g.: | |
// kubectlCmd.PersistentFlags().String("foo", "", "A help for foo") | |
// Cobra supports local flags which will only run when this command | |
// is called directly, e.g.: | |
// kubectlCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util | |
import ( | |
"log" | |
"net/http" | |
"time" | |
"github.com/fatih/color" | |
"sort" | |
"encoding/json" | |
"github.com/spf13/viper" | |
) | |
var UtilLogsColor = color.FgHiYellow | |
var UtilLogsBlock = "UTIL" | |
type Block struct { | |
Title string | |
Color color.Attribute | |
Time time.Time | |
} | |
func (block Block) Now() Block { | |
block.Time = time.Now() | |
return block | |
} | |
func (block Block) Print(message string) { | |
if viper.GetBool("verbose") { | |
red := color.New(block.Color).SprintFunc() | |
msg := "[" + red(block.Title) + "] " + message | |
empty := time.Time{} | |
if block.Time != empty { | |
msg = msg + " " + red("+") + red(time.Since(block.Time)) | |
} | |
log.Println(msg) | |
} | |
} | |
var PackageBlocks = map[string]Block{ | |
"redis": Block{Title: "REDIS", Color: color.FgWhite}, | |
} | |
func LogIfVerbose(cor color.Attribute, block, logg string) { | |
if viper.GetBool("verbose") { | |
red := color.New(cor).SprintFunc() | |
log.Printf("[%s] "+logg, red(block)) | |
} | |
} | |
func RunIfVerbose(logg func()) { | |
if viper.GetBool("verbose") { | |
logg() | |
} | |
} | |
var Ciano = color.New(color.FgCyan).Add(color.Underline) | |
func PanicIf(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} | |
func LogIfError(err error) { | |
if err != nil { | |
log.Println(err) | |
} | |
} | |
func PrintRequestHeaders(r *http.Request) { | |
for k, v := range r.Header { | |
log.Println("key:", k, "value:", v) | |
} | |
} | |
func PrintViperConfig() { | |
// TODO: HANDLE NESTED YAMLS BETTER | |
keys := viper.AllKeys() | |
sort.Strings(keys) | |
for _, key := range keys { | |
if key == "publickey" || key == "privatekey" { | |
LogIfVerbose(color.FgBlue, "VIPER", " "+key+": ******") | |
} else { | |
LogIfVerbose(color.FgBlue, "VIPER", " "+key+": "+viper.GetString(key)) | |
} | |
} | |
return | |
} | |
func Marshall(hey interface{}) string { | |
ola, err := json.Marshal(hey) | |
if err != nil { | |
return "Marsheling failed!" | |
} | |
return string(ola) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
make push | |
docker push cescoferraro/api:v0.0.1 | |
kubectl --namespace=api delete pods -l name=api | |
sleep 6 | |
kubectl --namespace=api logs $(kubectl --namespace=api get pods | awk 'FNR == 2 {print $1}') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package util | |
import ( | |
"bytes" | |
"log" | |
"os" | |
"strings" | |
docker "github.com/fsouza/go-dockerclient" | |
) | |
// Dockeroo embbeds a fsouza/go-dockerclient | |
type Dockeroo struct{ *docker.Client } | |
// DockerClient - Create Docker client | |
func DockerClient() Dockeroo { | |
client, _ := docker.NewClientFromEnv() | |
return Dockeroo{client} | |
} | |
// Build - Build Docker image | |
func (client *Dockeroo) Build(imageName string) { | |
var buf bytes.Buffer | |
here, err := os.Getwd() | |
opts := docker.BuildImageOptions{ | |
Name: imageName, | |
ContextDir: here, | |
OutputStream: &buf, | |
} | |
err = client.BuildImage(opts) | |
if err != nil { | |
log.Println(err.Error()) | |
} | |
// m := strings.Split(buf.String(), "\n") | |
for _, m := range strings.Split(buf.String(), "\n") { | |
log.Printf("metric: %s", m) | |
} | |
} | |
// Tag - Tag Docker image | |
func (client *Dockeroo) Tag(imageName, tagVersion string) { | |
tags := docker.TagImageOptions{ | |
Repo: imageName, | |
Tag: tagVersion, | |
} | |
err := client.TagImage(imageName, tags) | |
if err != nil { | |
log.Println(err.Error()) | |
} | |
} | |
// Inspect - Tag Docker image | |
func (client *Dockeroo) Inspect(imageName string) { | |
image, err := client.InspectImage(imageName) | |
if err != nil { | |
log.Println(err.Error()) | |
} | |
log.Println(image.RepoTags) | |
} | |
// Push - Push Docker image | |
func (client *Dockeroo) Push(imageName, tagVersion string) { | |
pushOpts := docker.PushImageOptions{ | |
Name: imageName, | |
Tag: tagVersion, | |
OutputStream: os.Stdout, | |
} | |
authOpts := docker.AuthConfiguration{ | |
Username: "cescoferraro", | |
Password: "password", | |
Email: "[email protected]", | |
ServerAddress: "registry.hub.docker.io", | |
} | |
err := client.PushImage(pushOpts, authOpts) | |
if err != nil { | |
log.Println(err.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment