<?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 MingSheng on Medium]]></title>
        <description><![CDATA[Stories by MingSheng on Medium]]></description>
        <link>https://medium.com/@hax.artisan?source=rss-9da7500be9ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6IA8HQLrrMX3E_1h</url>
            <title>Stories by MingSheng on Medium</title>
            <link>https://medium.com/@hax.artisan?source=rss-9da7500be9ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:15:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hax.artisan/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[AWS RDS IAM authentication]]></title>
            <link>https://medium.com/@hax.artisan/aws-rds-iam-authentication-59f2dfbf0cc6?source=rss-9da7500be9ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/59f2dfbf0cc6</guid>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[iam-authentication]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[MingSheng]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 09:49:31 GMT</pubDate>
            <atom:updated>2025-02-04T09:49:31.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context</h3><p>There are occasions when we need to extend production data access to a group of people.</p><p>However, we want to reduce the security risk and access control</p><ul><li>prevent password storage in local machine with IAM <em>authentication token</em></li><li>reduce effort on periodical password rotation</li><li>reduce effort on maintaining access control with predefined period</li><li>limit to only certain instance</li></ul><h3><strong>Limitation</strong></h3><p>supported DB: MariaDB, MySQL, and PostgreSQL</p><h3><strong>Workflow</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-Q5LsMre5hqg74_5AYSCA.png" /></figure><h3>Setup</h3><ol><li>Enable IAM authentication configuration on RDS</li></ol><ul><li>Enable cluster via cli (if rds is created as a cluster)</li></ul><pre>aws rds modify-db-cluster \<br>    --db-cluster-identifier mydbinstance \<br>    --apply-immediately \<br>    --enable-iam-database-authentication</pre><ul><li>Enable instance via cli (if rds is created as an instance)</li></ul><pre>aws rds modify-db-instance \<br>    --db-instance-identifier mydbinstance \<br>    --apply-immediately \<br>    --enable-iam-database-authentication</pre><p>2. Attach IAM policy to allow IAM roles</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;rds-db:connect&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:rds-db:us-east-2:1234567890:dbuser:*/*&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>for a more granular on certain rds instance</p><pre>{<br>   &quot;Version&quot;: &quot;2012-10-17&quot;,<br>   &quot;Statement&quot;: [<br>      {<br>         &quot;Effect&quot;: &quot;Allow&quot;,<br>         &quot;Action&quot;: [<br>             &quot;rds-db:connect&quot;<br>         ],<br>         &quot;Resource&quot;: [<br>             &quot;arn:aws:rds-db:us-east-2:1234567890:dbuser:db-ABCDEFGHIJKL01234/db_user&quot;<br>         ]<br>      }<br>   ]<br>}</pre><p>for a more granular predefined fix period</p><pre>{<br>  &quot;Sid&quot;: &quot;AllowRotaConnectIamDbUser&quot;,<br>  &quot;Effect&quot;: &quot;Allow&quot;,<br>  &quot;Action&quot;: [&quot;rds-db:connect&quot;],<br>  &quot;Resource&quot;: [&quot;arn:aws:rds-db:ap-southeast-1:${get_aws_account_id()}:dbuser:*/db_user_developer&quot;],<br>  &quot;Condition&quot;: {<br>    &quot;DateGreaterThanEquals&quot;: {&quot;aws:CurrentTime&quot;: &quot;2025-01-27T00:00:00+08:00&quot;},<br>    &quot;DateLessThanEquals&quot;: {&quot;aws:CurrentTime&quot;: &quot;2025-01-30T00:00:00+08:00&quot;},<br>    &quot;StringLike&quot;: {<br>      &quot;aws:userid&quot;: [&quot;*:tom&quot;]<br>    }<br>  }<br>}js</pre><p>The id db-ABCDEFGHIJKL01234 represent <strong>RDS Instance Identifier</strong>, which can be obtained via cli. The user db_user is a database user.</p><pre>aws rds describe-db-instances --query &quot;DBInstances[*].[DBInstanceIdentifier,DbiResourceId]&quot;</pre><p>3. Create database user</p><ul><li>Postgres</li></ul><pre>CREATE USER db_user; <br>GRANT rds_iam TO db_user;</pre><ul><li>MySQL</li></ul><pre>CREATE USER &#39;db_user&#39; IDENTIFIED WITH AWSAuthenticationPlugin AS &#39;RDS&#39;;</pre><p>4. Generate an authentication token and connect</p><ul><li>Postgres</li></ul><pre>RDSHOST=&quot;rdspostgres.123456789012.us-west-2.rds.amazonaws.com&quot;<br>AUTH_TOKEN=&quot;$(aws rds generate-db-auth-token --hostname $RDSHOST --port 5432 --region us-west-2 --username db_user )&quot;<br><br>psql &quot;host=rdspostgres.123456789012.us-west-2.rds.amazonaws.com port=5432 dbname=DBName user=db_user password=$AUTH_TOKEN&quot;<br></pre><ul><li>MySQL</li></ul><pre>$AUTH_TOKEN=$(aws rds generate-db-auth-token \<br>   --hostname rdsmysql.123456789012.us-west-2.rds.amazonaws.com \<br>   --port 3306 \<br>   --region us-west-2 \<br>   --username db_user)<br><br>mysql --host=rdsmysql.123456789012.us-west-2.rds.amazonaws.com \<br>    --port=3306 --enable-cleartext-plugin --user=db_user \<br>    --password=$AUTH_TOKEN</pre><h3>Possible Automation</h3><ul><li>Postgres<br>- authentication with pgpass<br>- authentication token generated using shell script</li></ul><pre>AUTH_TOKEN=$(aws rds generate-db-auth-token --hostname &quot;$RDS_HOST&quot; --port &quot;$RDS_POST&quot; --region $AWS_REGION --username &quot;$RDS_USER&quot; | sed &#39;s/\\/\\\\/g; s/:/\\:/g&#39;)<br><br>echo &quot;$RDS_HOST:$2:$3:$4:${AUTH_TOKEN}&quot;&gt;&gt;~/.pgpass</pre><p>note: special characters : or \ to escape with \</p><h3>Nutshell</h3><p>Benefits of using RDS IAM authentication</p><ul><li>authentication token password live every 15 minutes to improve security</li><li>reduce risk when password is stored locally</li><li>granular control with period</li><li>granular control to reader instance</li></ul><h3>Reference</h3><ul><li>pgpass spec <a href="https://www.postgresql.org/docs/current/libpq-pgpass.html">https://www.postgresql.org/docs/current/libpq-pgpass.html</a></li><li>MySQL option file spec <a href="https://dev.mysql.com/doc/refman/8.4/en/option-files.html">https://dev.mysql.com/doc/refman/8.4/en/option-files.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59f2dfbf0cc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hashicorp vault: migrate to a different AWS account]]></title>
            <link>https://medium.com/@hax.artisan/hashicorp-vault-migrate-to-a-different-aws-account-1786d3dd46f5?source=rss-9da7500be9ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/1786d3dd46f5</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[kms-key]]></category>
            <category><![CDATA[migrate]]></category>
            <category><![CDATA[vault]]></category>
            <dc:creator><![CDATA[MingSheng]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 18:24:51 GMT</pubDate>
            <atom:updated>2024-12-18T18:31:56.298Z</atom:updated>
            <content:encoded><![CDATA[<p>A quick and simple way to migrate the Hashicorp vault from AWS account A to AWS account B</p><p>Migration is suitable for</p><ul><li>vault is running with auto seal/unseal with AWS KMS key</li><li>dynamodb as storage backend</li></ul><h3>The mechanism</h3><p>The backend storage is sealed with old KMS key , it has to be unsealed before it can be sealed with new KMS key to work</p><h3>The workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7rhX06HumEeQZIrklV8lw.png" /></figure><p>Please refer to the guide on using AWS backup service for recovery point creation and recovery point copy across AWS accounts. <a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/copy-amazon-dynamodb-tables-across-accounts-using-aws-backup.html">https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/copy-amazon-dynamodb-tables-across-accounts-using-aws-backup.html</a></p><h4>1. Create AWS recovery point with AWS backup service in AWS account A</h4><h4>2. Copy AWS recovery point with AWS backup service to AWS account</h4><p>The required permission for AWS account A backup IAM role to to access backup-vault in AWS account B</p><pre>{<br> &quot;Effect&quot;: &quot;Allow&quot;,<br> &quot;Action&quot;: [<br>  &quot;backup:*&quot;<br> ],<br> &quot;Resource&quot;: [<br>  &quot;arn:aws:backup:{aws-region}:{aws-account-B}:backup-vault:*&quot;<br> ]<br>}</pre><h4>3. Restore AWS recovery point to dynamodb in AWS account B</h4><ul><li><strong>New dynamodb table name: </strong>any preference</li><li><strong>Encryption key: </strong>any KMS key can be used</li><li><strong>Restore role: </strong>any IAM role with permission</li></ul><h4>4. Auto unseal with KMS key from AWS account A</h4><p>In Hashicorp vault that is running in AWS account B. Update seal config with KMS key from AWS account A, vault is now running in AWS account B</p><pre>seal &quot;awskms&quot; {<br>  region = &quot;aws-region&quot;<br>  kms_key_id = &quot;arn:aws:kms:{aws-region}:{aws-account-A}:key/{aws-account-A-kms-key-id}&quot;              <br>}</pre><p>The required permission for service account IAM role in AWS account B</p><pre>{<br>  actions = [<br>    &quot;kms:Encrypt&quot;,<br>    &quot;kms:Decrypt&quot;,<br>    &quot;kms:DescribeKey&quot;<br>  ]<br>  effect    = &quot;Allow&quot;<br>  resources = [&quot;arn:aws:kms:ap-southeast-1:${loc}:key/f3f9ea66-639d-408f-afb1-105f6251b3d7&quot;, &quot;arn:aws:kms:ap-southeast-1:801475574804:key/ed5a0896-4160-4557-85ee-f19188767367&quot;]<br>}</pre><p><strong>5. Auto seal/unseal with KMS key AWS account B</strong></p><p>Update seal config with KMS key from AWS account B</p><pre>seal &quot;awskms&quot; {<br>  region = &quot;aws-region&quot;<br>  kms_key_id = &quot;arn:aws:kms:{aws-region}:{aws-account-B}:key/{aws-account-B-kms-key-id}&quot;              <br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1786d3dd46f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[k8s: debug & troubleshoot distroless pod]]></title>
            <link>https://medium.com/@hax.artisan/k8s-debug-troubleshoot-distroless-pod-13431cb9d645?source=rss-9da7500be9ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/13431cb9d645</guid>
            <category><![CDATA[distroless]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[debug]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[MingSheng]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 18:39:12 GMT</pubDate>
            <atom:updated>2024-12-15T11:11:08.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAPHLP5wsCql3dJn9A9PRw.png" /></figure><p>Using a distroless image can greatly improve security, performance, and cost. However, debugging and troubleshooting can be a serious headache.</p><p>The fact that distroless images strip off everything else and only keep necessary runtime dependencies. It becomes almost impossible to understand what’s going on when issues arise.</p><h3>Ways going about it</h3><ul><li><a href="#a678">kubectl command</a></li><li><a href="#c345">sidecar container</a></li><li><a href="#d7f8">nutshell</a></li></ul><h3>kubectl debug command</h3><p>Consider the following manifest for a pod running with distroless image</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: test-hello-world-distroless<br>spec:<br>  containers:<br>    - name: hello-world<br>      image: pureiboi/helloworld:latest</pre><p>Given the nature of the distroless image, one can’t attach or spawn a shell to run commands.</p><p>There will be an error when we try to get a shell</p><pre>kubectl exec -it test-hello-world-distroless -c hello-world -- /bin/bash<br><br>error: Internal error occurred: error executing command in container: failed to exec in container: failed to start exec &quot;afb6fe3f0727032e7631a4629a48daeb7ad202b52c72685031ce664d759364ad&quot;: OCI runtime exec failed: exec failed: unable to start container process: exec: &quot;/bin/bash&quot;: stat /bin/bash: no such file or directory: unknown</pre><p>To get around this, we can add an ephemeral container to existing pods and review underlying resources in the pod.</p><pre>kubectl debug -it test-hello-world-distroless - image=pegi3s/utilities:latest - share-processes - target=hello-world</pre><p>We will need to find out the process id with command ps -ax before proceeding further</p><pre>root@test-hello-world-distroless:/# ps -ax<br>  PID TTY      STAT   TIME COMMAND<br>    1 ?        Ssl    0:00 /pinger<br>   18 pts/0    Ss     0:00 /bin/bash<br>   31 pts/0    R+     0:00 ps -ax</pre><p>Now we can review the missing pieces for better troubleshooting session, i.e file system, network,</p><pre>root@test-hello-world-distroless:/# ls /proc/1/root/      <br>dev  etc  pinger  proc  sys  var</pre><h3>Sidecar container</h3><p>sidecar container is straightforward, however, it may not help in some cases.</p><p>the following manifest will spawn a pod with 2 containers</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: test-hello-world-distroless<br>spec:<br>  containers:<br>    - name: hello-world<br>      image: pureiboi/helloworld:latest<br>    - name: army-swiss-army<br>      image: leodotcloud/swiss-army-knife:latest<br><br></pre><p>now we can create a shell for the debugging container army-swiss-army</p><pre>kubectl exec -it test-hello-world-distroless -c army-swiss-army -- bash</pre><h3>Nutshell</h3><p>The approach to debug k8s pods depends on whether one has constraints.</p><p>The approach to choose depends on whether one needs to inspect the current state of a running pod.</p><ul><li>sidecar containers require pod recreation, you might need to keep the current pod state for investigation</li><li>sidecar containers require the same volume mount for file system issues</li><li>ephemeral container does not remove itself, if one forgets to handle it, it might result in a security risk</li><li>ephemeral container does not require restart, it can be useful to inspect a current state of a running pod</li><li>ephemeral container gets to review and inspect file system of a current running pod</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13431cb9d645" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go: Monitor your goroutine]]></title>
            <link>https://medium.com/@hax.artisan/go-monitor-your-goroutine-application-9edbdd6e581b?source=rss-9da7500be9ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/9edbdd6e581b</guid>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[monitoring]]></category>
            <dc:creator><![CDATA[MingSheng]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 03:49:14 GMT</pubDate>
            <atom:updated>2024-11-28T14:36:55.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-itiBppNJAB7DTsDoFlNIQ.png" /></figure><p>Working on goroutine can be little tricky and frustrating when it gets out of hand.</p><p>While there are few ways to monitor and track number of go routines which can be helpful on troubleshooting your goroutines.</p><h3>Understand the basic of goroutine</h3><blockquote>A <em>goroutine</em> is a lightweight thread managed by the Go runtime.</blockquote><p>Consider the following simple application that tells everything about the sentence, given a main thread.</p><pre><br>func main(){<br> fmt.Printf(&quot;Number of goroutines: %d\n&quot;, runtime.NumGoroutine())<br>}<br><br>----<br><br>// output <br>Number of goroutines: 1</pre><h3><strong>Monitoring goroutines</strong></h3><h4><strong>Using runtime package</strong></h4><pre>runtime.NumGoroutine()</pre><p>whenever a goroutine is spawned, the counter will display total number of goroutine including the main thread.</p><p>snippet that prints total 3 gorotines</p><pre>// 3 go routines<br>func main(){<br>  for x := range 2 {<br>      wg.Add(1)<br>      go func(){<br>        // some code here<br>      }()<br>  }<br>  fmt.Println(runtime.NumGoroutine())<br>}</pre><p><strong>Putting working code together</strong></p><p>We may have one or more goroutines worker doing the actual job.</p><pre>func worker(wg *sync.WaitGroup, id int, ch &lt;-chan int, done chan&lt;- int) {<br><br>    defer wg.Done()<br>    for x := range ch {<br>       time.Sleep(time.Second * 2)<br>       fmt.Printf(&quot;worker %d display x from channel %d\n&quot;, id, x)<br>    }<br>    done &lt;- 1<br>}</pre><p>We will have a goroutine monitor on number of goroutines every second</p><pre>func monitorGoroutines(ctx context.Context, wg *sync.WaitGroup) {<br>    defer wg.Done()<br>    for {<br>       select {<br>       case &lt;-ctx.Done():<br>          fmt.Println(&quot;context is done&quot;)<br>          return<br>       default:<br>          time.Sleep(time.Second)<br>          fmt.Printf(&quot;Number of goroutines: %d\n&quot;, runtime.NumGoroutine())<br>       }<br>    }<br>}</pre><p>Our main thread will spawn goroutine on monitoring, and worker go routine.</p><p>It will utilize channel for communication</p><pre>func main() {<br><br>    noOfWorker := 5<br>    ch := make(chan int, 100)<br>    done := make(chan int, 100)<br><br>    wg.Add(1)<br>    go monitorGoroutines(ctx, wg)<br><br>    for x := range noOfWorker {<br>       wg.Add(1)<br>       go worker(wg, x, ch, done)<br>    }<br><br>    for x := range 100 {<br>       ch &lt;- x<br>    }<br>    close(ch)<br>}</pre><p>The output, we will get total 8 goroutines.</p><p>1 for the main thread, 1 for notifying the job completion, 1 for goroutine monitoring, 5 for the workers</p><pre>.<br>.<br>.<br>Number of goroutines: 8<br>worker 4 display x from channel 96<br>worker 1 display x from channel 95<br>Number of goroutines: 6<br>worker 0 display x from channel 99<br>worker 2 display x from channel 97<br>worker 3 display x from channel 98<br>context is cancelled<br>Number of goroutines: 2<br>context is done<br>All operation finished</pre><p>Source code using runtime package</p><p><a href="https://github.com/pureiboi/MonitorGoroutine/blob/main/runtimex/main.go">MonitorGoroutine/runtimex/main.go at main · pureiboi/MonitorGoroutine</a></p><h4>Using pprof server</h4><pre>go func() {<br>    http.ListenAndServe(&quot;localhost:6060&quot;, nil)<br>}()</pre><p>profiling data can be less intuitive, especially when it comes to understand whether goroutine is spawned by you or by the HTTP server</p><p><strong>putting working code together</strong></p><pre>func main() {<br><br>    go func() {<br>       http.ListenAndServe(&quot;localhost:6060&quot;, nil)<br>    }()<br><br><br>    go func() {<br>       for {}<br>    }()<br><br><br>    for {}<br>}</pre><p>simply visit the URL <a href="http://localhost:6060/debug/pprof/goroutine?debug=1">http://localhost:6060/debug/pprof/goroutine?debug=1</a> will display the goroutine information</p><p>side note about the debug variable</p><pre>debug = 0 will generate binary<br>debug = 1 will plain text<br>debug ≥ 2 will display traces</pre><p>The line one will tell us total number of goroutine currently running.</p><p>Little tricky that we have 2 infinite loops runing in each in main thread and goroutine, that gives us total of 2 goroutines.</p><p>That means profiling http server comes with 3 goroutine by default, we will need to exclude that during troubleshooting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kF_HOxWxJucKDCQ-s3zIfw.png" /></figure><p>Source code using pprof</p><p><a href="https://github.com/pureiboi/MonitorGoroutine/blob/main/pprof/main.go">MonitorGoroutine/pprof/main.go at main · pureiboi/MonitorGoroutine</a></p><h4>Using prometheus</h4><p>This might be an overkill, but it is interesting to learn that how we can integrate small application into prometheus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNI6mKPbdhGngo0s4WtH2w.png" /></figure><p>Spawn an goroutine and expose metrics with prometheus package</p><pre>go func() {<br>  http.Handle(&quot;/metrics&quot;, promhttp.Handler())<br>  http.ListenAndServe(&quot;:2112&quot;, nil)<br> }()</pre><p><strong>Putting working code together</strong></p><pre>func main() {<br><br>    go func() {<br>       http.Handle(&quot;/metrics&quot;, promhttp.Handler())<br>       http.ListenAndServe(&quot;:2112&quot;, nil)<br>    }()<br><br>    go func(){<br>       for{}<br>    }()<br><br>    for {}<br>}</pre><p>Visit URL <a href="http://localhost:2112/metrics">http://localhost:2112/metrics</a> and you prolly notice the count on goroutines</p><pre># TYPE go_goroutines gauge<br>go_goroutines 8</pre><p>this may little tricky here, since promtheus package taken up 6 goroutines given our simple application</p><p>Source code using prometheus</p><p><a href="https://github.com/pureiboi/MonitorGoroutine/blob/main/prom/main.go">MonitorGoroutine/prom/main.go at main · pureiboi/MonitorGoroutine</a></p><p>full source code can be found here</p><p><a href="https://github.com/pureiboi/MonitorGoroutine">GitHub - pureiboi/MonitorGoroutine</a></p><h3>Reference</h3><ul><li><a href="https://go.dev/doc/effective_go#goroutines">Effective Go - The Go Programming Language</a></li><li><a href="https://pkg.go.dev/net/http/pprof">pprof</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9edbdd6e581b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go: Unbuffered Channel VS Buffered Channel]]></title>
            <link>https://medium.com/@hax.artisan/go-unbuffered-channel-vs-buffered-channel-80d393c001fa?source=rss-9da7500be9ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/80d393c001fa</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[buffered-channel]]></category>
            <category><![CDATA[unbuffered-channel]]></category>
            <dc:creator><![CDATA[MingSheng]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 12:04:30 GMT</pubDate>
            <atom:updated>2024-11-17T12:04:30.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8W0EgXtoieeh7FkvEzZ0Iw.png" /></figure><p>Concurrency has always been a big topic. Golang provides concurrency using Channel as form of communication. This encourage a mindset</p><blockquote><em>Do not communicate by sharing memory; instead, share memory by communicating.</em></blockquote><h3>Unbuffered Channel</h3><p><strong>Sending</strong>: sender goroutine places a value into channel, the sender will be blocked if there is no receiver ready to take the value. Once the value is received by receiver, the sender resumes its execution.</p><p><strong>Receiving</strong>: receiver goroutine takes value from channel, the receiver will be blocked if there is no data to receive.</p><p>Snippet for <strong>sender</strong> blocking</p><pre>func main() {<br>    jobs := make(chan int)<br>    jobs &lt;- 0<br>}</pre><p>Snippet for <strong>receiver</strong> blocking</p><pre>func main() {<br>    jobs := make(chan int)<br>    &lt;- jobs<br>}</pre><p>Both will result to goroutines deadlock</p><pre>fatal error: all goroutines are asleep - deadlock!<br><br>goroutine 1 [chan receive]: | goroutine 1 [chan send]:</pre><p>Putting things together</p><pre>func worker(jobs &lt;-chan int) {<br>    for {<br>       j, more := &lt;-jobs<br>       if more {<br>          fmt.Println(&quot;received job&quot;, j)<br>       }<br>    }<br>}<br><br>func main() {<br><br>    jobs := make(chan int)<br><br>    go worker(jobs)<br>    defer close(jobs)<br>    for i := range 100 {<br>       fmt.Println(&quot;sending job&quot;, i)<br>       jobs &lt;- i<br>    }<br>}</pre><p>With unbuffered channel, only 1 value can be sent and received at a time.</p><pre>sending job 0<br>sending job 1<br>received job 0<br>received job 1<br>sending job 2<br>sending job 3<br>received job 2<br>received job 3<br>...<br>...<br>sending job 98<br>sending job 99<br>received job 98<br>received job 99</pre><p>The output might be misleading as the Go runtime schedules goroutines concurrently. The main goroutine continue sending more jobs (2 sending and 2 receiving) to the channel while worker goroutine is processing one job before it prints. We will see clear distinct differences once we see outputs from buffered channel.</p><h3>Buffered Channel</h3><p>The buffered have a fixed size when initizing with make</p><p><strong>Sending</strong>: sender goroutine places a value and added to the buffer, the sender will be blocked if the buffer is full and there is no receiver ready. Once the value is received, the sender resumes its execution.</p><p><strong>Receiving</strong>: receiver goroutine takes value from channel buffer, the receiver will be blocked if the buffer is empty.</p><p>Snippet for <strong>sender</strong> blocking</p><pre>func main() {<br><br>    jobs := make(chan int, 5)<br><br>    for i := range 100 {<br>       jobs &lt;- i<br>       fmt.Println(&quot;sent job &quot;, i)<br>    }<br>}</pre><p>goroutine deadlock from sender</p><pre>sent job  0<br>sent job  1<br>sent job  2<br>sent job  3<br>sent job  4<br>fatal error: all goroutines are asleep - deadlock!<br><br>goroutine 1 [chan send]:</pre><p>Snippet for <strong>receiver</strong> blocking</p><pre>func main() {<br><br>    jobs := make(chan int, 50)<br><br>    &lt;-jobs<br>}</pre><p>goroutine deadlock from receiver</p><pre>fatal error: all goroutines are asleep - deadlock!<br><br>goroutine 1 [chan receive]:</pre><p>Putting things together with capacity of 50</p><pre>func worker(jobs &lt;-chan int) {<br><br>    for {<br>       j, more := &lt;-jobs<br>       if more {<br>          fmt.Println(&quot;received job&quot;, j)<br>       }<br>    }<br>}<br><br>func main() {<br><br>    jobs := make(chan int, 50)<br><br>    go worker(jobs)<br>    defer close(jobs)<br>    for i := range 100 {<br>       fmt.Println(&quot;sending job&quot;, i)<br>       jobs &lt;- i<br>    }<br>}</pre><p>With buffered channel, sender goroutine will fill up the buffer whenever it is not empty and received will take value from buffer whenever there is value</p><pre>sending job 0<br>sending job 1<br>sending job 2<br>sending job 3<br>...<br>...<br>sending job 47<br>sending job 48<br>sending job 49<br>sending job 50<br>sending job 51<br>received job 0<br>received job 1<br>received job 2<br>received job 3<br>...<br>...<br>received job 48<br>received job 49<br>received job 50<br>received job 51<br>sending job 52<br>sending job 53<br>sending job 54<br>...<br>...<br>sending job 71<br>sending job 72<br>sending job 73<br>received job 52<br>received job 53<br>...<br>...<br>sending job 98<br>sending job 99</pre><h3><strong>Consideration on chosing type of channel</strong></h3><p><strong>Unbuffered Channels</strong></p><ul><li><strong>Zero Capacity:</strong> Unbuffered channels do not use internal storage.</li><li><strong>Strict Synchronization:</strong> Sending and receiving on an unbuffered channel are synchronous operations. A sender must wait for a receiver, and vice versa.</li></ul><p><strong>Buffered Channels</strong></p><ul><li><strong>Non-Zero Capacity:</strong> Buffered channels have a fixed specified capacity, store values into internal storage.</li><li><strong>Asynchronous Communication:</strong> Senders can send values to a buffered channel without immediately blocking, as long as the buffer isn’t full. Receivers can receive values from a buffered channel without immediately blocking, as long as the buffer isn’t empty.</li></ul><h3>Reference</h3><p><a href="https://go.dev/doc/effective_go#concurrency">https://go.dev/doc/effective_go#concurrency</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80d393c001fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenSearch: Manage index alias and rollover]]></title>
            <link>https://medium.com/@hax.artisan/opensearch-manage-index-alias-and-rollover-98e1ee791250?source=rss-9da7500be9ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/98e1ee791250</guid>
            <category><![CDATA[opensearch]]></category>
            <category><![CDATA[alias]]></category>
            <category><![CDATA[index]]></category>
            <category><![CDATA[rollover]]></category>
            <dc:creator><![CDATA[MingSheng]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 02:37:17 GMT</pubDate>
            <atom:updated>2024-11-07T02:37:17.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*P4NLjLhAyICURAbHyrympQ.png" /></figure><h3>What is alias?</h3><p>An alias is a virtual index that points to 1 or more indexes, where indexes are grouped with alias for different operations.</p><p>Think of it like a box, holding index document with common properties, i.e different application logs, indexes rotated monthly</p><h3>What is rollover and when do you want to use rollover?</h3><p>When index rollover is called, backend will create a new index, and increments the index name with the pattern ^.*-\d+$</p><p>Rollover is important to keep index size small enough to improve search performance and optimized for warm/cold migration.</p><h3><strong>Getting Started with alias</strong></h3><p>Create an concrete index that complies with the rollover naming pattern, regex expression by the engine ^.*-\d+$</p><pre>PUT index-ts-run-000001</pre><p>Attach the index to an alias and update with is_write_index flag. With the flag prevent previous index will not be detached from alias, after new index is created and attached to alias.</p><pre>bash<br>POST _aliases<br>{<br>  &quot;actions&quot;: [<br>    {<br>      &quot;add&quot;: {<br>        &quot;index&quot;: &quot;index-ts-run-000001&quot;,<br>        &quot;alias&quot;: &quot;alias-ts-run&quot;,<br>        &quot;is_write_index&quot;: true<br>      }<br>    }<br>  ]<br>}</pre><p>Verify the alias, we can see that alias is created, and the index is attached to alias</p><pre>GET _cat/aliases/alias-ts-run?v<br><br>-------<br><br>alias        index               filter routing.index routing.search is_write_index<br>alias-ts-run index-ts-run-000001 -      -             -              true</pre><p>Perform a few manual rollover to see the effect</p><pre>POST alias-ts-run/_rollover<br><br>-------<br><br>alias        index               filter routing.index routing.search is_write_index<br>alias-ts-run index-ts-run-000001 -      -             -              false<br>alias-ts-run index-ts-run-000002 -      -             -              false<br>alias-ts-run index-ts-run-000003 -      -             -              false<br>alias-ts-run index-ts-run-000004 -      -             -              true</pre><p>Index operation can be done with alias, it will write document to <strong>write index, </strong>and read/search from all indexes with the alias</p><pre>GET alias-ts-run/_search<br><br>---- <br><br>POST /alias-ts-run/_doc<br>{<br>  &quot;name&quot;: &quot;Another Example&quot;,<br>  &quot;price&quot;: 19.99,<br>  &quot;description&quot;: &quot;We are such stuff as dreams are made on&quot;<br>}</pre><h3>Working on existing index with an alias</h3><p>Given the existing indexes</p><pre>green open index-old-ts-run-1          WOSKYd9ISKuK6ZGvOdtinw 5 1 0 0 2kb 1kb<br>green open index-old-ts-run            83f-YtZ3TfGKsXWwZ75fHA 5 1 0 0 2kb 1kb<br>green open index-old-ts-run-2024-11-11 8UxVlgGwRYCXWQkk-5U8XQ 5 1 0 0 2kb 1kb</pre><p>Adding existing indexes to alias</p><pre><br>POST _aliases<br>{<br>  &quot;actions&quot;: [<br>    {<br>      &quot;add&quot;: {<br>        &quot;index&quot;: &quot;index-old-ts-run*&quot;,<br>        &quot;alias&quot;: &quot;alias-new-ts-run&quot;<br>        }<br>    }<br>  ]<br>}</pre><p>Verifiy the alias</p><pre><br>GET _cat/aliases/alias-new-ts-run?v<br><br>alias            index                       filter routing.index routing.search is_write_index<br>alias-new-ts-run index-old-ts-run            -      -             -              -<br>alias-new-ts-run index-old-ts-run-1          -      -             -              -<br>alias-new-ts-run index-old-ts-run-2024-11-11 -      -             -              -</pre><p>Create a new write index with naming pattern to store the document and rollover</p><pre>PUT index-new-ts-convert-alias-000001</pre><p>Add the write index to alias</p><pre><br>POST _aliases<br>{<br>  &quot;actions&quot;: [<br>    {<br>      &quot;add&quot;: {<br>        &quot;index&quot;: &quot;index-new-ts-convert-alias-000001&quot;,<br>        &quot;alias&quot;: &quot;alias-new-ts-run&quot;,<br>        &quot;is_write_index&quot;: true<br>      }<br>    }<br>  ]<br>}</pre><p>Verify the added write index is_write_index flag is set</p><pre>alias            index                             filter routing.index routing.search is_write_index<br>alias-new-ts-run index-old-ts-run-1                -      -             -              -<br>alias-new-ts-run index-new-ts-convert-alias-000001 -      -             -              true<br>alias-new-ts-run index-old-ts-run                  -      -             -              -<br>alias-new-ts-run index-old-ts-run-2024-11-11       -      -             -              -</pre><p>Test rollover API with manual rollover and verify the effect</p><pre>POST alias-new-ts-run/_rollover<br><br><br>----<br><br>alias            index                             filter routing.index routing.search is_write_index<br>alias-new-ts-run index-old-ts-run-1                -      -             -              -<br>alias-new-ts-run index-new-ts-convert-alias-000001 -      -             -              false<br>alias-new-ts-run index-old-ts-run                  -      -             -              -<br>alias-new-ts-run index-new-ts-convert-alias-000002 -      -             -              false<br>alias-new-ts-run index-old-ts-run-2024-11-11       -      -             -              -<br>alias-new-ts-run index-new-ts-convert-alias-000005 -      -             -              false<br>alias-new-ts-run index-new-ts-convert-alias-000006 -      -             -              true<br>alias-new-ts-run index-new-ts-convert-alias-000003 -      -             -              false<br>alias-new-ts-run index-new-ts-convert-alias-000004 -      -             -              false</pre><h3>Benefits with alias and rollover</h3><ul><li>Single index name (virtual pointer) search and indexing</li><li>Single point of index within OpenSearch</li><li>Automated storage optimization management</li></ul><h3>Automation and Optimization</h3><p>Using ISM policy to manage index size and perform rollover. i.e rollover and create a new index once the index has reached 20gb.</p><p>This will do away with API call or storage management as needed with warm/cold tier migration</p><pre>PUT _plugins/_ism/policies/rollover_policy<br>{<br>  &quot;policy&quot;: {<br>    &quot;description&quot;: &quot;Example rollover policy.&quot;,<br>    &quot;default_state&quot;: &quot;rollover&quot;,<br>    &quot;states&quot;: [<br>      {<br>        &quot;name&quot;: &quot;rollover&quot;,<br>        &quot;actions&quot;: [<br>          {<br>            &quot;rollover&quot;: {<br>              &quot;min_size&quot;: &quot;20gb&quot;<br>            }<br>          }<br>        ],<br>        &quot;transitions&quot;: []<br>      }<br>    ],<br>    &quot;ism_template&quot;: {<br>      &quot;index_patterns&quot;: [&quot;alias-ts-run&quot;],<br>      &quot;priority&quot;: 100<br>    }<br>  }<br>}</pre><h3>Troubleshoot</h3><blockquote>Rollover an index and resulted error</blockquote><p>Rollover API can only trigger on alias or datastream. Refer to more details on <a href="https://opensearch.org/docs/latest/api-reference/index-apis/rollover/">https://opensearch.org/docs/latest/api-reference/index-apis/rollover/</a></p><pre>{<br>  &quot;error&quot;: {<br>    &quot;root_cause&quot;: [<br>      {<br>        &quot;type&quot;: &quot;illegal_argument_exception&quot;,<br>        &quot;reason&quot;: &quot;rollover target is a [concrete index] but one of [alias,data_stream] was expected&quot;<br>      }<br>    ],<br>    &quot;type&quot;: &quot;illegal_argument_exception&quot;,<br>    &quot;reason&quot;: &quot;rollover target is a [concrete index] but one of [alias,data_stream] was expected&quot;<br>  },<br>  &quot;status&quot;: 400<br>}</pre><blockquote>Rollover an alias with index name not following naming pattern ^.*-\d+$</blockquote><p>Rollover API will create and perform increment on a new index created. The OpenSearch engine is unable to derive new index with given index name for continuous index generation. Refer to more details on <a href="https://opensearch.org/docs/latest/im-plugin/ism/policies/#rollover">https://opensearch.org/docs/latest/im-plugin/ism/policies/#rollover</a></p><pre>{<br>  &quot;error&quot;: {<br>    &quot;root_cause&quot;: [<br>      {<br>        &quot;type&quot;: &quot;illegal_argument_exception&quot;,<br>        &quot;reason&quot;: &quot;index name [test-index-data] does not match pattern &#39;^.*-\\d+$&#39;&quot;<br>      }<br>    ],<br>    &quot;type&quot;: &quot;illegal_argument_exception&quot;,<br>    &quot;reason&quot;: &quot;index name [test-index-data] does not match pattern &#39;^.*-\\d+$&#39;&quot;<br>  },<br>  &quot;status&quot;: 400<br>}</pre><h3>Reference</h3><ul><li><a href="https://opensearch.org/docs/latest/api-reference/index-apis/alias/">Alias</a></li><li><a href="https://opensearch.org/docs/latest/api-reference/index-apis/rollover/#incrementing-index-names-for-an-alias">Rollover Index</a></li></ul><p><a href="https://opensearch.org/docs/latest/im-plugin/ism/policies/#rollover">https://opensearch.org/docs/latest/im-plugin/ism/policies/#rollover</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98e1ee791250" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitLab code coverage visualization with Cobertura]]></title>
            <link>https://medium.com/@hax.artisan/gitlab-code-coverage-visualization-with-cobertura-9cbf3df8b196?source=rss-9da7500be9ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cbf3df8b196</guid>
            <category><![CDATA[cobertura]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[MingSheng]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 18:09:59 GMT</pubDate>
            <atom:updated>2024-09-06T18:09:59.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Code Coverage visualization?</h3><p>Testing is one of the important phase in CICD pipeline</p><p>One of the key components is code coverage; It gives us insights on how extensive source source has been covered by unit test.</p><p>With code coverage visualization and integration on GitLab merge requests (MRs), you can view the code coverage in the file diff view just for the commit you have made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPDekhy8FVmrYQKr9Gh6Cw.png" /><figcaption>code coverage in file diff view (from gitlab.com)</figcaption></figure><h3>Consume the coverage report</h3><p>In order for the GitLab MR to display coverage report, GitLab CI/CD is to configure with artifacts coverage report in cobertura xml format.</p><p>GitLab consumes coverage report with artifcats keyword where cobertura xml is shared</p><pre>artifacts:<br>  reports:<br>    coverage_report:<br>      coverage_format: cobertura<br>      path: cobertura.xml</pre><p>Convert and generate cobertura xml format in a java project with haynes/jacoco2cobertura, the script supports both single module or multi-module maven project, and converts jacoco xml report into cobertura format</p><pre>script:<br>  - java_src=$(find &quot;$(pwd)&quot; -type d -regex &quot;.*src/main/java&quot; -exec echo {} \;)<br>  - python /opt/cover2cover.py target/site/jacoco/jacoco.xml $java_src &gt; cobertura.xml</pre><p>put everything together</p><pre>coverage-report:<br>  image: registry.gitlab.com/haynes/jacoco2cobertura:1.0.7<br>  script:<br>    - java_src=$(find &quot;$(pwd)&quot; -type d -regex &quot;.*src/main/java&quot; -exec echo {} \;)<br>    - python /opt/cover2cover.py target/site/jacoco/jacoco.xml $java_src &gt; cobert<br>  artifacts:<br>    reports:<br>      coverage_report:<br>        coverage_format: cobertura<br>        path: cobertura.xml<br></pre><p>The code coverage will be shown is MR, and it tells you whether a line of code has been covered by unit test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcWm9-OaAQSqo7DGaFu58A.png" /></figure><p>Complete code can be found here <a href="https://github.com/pureiboi/maven-unit-test">https://github.com/pureiboi/maven-unit-test</a></p><h3>Troubleshooting</h3><p>Few reasons that code coverage is showing</p><ul><li>The <strong>sources</strong> in cobertura xml may not be desired, there should be more than one child <strong>source </strong>nodes for multi-module project</li></ul><pre>&lt;sources&gt;<br>  &lt;source&gt;/tmp/maven-unit-test/module-a/src/main/kotlin&lt;/source&gt;<br>  &lt;source&gt;/tmp/maven-unit-test/module-b/src/main/kotlin&lt;/source&gt;<br>  &lt;source&gt;/tmp/maven-unit-test/module-common/src/main/kotlin&lt;/source&gt;<br>&lt;/sources&gt;</pre><ul><li>The changed file is not found in cobertura xml; Files changed has to be tested with coverage. Might want to verify the exclusion list.</li></ul><pre>&lt;class branch-rate=&quot;0.0&quot; complexity=&quot;4.0&quot; filename=&quot;io/poc/unit/test/ServiceA.kt&quot; line-rate=&quot;0.3333333333333333&quot; name=&quot;io.poc.unit.test.ServiceA&quot;&gt;</pre><ul><li>Cobertura xml is not configured as coverage report artifact. Take note syntax and path value</li></ul><pre>artifacts:<br>  reports:<br>    coverage_report:<br>      coverage_format: cobertura<br>      path: cobertura.xml</pre><h3>Reference</h3><p><a href="https://docs.gitlab.com/ee/ci/testing/test_coverage_visualization/cobertura.html">https://docs.gitlab.com/ee/ci/testing/test_coverage_visualization/cobertura.html</a></p><p><a href="https://docs.gitlab.com/ee/ci/yaml/index.html#artifactsreports">https://docs.gitlab.com/ee/ci/yaml/index.html#artifactsreports</a></p><p><a href="https://gitlab.com/haynes/jacoco2cobertura">https://gitlab.com/haynes/jacoco2cobertura</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cbf3df8b196" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>