<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Diego Garcia on Medium]]></title>
        <description><![CDATA[Stories by Diego Garcia on Medium]]></description>
        <link>https://medium.com/@drgarcia1986?source=rss-c1ee4d001ed6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*COV0N5C6i1ggCvo9Xz7MWg.jpeg</url>
            <title>Stories by Diego Garcia on Medium</title>
            <link>https://medium.com/@drgarcia1986?source=rss-c1ee4d001ed6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:22:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@drgarcia1986/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Changelogger]]></title>
            <link>https://drgarcia1986.medium.com/changelogger-5298b032b69b?source=rss-c1ee4d001ed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5298b032b69b</guid>
            <category><![CDATA[town-criers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[changelogger]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[changelog]]></category>
            <dc:creator><![CDATA[Diego Garcia]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 22:38:43 GMT</pubDate>
            <atom:updated>2021-06-02T22:40:23.963Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Originally published on <a href="https://dgarcia.dev/changelogger/">https://dgarcia.dev/changelogger/</a></blockquote><p>I started a project called changelogger. This project is a very simplified version of <a href="https://github.com/twisted/towncrier">Towncrier</a> but written in Go.</p><p>I can already hear you say: <strong>Why?</strong>. Well, Golang isn’t the main goal here, but the fact that I can distribute this tool as a binary without care about the developer environment. There’s no problem with Python (to tell the truth, Python has been paying my bills for ten years) but, I wouldn’t like to force a <em>Golang/JavaScript/Java/[put here your favorite lang]</em> dev to setup a python environment only to use a simple tool.</p><p>I used towncrier in my last python projects and I just love how the tool helps me to keep my changelog updated without git conflicts, so I want to continue to use it (or some similarly tool).</p><p>That’s how changelogger was born, with only limited features that I’m used to using in towncrier.</p><p>Check <a href="https://github.com/drgarcia1986/changelogger">the repository</a>, get the binary on <a href="https://github.com/drgarcia1986/changelogger/releases/tag/v0.0.1">release page</a> or install from the source with go get github.com/drgarcia1986/changelogger.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5298b032b69b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming Kubernetes — Running Pods]]></title>
            <link>https://drgarcia1986.medium.com/programming-kubernetes-running-pods-e2b1680b5d21?source=rss-c1ee4d001ed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2b1680b5d21</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Diego Garcia]]></dc:creator>
            <pubDate>Tue, 18 May 2021 22:20:49 GMT</pubDate>
            <atom:updated>2021-05-18T22:20:49.855Z</atom:updated>
            <content:encoded><![CDATA[<h3>Programming Kubernetes — Running Pods</h3><blockquote>Originally published on <a href="https://dgarcia.dev/programming-kubernetes-running-pods/">https://dgarcia.dev/programming-kubernetes-running-pods/</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RzcmRwc_WT_FFL2s.png" /></figure><p>This is the first post of a series I want to publish about interact with the Kubernetes programmatic instead of using kubectl for example. In this first post, we’ll create an API that runs an individual pod and returns the exit code with the stdout of the execution, something like that:</p><pre>$ curl -i -d \<br>    &#39;{&quot;image&quot;: &quot;python:3.7.0&quot;, &quot;command&quot;: &quot;python&quot;,\<br>    &quot;args&quot;: [&quot;-c&quot;, &quot;print(\&quot;Hello World\&quot;)&quot;]}&#39;\<br>    http://api-endpoint/<br><br>HTTP/1.1 200 OK<br>Content-Length: 41<br>Content-Type: application/json; charset=utf-8<br><br>{&quot;exit_code&quot;: 0, &quot;output&quot;: &quot;Hello World\n&quot;}</pre><p>Explaining the request payload:</p><ul><li><strong>image</strong>: the container image.</li><li><strong>command</strong>: main command the container will execute.</li><li><strong>args</strong>: the command arguments.</li></ul><p>And the response payload:</p><ul><li><strong>exit code</strong>: the container exit code.</li><li><strong>output</strong>: the stdout of container</li></ul><h3>The Stack</h3><p>We will use Golang with <a href="https://github.com/kubernetes/client-go">client-go</a> library to do that. But why? First of all, Kubernetes is written in Go and the <em>client-go</em> is the official library used on Kubernetes ecosystem, so, there’s no reason to use another library or consuming api-server via REST requests, but, if you hate Golang, there’re other options, like <a href="https://github.com/kubernetes-client/python">client-python</a> for example. Also, I’m using minikube with Kubernetes 1.18, but, feel free to choose your Kubernetes installation.</p><h3>Code snippets</h3><p>All the snippets on this post are simplified to archive better readability but don’t be angry, all codes are available <a href="https://github.com/drgarcia1986/drgarcia1986.github.io/tree/samples/programming-kubernetes-running-pods">here</a>.</p><h3>Adding the Kubernetes Client</h3><p>Let’s prepare our environment to talk to Kubernetes API, starting by add <em>client-go</em> library. Assuming you start this project by running the go mod init command, you can run go get k8s.io/client-go@latest on the same directory of the go.mod file to get the last version of the library.</p><p>After that let’s create an ultra simple Golang code that lists the Kubernetes cluster namespaces (just to validate the communication with the api-server).</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;fmt&quot;<br><br>    metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;<br>    &quot;k8s.io/client-go/kubernetes&quot;<br>    &quot;k8s.io/client-go/tools/clientcmd&quot;<br>    &quot;k8s.io/client-go/util/homedir&quot;<br>)<br><br>func main() {<br>    cfg, err := clientcmd.BuildConfigFromFlags(<br>        &quot;&quot;,<br>        filepath.Join(homedir.HomeDir(), &quot;.kube&quot;, &quot;config&quot;),<br>    )<br>    checkErr(err)<br><br>    k8s, err := kubernetes.NewForConfig(cfg)<br>    checkErr(err)<br><br>    nsList, err := k8s.CoreV1().<br>        Namespaces().<br>        List(context.Background(), metav1.ListOptions{})<br>    checkErr(err)<br><br>    for _, n := range nsList.Items {<br>    	fmt.Println(n.Name)<br>    }<br>}</pre><p>Before you run this code, don’t forget to run go mod tidy to normalize dependencies on the go.mod file.</p><p>And, the magic happens:</p><pre>$ go run main.go<br>default<br>kube-node-lease<br>kube-public<br>kube-system</pre><p>Let’s take a look at the important parts of that code:</p><ul><li>clientcmd.BuildConfigFromFlags(...): We take the Kubernetes access configuration from the ~/.kube/config yaml file (the same as the kubectl use).</li><li>kubernetes.NewForConfig(...): We create a new k8s client based on the previous configuration.</li><li>k8s.CoreV1().Namespaces().List(...): And finally, we perform a query on Kubernetes API (same as kubectl get ns).</li></ul><p>A note here, we’re consuming the Kubernetes API outside the cluster, later on, in a new blog post, we’ll deploy an application inside the Kubernetes with a <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/">service-account</a>. When we do that, we don’t need to inform where’s the config yaml file.</p><h3>Creating and Running Pod</h3><p>Now things start to get excited. We’ll create a pod manifest just as you would a yaml, but programmatic.</p><pre>pod := &amp;v1.Pod{<br>    ObjectMeta: metav1.ObjectMeta{Name: &quot;rtw&quot;},<br>    Spec: v1.PodSpec{<br>        RestartPolicy: v1.RestartPolicyNever,<br>        Containers: []v1.Container{<br>            v1.Container{<br>                Name:    &quot;main&quot;,<br>                Image:   &quot;python:3.8&quot;,<br>                Command: []string{&quot;python&quot;},<br>                Args:    []string{&quot;-c&quot;, &quot;print(&#39;hello world&#39;)&quot;},<br>            },<br>        },<br>    },<br>}</pre><p>And use the Kubernetes client we created before to create the pod on the cluster:</p><pre>_, err = k8s.CoreV1().Pods(&quot;default&quot;).Create(<br>    context.Background(),<br>    pod,<br>    metav1.CreateOptions{},<br>)</pre><p>That’s it! If you run this code, you’ll be able to see a beautifully hello world coming from our python container:</p><pre>$ kubectl get pods<br>NAME   READY   STATUS      RESTARTS   AGE<br>rtw    0/1     Completed   0          3s<br><br>$ kubectl logs rtw main<br>hello world</pre><h3>Getting Exit Code</h3><p>To get the container exit code there’s no magic or beautiful path, we need to polling Kubernetes API until the container execution terminates. Luckily we can use the helper PollImmediate from apimachinery to perform the polling with backoff and timeout.</p><pre>import (<br>    &quot;context&quot;<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br><br>    metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;<br>    &quot;k8s.io/apimachinery/pkg/util/wait&quot;<br>)<br><br>...<br><br>var exitCode int32<br>cli := k8s.CoreV1().Pods(&quot;default&quot;)<br>err := wait.PollImmediate(3*time.Second, 2*time.Minute, func() (bool, error) {<br>    p, err := cli.Get(context.Background(), &quot;rtw&quot;, metav1.GetOptions{})<br>    if err != nil {<br>        return false, err<br>    }<br>    if len(p.Status.ContainerStatuses) == 0 {<br>        return false, nil<br>    }<br>    state := p.Status.ContainerStatuses[0].State<br>    if state.Terminated != nil {<br>        exitCode = state.Terminated.ExitCode<br>        return true, nil<br>    }<br>    return false, nil<br>})<br>checkErr(err)<br>fmt.Printf(&quot;Container Exit Code: %d\n&quot;, exitCode)</pre><p><em>PollImmediate</em> will execute our anonymous function until return true, or an error, or reach the timeout (second arg).</p><p>So, what’s happening here? We’re getting pod information looking for the status of the main container (we created that pod with only one container). When Kubernetes API returns the status of the container, we check if the container is terminated, if yes, we get the exit code of it.</p><pre>Container Exit Code: 0</pre><h3>Getting StdOut</h3><p>OK, we already know the container exit code, now it’s time to get the stdout, to do that, we’ll get the logs from the container.</p><pre>stdout, err := k8s.CoreV1().<br>    Pods(&quot;default&quot;).<br>    GetLogs(&quot;rtw&quot;, &amp;v1.PodLogOptions{}).<br>    Do(context.Background()).<br>    Raw()<br><br>checkErr(err)<br>fmt.Println(string(stdout))</pre><p>Easy, right? The code above works as same as kubectl logs:</p><pre>$ kubectl logs rtw main<br>hello world</pre><h3>Deleting the Pod</h3><p>We have all we need to build our API, but before we move, don’t forget to delete the pod as we’ll no longer need it.</p><pre>err := k8s.CoreV1().<br>    Pods(&quot;default&quot;).<br>    Delete(<br>        context.Background(),<br>        &quot;rtw&quot;,<br>        metav1.DeleteOptions{},<br>    )<br><br>checkErr(err)</pre><p>Done, the code above works as same as kubectl delete pod rtw.</p><h3>Put all the things together</h3><p>Now is time to put all the things together in our HTTP Server, starting by the request and response payload:</p><pre>type RequestBody struct {<br>    Image   string   `json:&quot;image&quot;`<br>    Command string   `json:&quot;command&quot;`<br>    Args    []string `json:&quot;args&quot;`<br>}<br><br>type ResponseBody struct {<br>    ExitCode int32  `json:&quot;exit_code&quot;`<br>    Output   string `json:&quot;output&quot;`<br>}</pre><p>Good, now assuming we created a struct to represent the Kubernetes client with all method we created before, we end up with something like that:</p><pre>type Client struct {<br>    k8s kubernetes.Interface<br>    ns  string // The default namespace we&#39;ll work<br>}<br><br>func (c *Client) CreatePod(ctx context.Context, name, image, command string, args []string) error {<br>...<br>}<br><br>func (c *Client) GetPodExitCode(ctx context.Context, name string) (int32, error) {<br>...<br>}<br><br>func (c *Client) GetPodStdOut(ctx context.Context, name string) (string, error) {<br>...<br>}<br><br>func (c *Client) DeletePod(ctx context.Context, name string) error {<br>...<br>}<br><br>func NewClient(namespace string) (*Client, error) {<br>    // logic to create the k8s client<br>    return &amp;Client{k8s: k8s, ns: namespace}, nil<br>}</pre><p>The last piece of code is the HTTP handler:</p><pre>http.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {<br>    var rb RequestBody<br>    if err := json.NewDecoder(r.Body).Decode(&amp;rb); err != nil {<br>        http.Error(w, err.Error(), http.StatusBadRequest)<br>        return<br>    }<br>    err := cli.CreatePod(<br>        ctx,<br>        &quot;rtw&quot;,<br>        rb.Image,<br>        rb.Command,<br>        rb.Args,<br>    )<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusInternalServerError)<br>        return<br>    }<br>    exitCode, err := cli.GetPodExitCode(ctx, &quot;rtw&quot;)<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusInternalServerError)<br>        return<br>    }<br>    stdout, err := cli.GetPodStdOut(ctx, &quot;rtw&quot;)<br>    if err != nil {<br>        http.Error(w, err.Error(), http.StatusInternalServerError)<br>        return<br>    }<br>    go func() {<br>        if err := cli.DeletePod(ctx, &quot;rtw&quot;); err != nil {<br>            log.Printf(&quot;Error deleting pod: %v&quot;, err)<br>        }<br>    }()<br>    w.Header().Set(&quot;Content-type&quot;, &quot;application/json&quot;)<br>    w.WriteHeader(http.StatusOK)<br>    json.NewEncoder(w).Encode(<br>        ResponseBody{ExitCode: exitCode, Output: stdout},<br>    )<br>})</pre><p>Finally, put all the things together, our main function looks like:</p><pre>func main() {<br>    cli, err := NewClient(&quot;default&quot;)<br>    if err != nil {<br>        panic(err)<br>    }<br>    ctx := context.Background()<br><br>    http.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {<br>       // The HTTP Handler<br>    })<br>    log.Println(&quot;Starting HTTP Server&quot;)<br>    http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><p>It’s done, we finally have an API that creates a Kubernetes Pod, and returns the exit code and the stdout of the container executed inside the pod:</p><pre>$  go run main.go &amp;<br>[1] 25538<br>2021/05/15 19:28:27 Starting HTTP Server<br><br>$ curl -i localhost:8080 -d &#39;{&quot;image&quot;: &quot;python:3.8&quot;, &quot;command&quot;: &quot;python&quot;, &quot;args&quot;: [&quot;-c&quot;, &quot;print(\&quot;hello world\&quot;)&quot;]}&#39;<br>HTTP/1.1 200 OK<br>Content-Type: application/json<br>Date: Sat, 15 May 2021 22:28:33 GMT<br>Content-Length: 41<br><br>{&quot;exit_code&quot;:0,&quot;output&quot;:&quot;hello world\n&quot;}</pre><h3>Conclusion</h3><p>Consuming the Kubernetes API is easy and adds the maximum power over Kubernetes integrations. If you want to use Kubernetes most complete and sustainable way, there’s no easy path to do that without some code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2b1680b5d21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with Go and Generics]]></title>
            <link>https://drgarcia1986.medium.com/playing-with-go-and-generics-bba6961b14a0?source=rss-c1ee4d001ed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba6961b14a0</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Diego Garcia]]></dc:creator>
            <pubDate>Mon, 12 Apr 2021 22:42:21 GMT</pubDate>
            <atom:updated>2021-05-04T13:49:58.303Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Originally published on <a href="https://dgarcia.dev/playing-with-go-and-generics/">https://dgarcia.dev/playing-with-go-and-generics/</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yrCvWF5ZvhVr8m80Payxfg.jpeg" /></figure><p>Yes, it’s happening! The <a href="https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md">proposal to add generics</a> to Golang was <a href="https://github.com/golang/go/issues/43651#issuecomment-776944155">accepted</a>. It means that in some versions in the future, we’ll be able to code generic solutions without having to use complex workarounds with the empty interface{}. But, how it works?</p><p><strong>TLDR</strong>: Now there’s a <em>type parameter</em> described with square brackets to define generics types for structs, functions, etc. For instance:</p><pre>func Print[T any](s []T) {<br>	for _, v := range s {<br>		fmt.Print(v)<br>	}<br>}</pre><p><em>The identifier </em><em>any means that the type </em><em>T can be any type</em></p><p>With the previous notation we can use a slice of any type in an explicit way:</p><pre>func main() {<br>	Print([]string{&quot;Hello, &quot;, &quot;World\n&quot;})<br>	Print([]int{4, 2})<br>}</pre><p>And will work like a charm:</p><pre>Hello, World<br>42</pre><p>Let’s take a look at some classics data structures implemented in go with generics.</p><h4>Queue</h4><p>We can start with a simple <em>queue</em> implementation:</p><pre>type Queue[T any] []T<br><br>func (q *Queue[T]) enqueue(v T) {<br>	*q = append(*q, v)<br>}<br><br>func (q *Queue[T]) dequeue() (T, bool) {<br>	if len(*q) == 0 {<br>		var v T<br>		return v, false<br>	}<br>	v := (*q)[0]<br>	*q = (*q)[1:]<br>	return v, true<br>}</pre><p>When we testing the <em>generic queue</em> with string type:</p><pre>func main() {<br>	q := new(Queue[string])<br>	q.enqueue(&quot;item-1&quot;)<br>	q.enqueue(&quot;item-2&quot;)<br>	q.enqueue(&quot;item-3&quot;)<br>	fmt.Println(q)<br>	fmt.Println(q.dequeue())<br>	fmt.Println(q.dequeue())<br>	fmt.Println(q)<br>}</pre><p>We got the following output:</p><pre>&amp;[reg-1 reg-2 reg-3]<br>reg-1 true<br>reg-2 true<br>&amp;[reg-3]</pre><h4>Stack</h4><p>If we try a <em>Stack</em>?:</p><pre>type Stack[T any] []T<br><br>func (s *Stack[T]) push(v T) {<br>	*s = append([]T{v}, (*s)...)<br>}<br><br>func (s *Stack[T]) pop() (T, bool) {<br>	if len(*s) == 0 {<br>		var v T<br>		return v, false<br>	}<br>	v := (*s)[0]<br>	*s = (*s)[1:]<br>	return v, true<br>}</pre><p>What about test using int?:</p><pre>func main() {<br>	s := new(Stack[int])<br>	s.push(1)<br>	s.push(2)<br>	s.push(3)<br>	fmt.Println(s)<br>	fmt.Println(s.pop())<br>	fmt.Println(s.pop())<br>	fmt.Println(s)<br>}</pre><p>No big deal:</p><pre>&amp;[3 2 1]<br>3 true<br>2 true<br>&amp;[1]</pre><h4>Linked List</h4><p>Maybe a <em>Linked List</em>:</p><pre>type Node[T any] struct {<br>	data T<br>	next *Node[T]<br>}<br><br>type LinkedList[T any] struct {<br>	head *Node[T]<br>}<br><br>func (l *LinkedList[T]) add(data T) {<br>	node := &amp;Node[T]{data: data}<br>	if l.head == nil {<br>		l.head = node<br>		return<br>	}<br>	current := l.head<br>	for current.next != nil {<br>		current = current.next<br>	}<br>	current.next = node<br>}<br><br>func (l *LinkedList[T]) print() {<br>	current := l.head<br>	for current != nil {<br>		fmt.Println(current.data)<br>		current = current.next<br>	}<br>}</pre><p>A bit more of code I agree but there’s no secrets:</p><pre>func main() {<br>	ll := new(LinkedList[float32])<br>	ll.add(1.01)<br>	ll.add(2.02)<br>	ll.add(3.03)<br>	ll.print()<br>}</pre><p>Everything works as expected:</p><pre>1.01<br>2.02<br>3.03</pre><p>It looks a little strange on the first try, but I can get used to it.</p><h4>A more restrictive example</h4><p>We can define a more restrictive set of types that a generic type can use.</p><pre>type Number interface {<br>	type int, float32<br>}<br><br>func sum[T Number](a, b T) T {<br>	return a + b<br>}</pre><p>For int and float32 that function works fine:</p><pre>func main() {<br>	fmt.Println(sum(10, 30))<br>	fmt.Println(sum[float32](1.5, 4.2))<br>}</pre><p>But if we try with strings for example, the code won’t compile:</p><pre>string does not satisfy Number (string or string not found in int, float32)</pre><h4>Try It Yourself!</h4><p>You can play with generics in go by yourself by <a href="https://go.googlesource.com/go/+/refs/heads/dev.go2go/README.go2go.md">build from the source</a> or in <a href="https://go2goplay.golang.org/">The Go2Go Playground</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba6961b14a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Personal Activity Tracker]]></title>
            <link>https://drgarcia1986.medium.com/building-a-personal-activity-tracker-e0f0882b456?source=rss-c1ee4d001ed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0f0882b456</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[influxdb]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Diego Garcia]]></dc:creator>
            <pubDate>Sat, 10 Apr 2021 01:12:16 GMT</pubDate>
            <atom:updated>2021-04-13T20:31:36.607Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Originally published on <a href="https://dgarcia.dev/building-a-personal-activity-tracker/">https://dgarcia.dev/building-a-personal-activity-tracker/</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XHPJhiK6kDBf6H2d.png" /></figure><blockquote><strong>Disclaimer</strong>: This project/post is inspired on <a href="http://lucapette.me/building-an-activity-tracker-with-go-grafana-and-influxdb">Building an activity tracker with Go, Grafana, and InfluxDB</a> by <a href="https://twitter.com/lucapette">lucapette</a>, so there’re many common points and strategies.</blockquote><p>If you’re reading this in 2021 you’re living the <a href="https://www.who.int/health-topics/coronavirus">Coronavirus Pandemic Era</a> and you’re most likely working from home. Well, I’m working from home too with my fiance and my daughter (and two cats). I’m a software engineer who works in a big retail company and this kind of job is very intense. To archive a good work/life balance, I try to do a great focused job on my working hours, but when it’s time to rest I stop any job or study activity to give total attention to my family. I don’t know how you handle it but for my is a bit tricky to get focused working from home with my family, so I’m trying so hard to get rid of procrastination. To help me with this challenge I decided to build a simple activity tracker that monitoring my activities and give them a score based on some simple rules:</p><ul><li><strong>Work</strong>: 1 point</li><li><strong>Social</strong>: 0 point</li><li><strong>Game</strong>: -1 point</li></ul><p>Don’t get me wrong, there’s no problem with gaming and using social apps, but when I’m working I need to use my time with wisdom.</p><h4>How I built this?</h4><p>The first POC was built for Ubuntu environment so there’re some components to get all the project up and running:</p><ul><li>InfluxDB to keep the time series data.</li><li>A Shell script to get the current X window activity and send it to API.</li><li>A Go API to receive activity events, treat the data, and save on InfluxDB.</li><li>Grafana to show activities dashboard.</li></ul><p>Just for fun, I deployed every component (except the shell script) on an old Raspberry Pi 1 running <a href="https://dietpi.com/">DietPi</a> distro.</p><h4>Maybe you’re thinking, “Why”?</h4><p>It’s ok if you’re thinking about my decisions but I’ll try to explain some points.</p><h4>Why deploy it on a Raspberry Pi?</h4><p>The first (and maybe the main) reason is I had an old Raspberry Pi 1 saved for nothing so I decided to use it. The second reason is I’m working mostly with a Macbook but I study with an Ubuntu and I tried to create a solution that works in both scenarios.</p><h4>Why Golang?</h4><p>It’s simple, as long I decided to ship the solution on a Raspberry Pi, Golang fits very well to produce a binary that runs on the Raspberry Pi without any virtual machine or system dependency. Also, the Golang compiler is awesome, I didn’t have any problem compiling to Raspberry Pi (and I love to write Golang code).</p><h4>The Shell Script</h4><p>Let’s talk about the shell script. As I said before, I’m using Ubuntu with Gnome, so I can use the <a href="https://linux.die.net/man/1/xprop">xprop</a> utility to get some information about the focused window of the X server. The usage of <em>xprop</em> utility is simple, f.ex:</p><pre>$ xprop -root _NET_ACTIVE_WINDOW<br>_NET_ACTIVE_WINDOW(WINDOW): window id # 0x3c0000a</pre><p>The important thing on that output is the window id <strong>0x3c0000a</strong>. With that id we can dig through the window information, f.ex:</p><pre>$ xprop -id 0x3c0000a WM_CLASS<br>WM_CLASS(STRING) = &quot;gnome-terminal-server&quot;, &quot;Gnome-terminal&quot;</pre><p>As you can see, now we have the name of the focused window, but we still need to know the title of the window to specify what we’re doing in that application. In the previous command we asked for <em>the class</em> of the window <em>0x3c0000a</em> however we can ask for the <em>name</em> of the window (or title), f.ex:</p><pre>$ xprop -id 0x3c0000a WM_NAME<br>WM_NAME(STRING) = &quot;default - zsh&quot;</pre><p>I’m using Tmux with ZSH while I write this blog post, so the <strong>default</strong> is the name of my Tmux session, and the <strong>zsh</strong> is the currently running application on the <em>gnome-terminal-server</em>. Now that we have all the information we need, we can send it somewhere with <em>curl</em>.</p><pre>$ curl -v -H &quot;Content-Type: application/json&quot; -d \<br>    &quot;{\&quot;class\&quot;: \&quot;$window_class\&quot;, \&quot;title\&quot;: \&quot;$window_title\&quot;}&quot; \<br>    $ENDPOINT</pre><h4>The Go API</h4><p>This is our <em>business logic layer</em>, in this API we interpret the data from the collector shell script and persist it into InfluxDB. But, don’t be scared, this is a very simple (maybe a naive) API made only with the Golang standard library. There’re three main functions on that API to solve our problem:</p><ol><li>A HTTP handler to receive the collector’s requests.</li><li>A transformation layer to convert incoming data into the score rules.</li><li>A InfluxDB <em>write-only</em> client.</li></ol><p>A simplified version of the handle contains less than 15 LOC:</p><pre>func (s *Server) track(w http.ResponseWriter, r *http.Request) {<br>	var d requestData<br>	if err := json.NewDecoder(r.Body).Decode(&amp;d); err != nil {<br>            // error handling for a &quot;Bad Request&quot;<br>	}<br>	if err := s.client.Write(d.Class, d.Title); err != nil {<br>            // error handling data processing and saving data on influxdb<br>	}<br>	w.WriteHeader(http.StatusNoContent)<br>}</pre><p>The client is our InfluxDB client. Before we getting through the InfluxDB client let’s take a look at the transformation layer (that’s the ugly layer of this API).</p><pre>func convertToMetric(class, title string) metric {<br>	switch class {<br>	case &quot;gnome-terminal-server&quot;:<br>		return metric{<br>			category: WORK_CATEGORY,<br>			app:      convertTerminalAppName(title),<br>		}<br>	case &quot;Navigator&quot;:<br>		return metric{<br>			category: convertBrowserCategory(title),<br>			app:      &quot;FireFox&quot;,<br>		}<br>	case &quot;telegram&quot;:<br>		return metric{<br>			category: SOCIAL_CATEGORY,<br>			app:      class,<br>		}<br>	case &quot;Steam&quot;:<br>		return metric{<br>			category: GAME_CATEGORY,<br>			app:      &quot;Steam&quot;,<br>		}<br>	default:<br>		return metric{category: UNKNOWN_CATEGORY, app: title}<br>	}<br>}</pre><p>Every rule of the project is described above, for example, if the collector sends a request like this:</p><pre>{&quot;class&quot;: &quot;gnome-terminal-server&quot;, &quot;title&quot;: &quot;default - vim&quot;}</pre><p>The converter will return a metric with the WORK_CATEGORY:</p><pre>metric{<br>    category: category{name: &quot;work&quot;, score: 1},<br>    app     : &quot;vim&quot;,<br>}</pre><p>There’re other rules like verify if the current tab focused on the browser is a social site or not but, you get the idea. So, back to the InfluxDB client, actually the InfluxDB has a friendly REST API and because of that I decided to avoid big dependencies and solve the persistence layer with a simple <em>HTTP POST</em>:</p><pre>func (c *Client) Write(class, title string) error {<br>	resp, err := http.Post(<br>		fmt.Sprintf(&quot;%s/write?db=%s&quot;, c.endpoint, c.database),<br>		&quot;&quot;,<br>		buildPayload(class, title),<br>	)<br>	if err != nil {<br>		return err<br>	}<br>	if resp.StatusCode != http.StatusNoContent {<br>            // boring error handling<br>	}<br>	return nil<br>}</pre><p>Yeah, simple as pie. If you’re curious about the payload, here’s an example:</p><pre>productivity,category=&quot;work&quot;,app=&quot;vim&quot; value=1</pre><p>The last thing I want to share about the Go API is the compilation step. I deployed that API on a Raspberry Pi 1 and according to <a href="https://github.com/golang/go/wiki/GoArm">Golang Wiki</a>, to compile to <em>ARMv6</em> CPU architecture we need to pass the environment variable GOARM=6 on the build command (and the env GOARCH=arm too).</p><pre>$ GOARCH=arm GOARM=6 go build</pre><h4>InfluxDB</h4><p>There’re no tricks to get InfluxDB up and running on the Raspberry Pi, the straightforward apt install influxdb solves the problem. After the installation process, I created the database and set the <em>retention policy</em> to keep only one week of data (it’s enough for what I’m looking for).</p><pre>$ influx<br>Connected to http://localhost:8086 version 1.8.4<br>InfluxDB shell version: 1.8.4<br>&gt; CREATE DATABASE productivity<br>&gt; USE productivity<br>&gt; CREATE RETENTION POLICY &quot;1week&quot; on &quot;productivity&quot; DURATION 7d REPLICATION 1</pre><h4>Grafana</h4><p>However to install Grafana on the Raspberry Pi 1 there’s a trick, the default version of Grafana’s Debian package is built for the <em>ARMv7</em> architecture (its means that a simple apt install grafana doesn’t work), but the DietPi has the dietpi-software application that enables you to select an optimized installation of some software for the Raspberry Pi with DietPi OS. So I just installed Grafana from that and everything works well. As long the Grafana and the InfluxDB are up and running I created the InfluxDB data source on the Grafana and start “to draw” the dashboard.</p><h4>All Activities Panel</h4><p>For the <em>All Activities Panel</em> I used a graph visualization with bars as display option and the following query:</p><pre>SELECT count(&quot;value&quot;) as minutes FROM &quot;productivity&quot; WHERE $timeFilter GROUP BY time(1h),category</pre><h4>Score Panel</h4><p>The <em>Score</em> panel is a gauger that calculates the <em>mean</em> of the following query:</p><pre>SELECT mean(&quot;value&quot;) * 100 FROM &quot;productivity&quot; WHERE $timeFilter GROUP BY time($interval) fill(null)</pre><p>I multiplied to 100 to get the gauger working like a “percentage”.</p><h4>App Details Panel</h4><p><em>App Details</em> panel shows the name of apps with the time spending with them. It’s a table panel and I’m using the following query:</p><pre>SELECT count(&quot;value&quot;) FROM &quot;productivity&quot; WHERE $timeFilter GROUP BY time($interval), app fill(null)</pre><h4>Top Unknown</h4><p>And the last one is the <em>top unknown</em> panel, a panel to show the apps that are still uncategorized</p><pre>SELECT count(value) FROM &quot;productivity&quot; WHERE $timeFilter and category = &#39;&quot;unknown&quot;&#39; GROUP BY app</pre><h4>Turning the Go API into a Linux service</h4><p>To keep the Go API up and running I created a systemd service. To do that I created a file named productivity.service on directory /etc/systemd/system/ with this content:</p><pre>[Unit]<br>Description=The Productivity Tracker API<br><br>[Service]<br>User=tracker<br>WorkingDirectory=/home/tracker/app<br>ExecStart=/home/tracker/app/productivity<br>Restart=always<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>After that, I added the service and started it</p><pre>$ systemctl enable productivity.service<br>$ systemctl start productivity.service</pre><h4>The Source Code</h4><p>I pushed everything of this POC to a <a href="https://github.com/drgarcia1986/drgarcia1986.github.io/tree/samples/building-a-personal-activity-tracker">Github repo</a> but if you want to use it, you’ll need to do some changes (this project was made to help me with my productivity and to have some fun). I know it’s weird but I named this project as <a href="https://vikings.fandom.com/wiki/Floki">Floki</a>, I thought Floki is a better name than <em>productivity</em> or <em>tracker</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0f0882b456" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como aceleramos a adoção do Kubernetes em larga escala]]></title>
            <link>https://medium.com/luizalabs/como-aceleramos-a-ado%C3%A7%C3%A3o-do-kubernetes-em-larga-escala-5ea0e6b71cf8?source=rss-c1ee4d001ed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ea0e6b71cf8</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[código]]></category>
            <category><![CDATA[paas]]></category>
            <dc:creator><![CDATA[Diego Garcia]]></dc:creator>
            <pubDate>Mon, 12 Mar 2018 14:19:50 GMT</pubDate>
            <atom:updated>2018-07-19T16:04:09.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFiG64aF-AjW8HblDQiU-Q.jpeg" /><figcaption>fonte: Google Images</figcaption></figure><p>Se você não estava preso em uma cabana no meio da floresta totalmente isolado do mundo, com certeza já deve ter ouvido falar sobre o <a href="http://kubernetes.io/">Kubernetes</a>, caso ainda não tenha ouvido falar, o Kubernetes (também conhecido como k8s) segundo o site oficial.</p><blockquote>É um sistema open source para deployments automatizados, scaling e gerenciamento de aplicações conteinerizadas</blockquote><p>Se você ainda não teve a oportunidades de conhecer esse projeto fantástico, pause a leitura desse artigo e procure saber mais sobre, você pode começar por <a href="https://cloud.google.com/kubernetes-engine/kubernetes-comic/">aqui</a>.</p><p>Agora que você já sabe o que é o k8s, já sabe o impacto que ele vem causando na forma como colocamos aplicações no ar. De fato é muito simples escrever um yaml e rodar um comando kubectl apply -f my-project.yaml, porém, isso é escalável?</p><p>Você não pode simplesmente entregar o kubectl para todos os desenvolvedores da sua empresa e esperar que nenhum comando perigoso (ou desastroso) seja executado, principalmente se você conta com um número elevado de desenvolvedores (IMO, nesse cenário, 20 desenvolvedores já é um número grande). E é claro, kubectl é uma ferramenta para quem opera o cluster, não para quem desenvolve aplicações para ele :-].</p><p>A solução mais comum que vem sendo empregada por várias empresas é investir pesado em processos de CI/CD, porém, com CI/CD, até onde vai a autonomia do desenvolvedor e o quanto você consegue expor de funcionalidades para eles? Outros problemas nesse cenário podem vir a tona, como por exemplo, manter (ou pagar por) um registry de imagens docker privado, falta de padronização nos objetos criados no cluster, etc.</p><p>Aqui no LuizaLabs escolhemos outro caminho.</p><h4>Kubernetes in real life</h4><p>No LuizaLabs estamos na margem de <strong>400 desenvolvedores</strong> e em constante expansão. Esses desenvolvedores possuem os mais diversos skills e backgrounds, alguns já experientes em aplicações que rodam no cloud, outros ainda com dependências rodando on premise.</p><p>Nosso desafio é continuar aumentando essa escala mas sem perder agilidade. Porém sem uma padronização na forma como provisionamos nossos ambientes, isso seria uma tortura. Nesse aspecto o k8s se torna nosso melhor amigo, no entanto temos os problemas já citados antes.</p><p>A partir dessa dor, resolvemos criar o nosso próprio PaaS.</p><h4>Teresa — Nosso próprio PaaS</h4><p>Sim, é isso mesmo, nós optamos por construir nosso próprio PaaS nos espelhando em projetos de sucesso como por exemplo o <a href="https://www.heroku.com/">Heroku</a>, porém, em cima do k8s.</p><p>O <a href="https://github.com/luizalabs/teresa">Teresa</a> é um projeto open source, escrito em <a href="https://golang.org/">Golang</a> e em constante evolução, com ele você consegue fazer o seu controle de usuários e permissões completamente apartado do k8s e de quebra você ainda possui uma ferramenta poderosa para fazer build de suas aplicações (baseado nos <a href="https://devcenter.heroku.com/articles/buildpacks">buildpacks</a> do heroku).</p><p>E o melhor de tudo, com poucos comandos você pode instalar o Teresa em seu cluster de k8s e ter seu próprio PaaS (veremos como fazer isso em um próximo artigo :-] ).</p><h4>Como o Teresa funciona</h4><p>O Teresa após <em>instalado</em> no cluster, passa a consumir o <a href="https://kubernetes.io/docs/reference/generated/kube-apiserver/">kube-apiserver</a> para criar objetos no cluster. Ao criar um novo app, o Teresa cria um novo namespace para esse app com alguns secrets.</p><p>De maneira simplificada, no momento do deploy desse app, é gerado um pod que utiliza o <a href="https://github.com/luizalabs/slugbuilder">Slugbuilder</a> em conjunto com os buildpacks do Heroku a fim de criar um build da aplicação.</p><p>Ao final da geração desse build, o Teresa gera um deploy do k8s utilizando como imagem o <a href="https://github.com/luizalabs/slugrunner">Slugrunner</a> e caso a aplicação seja um <em>webservice</em>, um <a href="https://kubernetes.io/docs/concepts/services-networking/service/">Service</a> do k8s é criado (isso somente no primeiro deploy).</p><h4>Autonomia com responsabilidade</h4><p>Com o Teresa, os desenvolvedores têm a autonomia que precisam e o time de ops tem menos overhead.</p><p>A partir do cli da Teresa o desenvolvedor consegue criar usuários, times, aplicações, consegue deletá-los, criar deploys, cronjobs, fazer rollbacks, alterar regras de scaling, quotas de recurso, variáveis de ambiente, configurar healthchecks, estratégia de rolling update, consultar logs (com opção de follow), rodar comandos em réplicas isoladas, etc. Isso sem contar as vantagens de rodar uma aplicação no k8s, como por exemplo service discovery.</p><p>Em termos de operação do cluster, as aplicações criadas no k8s via Teresa segue o mesmo padrão, então é mais fácil entender o que está acontecendo no cluster e como debugar uma aplicação no meio de um troubleshooting.</p><p>Em um dos próximos artigos mostraremos como subir uma aplicação no k8s via Teresa e como manipulá-la.</p><h4>Os resultados obtidos</h4><p>Hoje, graças ao Teresa, já temos (até o momento) mais de 200 aplicações em produção, escritas em diferentes linguagens (python, go, java e nodejs) e já passamos por duas black friday.</p><p>Com pouquíssimas adequações (ouvir na porta especificada na variável de ambiente $PORT e ter um <a href="https://devcenter.heroku.com/articles/procfile">Procfile</a>), qualquer aplicação já está preparada para rodar no k8s via Teresa, o que significa que a aplicação já se torna nativa ao cloud (ok, eu sei, só isso não torna a aplicação resiliente por exemplo, mas é um passo).</p><p>Outra vantagem de estar <em>on top of kubernetes</em> é que nossa infra se torna multi-cloud (inclusive já rodamos o Teresa em clusters de k8s on premise e em diferentes cloud providers)</p><h4>Como posso usar?</h4><p>Em outros posts pretendo mostrar os processos de instalação do Teresa em um cluster k8s (visão do admin do cluster) e como utilizar a ferramenta (visão do desenvolvedor), mas se você não quiser esperar, você pode olhar o <a href="https://github.com/luizalabs/teresa/blob/master/README.md">README</a> do projeto.</p><p>Caso você tenha alguma dúvida, pode entrar em contato conosco no canal <strong>#teresa</strong> no <a href="https://invite.slack.golangbridge.org/">slack da comunidade go</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ea0e6b71cf8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luizalabs/como-aceleramos-a-ado%C3%A7%C3%A3o-do-kubernetes-em-larga-escala-5ea0e6b71cf8">Como aceleramos a adoção do Kubernetes em larga escala</a> was originally published in <a href="https://medium.com/luizalabs">luizalabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Listen gRPC and HTTP requests on the same port]]></title>
            <link>https://drgarcia1986.medium.com/listen-grpc-and-http-requests-on-the-same-port-263c40cb45ff?source=rss-c1ee4d001ed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/263c40cb45ff</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Diego Garcia]]></dc:creator>
            <pubDate>Tue, 08 Aug 2017 17:51:14 GMT</pubDate>
            <atom:updated>2017-08-08T17:51:14.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*gB04lteGvcOoMDKtWVce8w.jpeg" /></figure><p>As I said before, I&#39;m working on a great project called Teresa written in Golang that uses gRPC. To facilitate monitoring and health checks, we decided to expose a health check endpoint with HTTP standard protocol instead of gRPC, but how can we expose those services on the same port?</p><p>There is a great project called <a href="https://github.com/soheilhy/cmux">cmux</a> that can help us like a charm. According to cmux documentation: cmux is a generic Go library to multiplex connections based on their payload. In other words, you create a common net.Listener and define some rules to route your requests to the right server.</p><p>Talk is cheap, so let&#39;s build a toy example to show cmux in action beginning with a gRPC handler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a679bb4a5ff1391e57e0be6e38e7e9da/href">https://medium.com/media/a679bb4a5ff1391e57e0be6e38e7e9da/href</a></iframe><p>Nothing special here, right? Now, a &quot;ping-pong&quot; HTTP handler:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19c05c0a4cfd8d9179bdcbdee38d3e02/href">https://medium.com/media/19c05c0a4cfd8d9179bdcbdee38d3e02/href</a></iframe><p>Ok, now is the time to “up and running”. We’ll create the main listener, a new connection multiplexer (aka cmux instance), new listeners that accept only connections that respect some rules like protocol, headers, etc (under the hood, those listeners use the same main listener we had created before) and finally start our server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69d62159612bd6d09309f79c4f9abff1/href">https://medium.com/media/69d62159612bd6d09309f79c4f9abff1/href</a></iframe><p>Done! Now you can run both servers (gRPC and HTTP) on the same TCP port. You can check the complete example on <a href="https://github.com/drgarcia1986/grpc-hw/tree/master/grpc-http-same-port">Github</a>.</p><p>There is another way to deal with gRPC and HTTP on the same port without a third party framework (like cmux), but it’s a subject to another post.</p><p>Do you remember the problem I described in my <a href="https://medium.com/@drgarcia1986/creating-a-filter-for-your-grpc-logs-1f6a34bd7e41">last post</a>? Well, now it&#39;s solved, because I started to accept HTTP requests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=263c40cb45ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a filter for your gRPC logs]]></title>
            <link>https://drgarcia1986.medium.com/creating-a-filter-for-your-grpc-logs-1f6a34bd7e41?source=rss-c1ee4d001ed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f6a34bd7e41</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Diego Garcia]]></dc:creator>
            <pubDate>Sun, 30 Jul 2017 15:46:29 GMT</pubDate>
            <atom:updated>2017-07-30T15:46:29.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*72e4svQUvaeTt6Hye20ulA.jpeg" /></figure><p>I’m having a lot of fun working on <a href="https://github.com/luizalabs/teresa-api">Teresa</a> project (Teresa is a simple PaaS on top of Kubernetes). Our main use case is <a href="http://www.magazineluiza.com.br/">Magazine Luiza</a> where we deploy hundreds of applications to cloud with AWS as a cloud provider of our Kubernetes cluster.</p><p>Recently we chose to change from go-swagger to gRPC. Consequently, the project quality took a leap forward. But after that, an annoying behavior came across. When you expose a Load Balancer service in Kubernetes, it creates a load balancer on the cloud provider and by default, the AWS ELB performs a health check in its backend. But, gRPC uses HTTP2 instead of HTTP1 and doesn’t understand the ELB health check requests causing chaos on logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYgDu_MEVWb-tBS8h5qbHQ.png" /><figcaption>I was tired of using grep -v</figcaption></figure><p>I don’t wanna to change the configurations of ELB by hand because it’s not a multi-cloud action and while Kubernetes doesn’t provide a way to deal with it, I’ll fix this issue on the application layer.</p><p>Fortunately, creating a filter in logs of the standard library is very simple, you just have to re-write the method Write of io.Writer interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99a67c42cd095bfe7d7791cee6a41672/href">https://medium.com/media/99a67c42cd095bfe7d7791cee6a41672/href</a></iframe><p>And to use it with gRPC, just set the logger of the server with this new writer: grpclog.SetLogger(logger.New(os.Stdout)). And that&#39;s it, no more tons of useless messages on your log.</p><p>Is there a better solution for this issue? Let me know If you know a better way to solve this issue without the AWS console (i.e. a generic solution for any cloud provider).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f6a34bd7e41" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>