<?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[Coccoc Engineering Blog - Medium]]></title>
        <description><![CDATA[Where engineers matter - Medium]]></description>
        <link>https://medium.com/coccoc-engineering-blog?source=rss----ac2691688f07---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Coccoc Engineering Blog - Medium</title>
            <link>https://medium.com/coccoc-engineering-blog?source=rss----ac2691688f07---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:37:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/coccoc-engineering-blog" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mythical 0-link, readable file and other wonkeries]]></title>
            <link>https://medium.com/coccoc-engineering-blog/mythical-0-link-readable-file-and-other-wonkeries-a3dbe0c82b38?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/a3dbe0c82b38</guid>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[containerd]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[hdhoang]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 05:07:29 GMT</pubDate>
            <atom:updated>2023-09-13T05:07:29.109Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Here are some unassorted strangeness we encountered recently, while<br>using k8s/containers on linux.</p><h3>Unbalanced directory index</h3><p>one day, a k8s node logged these messages every few hours, in bundles of 4:</p><pre>EXT4-fs warning (device md1): ext4_dx_add_entry:2380: Directory (ino: 211566352) index full, reach max htree level :2<br>EXT4-fs warning (device md1): ext4_dx_add_entry:2384: Large directory feature is not enabled on this filesystem<br>EXT4-fs warning (device md1): ext4_dx_add_entry:2380: Directory (ino: 211566352) index full, reach max htree level :2<br>EXT4-fs warning (device md1): ext4_dx_add_entry:2384: Large directory feature is not enabled on this filesystem<br>EXT4-fs warning (device md1): ext4_dx_add_entry:2380: Directory (ino: 211566352) index full, reach max htree level :2<br>EXT4-fs warning (device md1): ext4_dx_add_entry:2384: Large directory feature is not enabled on this filesystem<br>EXT4-fs warning (device md1): ext4_dx_add_entry:2380: Directory (ino: 211566352) index full, reach max htree level :2<br>EXT4-fs warning (device md1): ext4_dx_add_entry:2384: Large directory feature is not enabled on this filesystem</pre><p>the mentioned directory was always inode 211566352, so the situation impacted just 1 workload. redhat has a <a href="https://access.redhat.com/solutions/29894">nice article</a> explaining the mechanism at work, and a note explaining why it happened occasionally:</p><blockquote>Files can still be successfully created if the hash of their filename does not fall into an already full hash bucket.</blockquote><p>It includes an auditd log searching example at syscall level (egcreat, openat, …). however, at CocCoc, we’re more familiar with<a href="https://github.com/iovisor/bpftrace/blob/master/docs/reference_guide.md#1-kprobekretprobe-dynamic-tracing-kernel-level">ebpftooling</a>,<br>and the message contained a function-ish hint ext4_dx_add_entry. let’s hunt for the failing process:</p><pre>## is there some related probe/tracepoint?<br>$ sudo bpftrace -l &#39;*ext4_dx*&#39;<br>hardware:*ext4_dx*:<br>kprobe:ext4_dx_add_entry<br>kprobe:ext4_dx_csum<br>kprobe:ext4_dx_csum_set<br>kprobe:ext4_dx_find_entry<br>software:*ext4_dx*:<br><br><br>## yes, neat, let&#39;s grab any failling call &amp; print out the process<br>$ sudo bpftrace -e &#39;kretprobe:ext4_dx_add_entry /retval !=0/ {printf(&quot;%d %s: %d\n&quot;, pid, comm, retval);}&#39; |head -n 30<br>Attaching 1 probe...<br>2916472 php-fpm: -28<br>2916472 php-fpm: -28<br>2916472 php-fpm: -28<br>2916472 php-fpm: -28<br><br><br>## what is that<br>$ sudo systemctl status 2916472<br>...<br>kubepods-burstable.slice/kubepods-burstable-pod834b7b00_d731_4186_803c_8c4a35a84627.slice/cri-containerd-41b8343f32f8623c7d20942813b4a48c72cc0d34ae74<br>...<br>$ sudo crictl ps | grep 41b8343f3<br>...php...41b8343f3...some-app</pre><p>From there, we could do kubectl debug into the container &amp; look around for any huge directory. this app creates temporary files in a flat directory:</p><pre>$ stat /app/tmp<br>  File: /app/tmp<br>  Size: 586358784       Blocks: 1145712    IO Block: 4096   directory<br>Device: 901h/2305d      Inode: 211566352   Links: 2<br><br><br>## that&#39;s our reported inode! what&#39;s in there? links=2 shows that there&#39;s no subdirectory<br>$ find /app/tmp -type f | wc -l<br>4781597<br>$ du -h /app/tmp<br>242G    /app/tmp</pre><p>At this point, we made the mistake of rollout-restarting the deployment. new pods started working fine right away, but the old pods were still around in Terminating state. linux was busy removing the files in their overlayfs mount, including the above giant directories &amp; their files. that caused ~3hours of high write-iops to commit filesystem metadata on the nodes, which slowed down other unrelated workloads. we had to cordon them during that time, and moved more important pods out of there.</p><p>The strangest effect was that pods on other nodes also failed readiness check randomly. it turned out some of their mysqlrouters were on the heavy-load nodes. the db clusters were totally fine, they run on different HW.</p><pre>routing ERROR [7fc427ed7700] connecting to backend failed: Connection timed out (generic:110)<br>routing ERROR [7fc4286d8700] connecting to backend failed: not set (destinations:1)<br>routing ERROR [7fc425690700] connecting to backend failed: not set (destinations:1)<br>router Application got fatal signal: 11<br>router stack_bottom = 0 thread_stack 0x0<br>router /usr/lib64/mysqlrouter/private/libmysqlharness.so.1(my_print_stacktrace(unsigned char const*, unsigned long)+0x41) [0x7fc430782d71]<br>router /usr/lib64/mysqlrouter/private/libmysqlharness.so.1(+0xdc3b1) [0x7fc43076d3b1]<br>router /lib64/libpthread.so.0(+0x12d00) [0x7fc4303b4d00]<br>router /usr/lib64/mysqlrouter/private/libmysqlrouter_routing.so.1(MySQLRoutingAPI::get_destinations() const+0x22) [0x7fc42d04e4d2]<br>router /usr/lib64/mysqlrouter/private/libmysqlrouter_routing.so.1(+0x8e1bb) [0x7fc42d04f1bb]</pre><p>I still don’t understand how a network-heavy app can be disturbed so much by disk io. perhaps it checkpoints or logs something in critical path? but that’s now <a href="https://youtu.be/4G-YQA_bsOU">water under the bridge</a>.</p><h3>Filesystem IO-load and containerd</h3><p>Segue from the previous issue, for a long time we have been facing this situation:</p><ul><li>Growing amount of linux process/thread (tasks) on some k8s nodes</li><li>All of the extra ones are containerd-shim processes, with no related running containers</li></ul><p>Each shim is small, but the overall built-up causes system-wide degradation:</p><ul><li>atop, our favorite recording tool, starts failing with Malloc failed for compression buffer</li><li>Anything that scales per-process or per-cgroup has more useless work to do</li></ul><p>Here is an example which started running &amp; finished its work during the above deletion:</p><pre>## filtering out `collecting metrics` errors<br>$ sudo grep 513f9b55e96a /var/log/containerd.log.1|grep -v collecting|grep -o T.*<br>T14:14:36.809200001+07:00&quot; level=info msg=&quot;CreateContainer within sandbox \&quot;3ced0a60e406e5a4fff274f794947ff96129d15ccb8cabca3f3cc867511265da\&quot; for &amp;ContainerMetadata{Name:worker-5,Attempt:436,} returns container id \&quot;513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f\&quot;&quot;<br>T14:14:36.810770998+07:00&quot; level=info msg=&quot;StartContainer for \&quot;513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f\&quot;&quot;<br>T14:14:37.979214517+07:00&quot; level=info msg=&quot;StartContainer for \&quot;513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f\&quot; returns successfully&quot;<br>T14:44:43.486606295+07:00&quot; level=error msg=&quot;Failed to pipe stdout of container \&quot;513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f\&quot;&quot; error=&quot;read /proc/self/fd/62: file already closed&quot;<br>T14:44:52.439833260+07:00&quot; level=error msg=&quot;failed to handle container TaskExit event &amp;TaskExit{ContainerID:513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f,ID:513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f,Pid:211974,ExitStatus:0,ExitedAt:2023-09-06 07:44:42.439304235 +0000 UTC,XXX_unrecognized:[],}&quot; error=&quot;failed to stop container: context deadline exceeded: unknown&quot;<br>T14:47:02.214579151+07:00&quot; level=info msg=&quot;TaskExit event &amp;TaskExit{ContainerID:513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f,ID:513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f,Pid:211974,ExitStatus:0,ExitedAt:2023-09-06 07:44:42.439304235 +0000 UTC,XXX_unrecognized:[],}&quot;<br>T14:52:34.752879642+07:00&quot; level=info msg=&quot;RemoveContainer for \&quot;513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f\&quot;&quot;<br>T14:52:55.277595056+07:00&quot; level=info msg=&quot;RemoveContainer for \&quot;513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f\&quot;&quot;<br>T14:52:55.277675179+07:00&quot; level=error msg=&quot;RemoveContainer for \&quot;513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f\&quot; failed&quot; error=&quot;failed to set removing state for container \&quot;513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f\&quot;: container is already in removing state&quot;<br>T14:53:00.815222826+07:00&quot; level=info msg=&quot;RemoveContainer for \&quot;513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f\&quot; returns successfully&quot;<br><br>## it&#39;s still here a day later, and will be forever more<br>$ ps aux|grep 513f9b55e96a<br>root      211874  0.0  0.0 708400  7324 ?        Sl   Sep06   0:02 containerd-shim -namespace k8s.io -workdir /var/lib/containerd/io.containerd.runtime.v1.linux/k8s.io/513f9b55e96a531360dc266d6c13124c5b7a2e027552245912203ab96b60e98f -address /run/containerd/containerd.sock -containerd-binary /usr/bin/containerd -systemd-cgroup</pre><p>After 10s, from ExitedAt :44:42 to deadline exceeded :44:52, containerd gave up on removing the task, and the orphan shim stays around from then.</p><p>Again with ebpf in one hand and the flow around this area in another, we think that discarding/unmounting each container’s overlay filesystem is io-intensive as well as io-sensitive.</p><pre>## with https://github.com/tanelpoder/0xtools<br>$ sudo psn -G kstack<br> samples | avg_threads | comm                        | state                  | kstack<br>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br>       3 |        1.00 | (md*_resync)                | Disk (Uninterruptible) | kthread()-&gt;md_thread()-&gt;md_do_sync.cold.90()-&gt;msleep()<br>       2 |        0.67 | (containerd)                | Disk (Uninterruptible) | syscall_exit_to_user_mode()-&gt;exit_to_user_mode_prepare()-&gt;task_work_run()-&gt;cleanup_mnt()-&gt;deactivate_locked_super()-&gt;kill_anon_super()-&gt;generic_shutdown_super()-&gt;sync_filesystem()-&gt;ovl_sync_fs()-&gt;sync_filesystem()-&gt;__writeback_inodes_sb_nr()-&gt;wb_wait_for_completion()<br>       2 |        0.67 | (exe)                       | Disk (Uninterruptible) | __x64_sys_mount()-&gt;do_mount()-&gt;path_mount()-&gt;rwsem_down_write_slowpath()</pre><pre>## stack going back from sync_fs through to containerd process<br># sorry, i forgot the command used to get this, perhaps something in bcc-tools for stack snooping<br>  ffffffffc067aea1 b&#39;ext4_sync_fs&#39;<br>  ffffffff818f55b1 b&#39;sync_filesystem&#39;<br>  ffffffffc07811e9 b&#39;ovl_sync_fs&#39;<br>  ffffffff818f55b1 b&#39;sync_filesystem&#39;<br>  ffffffff818bc9c2 b&#39;generic_shutdown_super&#39;<br>  ffffffff818bcab4 b&#39;kill_anon_super&#39;<br>  ffffffff818bc37f b&#39;deactivate_locked_super&#39;<br>  ffffffff818df498 b&#39;cleanup_mnt&#39;<br>  ffffffff816aa276 b&#39;task_work_run&#39;<br>  ffffffff8170fdf9 b&#39;exit_to_user_mode_prepare&#39;<br>  ffffffff81e882c8 b&#39;syscall_exit_to_user_mode&#39;<br>  ffffffff8200008c b&#39;entry_SYSCALL_64_after_hwframe&#39;<br>  55eb400e0750     b&#39;syscall.Syscall&#39;<br>  55eb40209055     b&#39;github.com/containerd/containerd/mount.unmount&#39;<br>  55eb4020930d     b&#39;github.com/containerd/containerd/mount.UnmountAll&#39;<br>  55eb4020d404     b&#39;github.com/containerd/containerd/mount.WithTempMount.func2&#39;<br>  55eb4020c7a3     b&#39;github.com/containerd/containerd/mount.WithTempMount&#39;<br>  55eb407b6860     b&#39;github.com/containerd/containerd/oci.WithAdditionalGIDs.func1&#39;<br>  55eb40e199d2     b&#39;github.com/containerd/containerd/vendor/github.com/containerd/cri/pkg/containerd/opts.WithAdditionalGIDs.func1&#39;<br>  55eb407af412     b&#39;github.com/containerd/containerd/oci.ApplyOpts&#39;<br>  55eb4080196a     b&#39;github.com/containerd/containerd.WithSpec.func1&#39;<br>  55eb407e37f9     b&#39;github.com/containerd/containerd.(*Client).NewContainer&#39;<br>  55eb40f06bb1     b&#39;github.com/containerd/containerd/vendor/github.com/containerd/cri/pkg/server.(*criService).CreateContainer&#39;<br>  55eb40f25abd     b&#39;github.com/containerd/containerd/vendor/github.com/containerd/cri/pkg/server.(*instrumentedService).CreateContainer&#39;<br>  55eb40da0278     b&#39;github.com/containerd/containerd/vendor/k8s.io/cri-api/pkg/apis/runtime/v1alpha2._RuntimeService_CreateContainer_Handler.func1&#39;<br>  55eb4106167f     b&#39;github.com/containerd/containerd/vendor/github.com/grpc-ecosystem/go-grpc-prometheus.(*ServerMetrics).UnaryServerInterceptor.func1$<br>  55eb40d0bedd     b&#39;github.com/containerd/containerd/vendor/k8s.io/cri-api/pkg/apis/runtime/v1alpha2._RuntimeService_CreateContainer_Handler&#39;<br>  55eb40646676     b&#39;github.com/containerd/containerd/vendor/google.golang.org/grpc.(*Server).processUnaryRPC&#39;<br>  55eb4064a399     b&#39;github.com/containerd/containerd/vendor/google.golang.org/grpc.(*Server).handleStream&#39;<br>  55eb40657a1d     b&#39;github.com/containerd/containerd/vendor/google.golang.org/grpc.(*Server).serveStreams.func1.1&#39;<br>  55eb400c33e1     b&#39;runtime.goexit&#39;<br>    b&#39;containerd&#39; [1310]</pre><p>Cloudfoundry discussed <a href="https://www.cloudfoundry.org/blog/an-overlayfs-journey-with-the-garden-team/">this general problem</a>. CocCoc is following with great interest for newer containerd 1.6 LTS releases with fixes around handling overlay deletion. Some recent ones improved short-term, temporary mounts by marking them readonly. Containerd maintainers also made a <a href="https://github.com/containerd/containerd/pull/9004/files#diff-1d0d1c3863f35bb86ef37975c4e1a2062e6ca71e6f6a94dc385f8a3556284ddcR117">great reproduction</a> with strace fault-injection feature:</p><pre># step 2: strace to inject failpoint for the pod&#39;s shim<br>sudo strace -p $(pidof target-shim) --trace=umount2 -f --detach-on=execve -e inject=umount2:delay_enter=12s</pre><p>A more fundamental fix, using overlayfs volatile mode to alleviate whole-system load, is <a href="https://github.com/containerd/containerd/pull/4785">in design phase for now</a>.</p><p>We can’t do much else to mitigate this problem, due to the nature of php/nodejs/python applications with many loose files for each container, and the way we <a href="https://medium.com/coccoc-engineering-blog/our-journey-to-kubernetes-container-design-principles-is-your-back-bag-9166fc4736d2#957e">pass php files to nginx containers</a> in a shared emptyDir volume.</p><h3>Ghost hostPath files</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*brgd2BTC9Q5Wk7ikPDCe7A.png" /><figcaption>Source: <a href="https://www.snexplores.org/wp-content/uploads/2019/11/860_ghoststairs.png">https://www.snexplores.org/wp-content/uploads/2019/11/860_ghoststairs.png</a></figcaption></figure><p>Onward to the main title. as part of migrating on-host applications to k8s, we mount some files as hostPath volume into containers, and let host cronjobs write new data into them. for a time, this worked correctly:</p><pre>## manifest fragments<br><br>volumes:<br>- name: host-data<br>  hostPath:<br>    path: /tmp/data.txt<br>    type: File<br>containers:<br>- name: app<br>  volumeMounts:<br>  - name: host-data<br>    mountPath: /data.txt<br>    readOnly: true</pre><pre>## updating from host is reflected in container<br>host$ echo version1 &gt; /tmp/data.txt<br>app$ cat /data.txt<br>version1<br><br>host$ echo version2 &gt; /tmp/data.txt<br>app $ cat /data.txt</pre><p>But update to the cronjob code introduced a new phenomenon. On host, we can see the new data in the file, but k8s pods read only old data.</p><pre>host$ echo version3 &gt; /tmp/new.txt<br>host$ mv -f /tmp/new.txt /tmp/data.txt<br>host$ cat /tmp/data.txt<br>version3<br><br>app $ cat /data.txt<br>version2</pre><p>Oops! here is the reason:</p><pre>host$ stat /tmp/data.txt<br>  File: /tmp/data.txt<br>  Size: 9               Blocks: 8          IO Block: 4096   regular file<br>Device: 901h/2305d      Inode: 68812819    Links: 1<br><br>app $ stat /data.txt<br>  File: /data.txt<br>  Size: 9               Blocks: 8          IO Block: 4096   regular file<br>Device: 901h/2305d      Inode: 68812816    Links: 0<br>app $ mount|grep data<br>/dev/md1 on /data.txt type ext4 (ro,relatime,errors=remount-ro)</pre><p>hostPath is implemented as a bind-mount, so it’s “translated” to specific inode once at the pod setup phase. after mv rewrote the path to different inode, 68812816 is kept alive only by the mount namespace. It’s similar to a running process holding open a deleted file, giving DEL state in lsof listings. but this 0-link file is still reachable from host, via the container’s root/ under /proc:</p><pre>host$ sudo cat /proc/4185645/root/data.txt<br>version2</pre><p>Our mitigation for this one was changing hostPath up a level, to share the more-stable directory as volume instead. It would still break the same way if someone rename the directory, but it’s less likely. And further, we’ll work with people to share the data updates in a more robust way.</p><p>We hope you can have fun with the substrate under containers as we’re having here.</p><p><em>Originally published at </em><a href="https://nest.pijul.com/hdhoang/homes:main/WF6HOUZUSQPAW.DUAQA"><em>https://nest.pijul.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3dbe0c82b38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/mythical-0-link-readable-file-and-other-wonkeries-a3dbe0c82b38">Mythical 0-link, readable file and other wonkeries</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[concrete reproduction checks my thinking]]></title>
            <link>https://medium.com/coccoc-engineering-blog/concrete-reproduction-checks-my-thinking-1399c1144718?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/1399c1144718</guid>
            <dc:creator><![CDATA[hdhoang]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 04:45:25 GMT</pubDate>
            <atom:updated>2023-02-10T04:45:25.057Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>I almost reported an issue, right up to the point where bisecting doesn’t reproduce it reliably.</p><p>I run both kafka-minion <a href="https://github.com/redpanda-data/kminion/blob/v1.0.2/options/options.go#L63">v1, known under cloudhut org</a> and kminion <a href="https://github.com/redpanda-data/kminion/blob/v2.2.0/docs/reference-config.yaml#L13">v2, now under redpanda-data org</a> in parallel, in order to gauge how their metrics compare. (Truth be told, i wrote some suboptimal configs for kafka-minion, and the dashboards are too tied up with such config.) They use the same configuration via a systemd EnvironmentFile. That&#39;s the only method supported by kafka-minion whose Options are deserialized by struct definion:</p><pre>string `envconfig:&quot;KAFKA_TLS_CA_FILE_PATH&quot;`</pre><p>kminion can load config from some koanf providers: env and/or yaml. There&#39;s a transformation step to collapse yaml maps into a flat environment variable name:</p><pre>kafka.tls.caFilepath =&gt; `KAFKA_TLS_CAFILEPATH`</pre><p>Due to some recent issue, I wanted to build kminion from git repo. However, moving beyond <a href="https://github.com/redpanda-data/kminion/pull/147">commit a066</a> gave a weird error:</p><pre>&quot;caller&quot;: &quot;kminion/main.go:43&quot;,<br> &quot;msg&quot;: &quot;failed to parse config&quot;,<br> &quot;error&quot;: &quot;1 error(s) decoding:\n\n* &#39;kafka.tls.ca[0]&#39; expected type &#39;uint8&#39;, got unconvertible type &#39;map[string]interface {}&#39;, value: &#39;map[file:map[path:kafka_chain.pem]]&#39;&quot;,<br> &quot;stacktrace&quot;: &quot;main.main\n\t/home/me/github/kminion/main.go:43\nruntime.main\n\t/usr/lib/golang/src/runtime/proc.go:250&quot;</pre><p>map[file:map[path:kafka_chain.pem]] okay, I see my CA file here (actually the content is ISRG root CA). But what&#39;s this &#39;kafka.tls.ca[0]&#39; expected type &#39;uint8&#39;? Why is something plugging a map into an integer? At least I have a clean commit to write a bisect demo.</p><p>So I copied over the EnvironmentFile, removed anything about SASL authentication, exporter, set 0:9092 as bootstrap.servers for a quick recognizable failure once the app passes config parsing. And let git bisect run rip!</p><p>It pointed somewhere around the merge commit, as i expected. But then i had doubt, and set kafka-minion’s envvar in a shell:</p><pre>&gt; env KAFKA_TLS_CAFILEPATH=kafka_chain.pem kafka-minion<br>...snip...Connection refused</pre><p>eh, it got right up to trying connection? what happened to my bug?</p><p>As it happened, the envvar intended for kafka-minion ( KAFKA_TLS_CA_FILE_PATH) matches koanf auto-hydration(?), and it tried to construct this structure:</p><pre>kafka:<br> tls:<br>  ca:<br>   file:<br>    path: &quot;kafka_chain.pem&quot;</pre><p>because the new feature now accepts this structure:</p><pre>kafka:<br> tls:<br>  ca: MIIF....base64 DER data....</pre><p>Thus, the expected first element should have been a byte from the certificate.</p><p>With the new-issue tab firmly closed, I added to kminion’s systemd unit file:</p><pre>[Service]<br>UnsetEnvironment=KAFKA_TLS_CA_FILE_PATH</pre><p>As usual, I succeeded by nearly failing.</p><p><em>Originally published at </em><a href="https://hdhoang.substack.com/p/concrete-reproduction-checks-my-thinking"><em>https://hdhoang.substack.com</em></a><em> on August 21, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1399c1144718" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/concrete-reproduction-checks-my-thinking-1399c1144718">concrete reproduction checks my thinking</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Have you seen DNS TYPE0 CLASS256?]]></title>
            <link>https://medium.com/coccoc-engineering-blog/have-you-seen-dns-type0-class256-896b10af92fc?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/896b10af92fc</guid>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[hdhoang]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 04:44:56 GMT</pubDate>
            <atom:updated>2023-02-10T04:44:56.849Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>we run a recursive resolver for historical reason. these recent months, we started seeing messages like this in unbound.log, with different names:</p><pre>info: resolving cctv-api.cdn20.com.cd23f.com. TYPE0 CLASS256<br>info: resolving cctv-api.cdn20.com.chnc.cloudcsp.com. TYPE0 CLASS256<br>info: resolving cctv-api.wswebpic.com.chnc.cloudcsp.com. TYPE0 CLASS256<br>info: resolving overseatest.livehttp.speedcdns.com. TYPE0 CLASS256<br>info: resolving wangsu-1.ttyuyin.com.cdn20.com. TYPE0 CLASS256<br>info: resolving wangsu-3.ttyuyin.com.cdn20.com. TYPE0 CLASS256</pre><p>afaik we have no relationship with such infrastructure (CCTV in some Chinese cloud?). we blocked the most queried labels, and move on to other things. however i have a nagging question: what is that?</p><p>i still have no details about the chinese parties, but after some searching &amp; reproduction, i think there is a defect-attractor in DNS-packet construction. in order to avoid search-suffix behaviour, people write .-ending names in config, and some software will construct an invalid DNS query:</p><ul><li>haproxy, before 2020 <a href="https://github.com/haproxy/haproxy/issues/435">https://github.com/haproxy/haproxy/issues/435</a></li><li>gnupg dirmngr, in 2017 <a href="https://dev.gnupg.org/T3517#106524">https://dev.gnupg.org/T3517#106524</a></li><li>nongnu LWIP, in 2020 <a href="https://savannah.nongnu.org/bugs/?58473#comment3">https://savannah.nongnu.org/bugs/?58473#comment3</a></li></ul><p>the sequence is potentially like this:</p><ol><li>split name by .</li><li>for each item, construct ${length}${label} segments. the final empty label gets converted to its own 0x0 byte</li><li>concat the segments together, then append the empty label 0x0, regardless of previous step</li><li>append the DNS type &amp; class (always IN/0x1 for Internet)</li></ol><p>Thus, now we have a name that ends with \0\0 (or 00 00 in hexdump view). The question now appends usual Type A (00 01), Class IN (00 01), but those become misaligned:</p><pre>Okay:<br>03 ?? ?? ?? 00|  00 01|    00 01<br>ll  c  o  m . | TYPE A|CLASS  IN<br><br>Wrong:<br>03 ?? ?? ?? 00|  00 00|    01 00 01<br>ll  c  o  m . | TYPE 0|CLASS 256 FORMAT ERROR, i hope the server answer</pre><p>for more background, check out <a href="https://jvns.ca/blog/2022/09/12/why-do-domain-names-end-with-a-dot-/#in-a-dns-request-response-domain-names-don-t-have-a-trailing">jvns’ blog</a> or view responses in various formats with <a href="https://dnsinstitute.com/webdnsquery/">DNS institute tool</a>.</p><p>i also found a <a href="https://groups.google.com/g/comp.protocols.dns.bind/c/pIVLil7p8wA/m/Y0bxMyn5bI0J">different case from 2001</a>, where a (windows-based?) client sent TYPE &amp; CLASS as little-endian, not big-endian, resulting in TYPE256 CLASS256 query.</p><h3>Reproduction</h3><p>a single ping, comrade. just one, for range. — Marko Ramius (in The Hunt for Red October)</p><p>we can catch the non-Internet class queries with tcpdump/pcap filter udp port 53 and dns.query.class &gt; 1 , or wireshark/tshark dns.qry.class &gt; 1 . but i want to generate those wrong Questions on-demand, to observe and quote the various DNS servers’ log lines about them, as well as to put <a href="https://www.netmeister.org/blog/dns-rrs.html">all kind of TYPEs</a> in the Q and see what they look like.</p><pre>declare -a TYPES=(type1 type2 cname type6 mx txt aaaa srv dname type65 type255 caa)</pre><p>The core code is over here <a href="https://nest.pijul.com/hdhoang/homes:main/CHTEJVPDN5R2S.CUAAA">https://nest.pijul.com/hdhoang/homes:main/CHTEJVPDN5R2S.CUAAA</a>, with core function:</p><pre>fn naughty_question(qtype: Rtype) -&gt; Question&lt;Dname&lt;Vec&lt;u8&gt;&gt;&gt; {<br>    let name = Dname::vec_from_str(&quot;example.&quot;).unwrap();<br>    let mut bytes = name.into_octets();<br>    bytes.push(0);<br>    Question::new_in(<br>        // Safety: I want to do it wrong<br>        unsafe { Dname::from_octets_unchecked(bytes) },<br>        qtype,<br>    )<br>}<br>#[test]<br>fn it_is_different() {<br>    assert!(<br>        !Question::from((Dname::vec_from_str(&quot;example.&quot;).unwrap(), Rtype::Any))<br>            .eq(&amp;naughty_question(Rtype::Any))<br>    );<br>}</pre><p>i chose NLnet Labs’ <a href="https://lib.rs/crates/domain">domain crate</a>, because it is self-contained, and comes with a resolver. fortunately it exposes the above hand-off function to give users&#39; direct access to parsed domain bytes. i haven&#39;t wrapped my head around how to properly print out all kinds of answer data yet, so i resigned to asserting that the queried server ignores/refuses the bad questions. i can construct a bad Dname, pinky-promise to domain that it is good, and let it help me with the rest of DNS+UDP wrapping &amp; handling! an alternative would be trust-dns&#39;s proto &amp; client crates.</p><p>I queried some usual resource types against an unbound server:</p><pre>declare -a TYPES=(type1 type2 cname type6 mx txt aaaa srv dname type65 type255 caa)<br><br>for type in ${TYPES[*]}; do cargo r -q -- @unbound.address $type; done</pre><pre>A: b&quot;\0\0\x81\x85\0\x01\0\0\0\0\0\0\x07example\0\0\0\x01\0&quot;<br>NS: server ignored us, perhaps: Custom { kind: TimedOut, error: &quot;all timed out&quot; }<br>CNAME: b&quot;\0\0\x81\x85\0\x01\0\0\0\0\0\0\x07example\0\0\0\x05\0&quot;<br>SOA: b&quot;\0\0\x81\x85\0\x01\0\0\0\0\0\0\x07example\0\0\0\x06\0&quot;<br>MX: b&quot;\0\0\x81\x85\0\x01\0\0\0\0\0\0\x07example\0\0\0\x0f\0&quot;<br>TXT: b&quot;\0\0\x81\x85\0\x01\0\0\0\0\0\0\x07example\0\0\0\x10\0&quot;<br>AAAA: b&quot;\0\0\x81\x85\0\x01\0\0\0\0\0\0\x07example\0\0\0\x1c\0&quot;<br>SRV: b&quot;\0\0\x81\x85\0\x01\0\0\0\0\0\0\x07example\0\0\0!\0&quot;<br>DNAME: server ignored us, perhaps: Custom { kind: TimedOut, error: &quot;all timed out&quot; }<br>HTTPS: server ignored us, perhaps: Custom { kind: TimedOut, error: &quot;all timed out&quot; }<br>ANY: b&quot;\0\0\x81\x85\0\x01\0\0\0\0\0\0\x07example\0\0\0\xff\0&quot;<br>CAA: server ignored us, perhaps: Custom { kind: TimedOut, error: &quot;all timed out&quot; }</pre><p>“perhaps” is because, as we see below, the program sometimes doesn’t receive response data. unbound logs clear messages:</p><pre>unbound[1626:0] info: resolving example. TYPE0 CLASS256<br>unbound[1626:4] info: resolving example. TYPE0 CLASS512<br>unbound[1626:2] info: resolving example. TYPE0 CLASS1280<br>unbound[1626:3] info: resolving example. TYPE0 CLASS1536<br>unbound[1626:1] info: resolving example. TYPE0 CLASS3840<br>unbound[1626:5] info: resolving example. TYPE0 CLASS4096<br>unbound[1626:2] info: resolving example. TYPE0 CLASS7168<br>unbound[1626:4] info: resolving example. TYPE0 CLASS8448<br>unbound[1626:3] info: resolving example. TYPE0 CLASS9984<br>unbound[1626:3] info: resolving example. TYPE0 CLASS65280</pre><p>Here is tcpdump’s translation of the traffic:</p><pre>0+ [1au] Type0 (Class 256)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 256)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 512)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 512)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 1280)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 1280)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 1536)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 1536)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 3840)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 3840)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 4096)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 4096)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 7168)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 7168)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 8448)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 8448)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 9984)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 9984)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 16640)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 16640)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] Type0 (Class 65280)? example. (37)<br>0 FormErr 0/0/1 (36)<br>0+ Type0 (Class 65280)? example. (26)<br>0 Refused 0/0/0 (25)<br>0+ [1au] A (Class 256)? example. (37)<br>0 FormErr 0/0/1 (36)</pre><p>(you see why i said perhaps). this last one A (Class 256)? is from a CAA rtype. its high byte gets reinterpreted as type A again! but the Class 256 is never fixable, and the whole packet is malformed beyond repair anyhow.</p><p>i hope someone out there come across this &amp; figure out whatever is happening with the clients sending these queries.</p><p>i tested against ISC bind, but it says only:</p><pre>client: warning: client 4.5.6.7#33870: message parsing failed: unexpected end of input</pre><p>CoreDNS, NLnet NSD, systemd-resolved doesn’t log anything about these at all in my testing. of the cloudflare addresses, .1 and .3 replies quickly &amp; i can print the response, but i miss .2 traffic consistently:</p><pre>for s in 1 2 3; do cargo r -q -- @1.1.1.$s aaaa; done<br>AAAA: b&quot;\0\0\x81\x84\0\x01\0\0\0\0\0\0\x07example\0\0\0\x1c\0&quot;<br>AAAA: server ignored us, perhaps: Custom { kind: TimedOut, error: &quot;all timed out&quot; }<br>AAAA: b&quot;\0\0\x81\x84\0\x01\0\0\0\0\0\0\x07example\0\0\0\x1c\0&quot;</pre><p>nothing comes back from .2:</p><pre>0+ [1au] Type0 (Class 7168)? example. (37)<br>0 NotImp 0/0/0 (25)<br>0+ [1au] Type0 (Class 7168)? example. (37)<br>0+ [1au] Type0 (Class 7168)? example. (37)<br>0 NotImp 0/0/0 (25)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=896b10af92fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/have-you-seen-dns-type0-class256-896b10af92fc">Have you seen DNS TYPE0 CLASS256?</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuning & Monitoring MySQL (Part 1)]]></title>
            <link>https://medium.com/coccoc-engineering-blog/tuning-monitoring-mysql-part-1-58718fe9aaf4?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/58718fe9aaf4</guid>
            <dc:creator><![CDATA[Duc Nc]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 04:29:41 GMT</pubDate>
            <atom:updated>2022-04-24T04:29:41.616Z</atom:updated>
            <content:encoded><![CDATA[<p>MySQL is a popular open-source database application that stores and structures data in a way that is meaningful and readily accessible.</p><p>Poorly-managed MySQL server can act as a potent killer of the overall performance. With large applications, the sheer amount of data can lead to many unexpected problems. Therefore, it is crucial to optimize the MySQL parameters.</p><p><strong>I. Storage Engine Overview</strong></p><p>Storage engines are MySQL components that handle the SQL operations for different table types. They perform actions on the underlying data that is maintained at the physical server level. In short, they decide how and what will be stored on disk.</p><p>The MySQL pluggable storage engine architecture enables a database professional to select a specialized storage engine for a particular application while being completely shielded from managing any specific application coding requirements. Although there are different capabilities across different storage engines, there is no need for the developers to be aware of these differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/0*-f1RTvcJcTPxK-Sh" /><figcaption><strong>Execution path of a query</strong></figcaption></figure><p>InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data. InnoDB row-level locking increases multi-user concurrency and performance. It stores data in clustered indexes to reduce I/O for common queries based on primary keys. To maintain data integrity, InnoDB also supports FOREIGN KEY referential-integrity constraints.</p><p>InnoDB is a general-purpose storage engine that balances high reliability and high performance. InnoDB has been the default storage engine since MySQL 5.5 and it is much more frequently used than any other storage engine. That’s why it should be configured carefully.</p><p><strong>II. InnoDB Components</strong></p><p>Before getting our hands dirty, we should have a solid understanding of what is about to be configured.</p><p>1. The Buffer Pool</p><p>Every data in InnoDB is measured by a page. A page has a default size of 16 KB, which can be changed afterward. It will try to hold as many records as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/0*i9yYUWRdM8wQq2GU" /><figcaption><strong>The buffer pool is a linked list of pages</strong></figcaption></figure><p>The buffer pool is an area in main memory where InnoDB caches table and index data as it is accessed. The buffer pool permits frequently used data to be accessed directly from memory, which greatly speeds up query.</p><p>The buffer pool is managed as a list using a variation of the LRU algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*YkM4iUMx1DLKrI9w.png" /></figure><p>When room is needed to add a new page to the buffer pool, the least recently used page is evicted and a new page is added to the middle of the list. This midpoint insertion strategy treats the list as two sublists:</p><ul><li>At the head, a sublist of young pages that were accessed recently</li><li>At the tail, a sublist of old pages that were accessed less recently</li></ul><p>The algorithm keeps frequently used pages in the new sublist. The old sublist contains less frequently used pages; these pages are candidates for eviction.</p><p>2. Log Buffer &amp; Redo Log</p><p>The redo log is a write ahead log of changes applied to contents of data pages. It provides durability for all changes applied to the pages. In case of crash, it is used to recover modifications to pages that were modified but have not been flushed to disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/0*3SRzibm9v3la_-s3" /><figcaption><strong>The relation between the log buffer and the redo log</strong></figcaption></figure><p>By default, the redo log is physically represented on disk by two files named ib_logfile0 and ib_logfile1. MySQL writes to the redo log files in a circular fashion. Data in the redo log is encoded in terms of records affected; this data is collectively referred to as redo. The passage of data through the redo log is represented by an ever-increasing LSN (Log Sequence Number) value.</p><p>The log buffer is the memory area that holds data to be written to the log files on disk. The contents of the log buffer are periodically flushed to disk. A log buffer enables transactions to run without the need to write redo log data to disk before the transactions commit.</p><p><strong>III. InnoDB Settings</strong></p><p>1. Buffer Pool Size</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*RPxSKc7ugTjECg_N" /><figcaption><strong>The buffer pool size varies in chunks</strong></figcaption></figure><p>When the InnoDB buffer pool is large, many data requests can be satisfied by retrieving from memory. You might encounter bottlenecks from multiple threads trying to access the buffer pool at once.</p><p>MySQL enables multiple buffer pools by default to minimize this contention. Each page that is stored in or read from the buffer pool is assigned to one of the buffer pools randomly, using a hashing function. Each buffer pool manages its own free lists, flush lists, LRUs, and all other data structures connected to a buffer pool.</p><blockquote>innodb_buffer_pool_size = innodb_buffer_pool_instances * innodb_buffer_pool_chunk_size</blockquote><p>2. Mid-point Insertion</p><p>Rather than using a strict LRU algorithm, InnoDB uses a technique to minimize the amount of data that is brought into the buffer pool and never accessed again. The goal is to make sure that frequently accessed pages remain in the buffer pool</p><p>You can control the insertion point in the LRU list and choose whether InnoDB applies the same optimization to blocks brought into the buffer pool by table or index scans.</p><p>For example, when scanning large tables that cannot fit entirely in the buffer pool, setting the insertion point to a small value keeps the data that is only read once from consuming a significant portion of the buffer pool.</p><blockquote>innodb_old_blocks_pct</blockquote><p>3. Preload</p><p>After restarting a busy server, there is typically a warmup period with steadily increasing throughput, as disk pages that were in the buffer pool are brought back into memory (as the same data is queried, updated, and so on).</p><p>To reduce the warmup period after restarting the server, InnoDB saves a percentage of the most recently used pages for each buffer pool at server shutdown and restores these pages at server startup.</p><p>The ability to restore the buffer pool at startup shortens the warmup period by reloading disk pages that were in the buffer pool before the restart rather than waiting for DML operations to access corresponding rows. Also, I/O requests can be performed in large batches, making the overall I/O faster. Page loading happens in the background, and does not delay database startup.</p><p>Also, the cost for saving pages on disk is quite small. I have tested storing ~300 MB buffer pool in the memory and it only took 100 MB.</p><blockquote>innodb_buffer_pool_dump_pct</blockquote><p>4. Buffer Pool Utilization</p><p>Trust me. I will not suggest you to tune innodb_buffer_pool_size up to 80% of physical memory just like <strong>every other blog </strong>about MySQL tuning.</p><p>My workload is different from your workload, so are theirs. Why we have to assign most of our RAM to a MySQL server which only run some simple queries?</p><p>Then how do we know how much memory is suitable? The answer is analyzing InnoDB Monitor Output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*JKj5xdIuQk7m1KpimW_dsA.png" /></figure><p>The average of buffer pool hit rate will tell so much about how your buffer pool is doing. If the value is low, which means the recently accessed pages were not in the buffer pool. In this case, the MySQL server has to fetch the corresponding page into the buffer pool.</p><p>Also, we can make use of youngs/s and non-youngs/s. These values give information about how “green” your buffer pool is. If a page already in the buffer pool is accessed, that page will be made young. In contrast, a page which is evicted without being made young is considered non-young. We should keep youngs/s high and non-youngs/s as low as possible.</p><p>In short, if the value of buffer pool hit rate, young-making rate close to 100%, youngs/s is high, everything about non-young is low then your buffer pool is good to go. If not, you can increase the performance by making changes to Buffer Pool Size and Mid-point Insertion.</p><blockquote>N youngs/s, N non-youngs/s<br>Buffer pool hit rate N / 1000, young-making rate N / 1000 not N / 1000</blockquote><p>5. Redo Log Size</p><p>Generally, the combined size of the log files should be large enough that the server can smooth out peaks and troughs in workload activity. When InnoDB has written the redo log files full, it must write the modified contents of the buffer pool to disk in a checkpoint. Small redo log files cause many unnecessary disk writes.</p><blockquote>innodb_log_file_size * innodb_log_files_in_group</blockquote><p>6. Log Buffer Size</p><p>A large log buffer enables large transactions to run without the need to write redo log data to disk before the transactions commit. Thus, if you have transactions that update, insert, or delete many rows, consider increasing the size of the log buffer saves disk I/O.</p><blockquote>innodb_log_buffer_size</blockquote><p>7. Log Buffer &amp; Redo Log Utilization</p><p>I created a test metrics to monitor the buffer log and the redo log as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/0*sDx0j4cVTWWT89Px" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*DoClqFA-oQrGjAxc" /></figure><p>I use the same workload while making changes to innodb_buffer_log_size and innodb_log_file_size to see how it goes. There are 4 cases:</p><ul><li>innodb_log_buffer_size = 1G (high), innodb_log_file_size = 500M (high) → 15:55–16:04 (9 mins)</li><li>innodb_log_buffer_size = 256K (low), innodb_log_file_size = 500M (high) → 16:13–16:27 (14 mins)</li><li>innodb_log_buffer_size = 1G (high), innodb_log_file_size = 1K (low) → 16:35–17:36 (59 mins)</li><li>innodb_log_buffer_size = 256K (low), innodb_log_file_size = 1K (low) → 18:00–18:51 (51 mins)</li></ul><p>After observing, we can clearly see that the performance greatly reduces because of small innodb_log_file_size. Thus, this one should be configured carefully.</p><p>On the other hand, despite being little, innodb_log_buffer_size doesn’t slow the server down too much (This quite surprises me since it’s believed that writing to disk is much slower than on memory).</p><p>A little explanation about monitoring value:</p><ul><li>Log_Buffer = Log sequence number — Log flushed up to: how much the log buffer can hold before flushing</li><li>Redo_Log = Log flushed up to — Pages flushed up to: how much the redo log can hold before writing checkpoint</li><li>Checkpoint = Pages flushed up to — Last checkpoint at: the speed MySQL flushes dirty pages from memory to disk, truncates logs to make more space in redo log</li><li>Logs_Per_Sec, as its name, log i/o’s/second: how many logs the server has to write to disk.</li></ul><p>Explanation about metrics:</p><ul><li>Case 1: The combination of large log buffer and large log file gives the server the best performance since it can hold so much physical changes to the table and merge into a big one before flushing logs (Log_Buffer), flushing modified pages (Redo_Log) and writing checkpoint (Checkpoint)</li><li>Case 2: Despite the fact that Log Buffer is similar to case 1, the server has to flush more logs to disk to make more free space for the log buffer (Logs_Per_sec)</li><li>Case 3: Every time the server writes a checkpoint, every other processes is blocked till the checkpoint is done. That’s why there is a huge drop in performance</li><li>Case 4: Similar to case 3, but there is a bit more Logs_Per_Sec because we made change to the log buffer.</li></ul><p>My suggestion for tuning parameters: After observing Redo_Log / Log_Buffer / Checkpoint, we could determine if the innodb_log_file_size is too low. If the value is low → raise innodb_log_file_size. Then, Logs_Per_Sec would tell us to configure innodb_log_buffer_size.</p><blockquote>Log sequence number N<br>Log flushed up to N<br>Pages flushed up to N<br>Last checkpoint at N<br>N log i/o’s/second</blockquote><p><strong>IV. Common Pitfalls</strong></p><p>Even experienced people can make mistakes that can cause a lot of trouble. So before blindly applying the recommendations of this post, please keep in mind the following items:</p><ul><li>Change one setting at a time! This is the only way to estimate if a change is beneficial.</li><li>Most settings can be changed at runtime with SET GLOBAL. It is very handy and it allows you to quickly revert the change if it creates any problem. But in the end, you want the setting to be adjusted permanently in the configuration file.</li><li>A change in the configuration is not visible even after a MySQL restart? Did you use the correct configuration file? Did you put the setting in the right section? (all settings in this post belong to the [mysqld] section)</li><li>The server refuses to start after a change: did you use the correct unit? For instance, innodb_buffer_pool_size should be set in bytes.</li><li>Do not allow duplicate settings in the configuration file. If you want to keep track of the changes, use version control.</li><li>Don’t do naive math, like “my new server has 2x RAM, I’ll just make all the values 2x the previous ones”.</li></ul><p><strong>V. Conclusion</strong></p><p>MySQL itself is already a big topic. Studying about its components, operations and tuning the parameters require a significant investment of time. While it’s not possible to cover all the important variables in one article, you can take this as a good start of making your MySQL server a better configured one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58718fe9aaf4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/tuning-monitoring-mysql-part-1-58718fe9aaf4">Tuning &amp; Monitoring MySQL (Part 1)</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best practices for minimize vulnerabilities for Microservice]]></title>
            <link>https://medium.com/coccoc-engineering-blog/best-practices-for-minimize-vulnerabilities-for-microservice-7765b499167f?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/7765b499167f</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Lambq]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 03:57:00 GMT</pubDate>
            <atom:updated>2022-04-24T03:57:00.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Monolitic and Microservice</h3><blockquote>The monolithic architecture is considered to be a traditional way of building applications. A monolithic application is built as a single and indivisible unit. Usually, such a solution comprises a client-side user interface, a server side-application, and a database.</blockquote><p><a href="https://www.n-ix.com/microservices-vs-monolith-which-architecture-best-choice-your-business/">https://www.n-ix.com/microservices-vs-monolith-which-architecture-best-choice-your-business/</a></p><p>It is unified and all the functions are managed and served in one place. Normally, monolithic applications have one large code base and lack modularity. If developers want to update or change something, they access the same code base. So, they make changes in the whole stack at once.</p><figure><img alt="Monolithic applications have one large code base and lack modularity. If developers want to update or change something, they access the same code base" src="https://cdn-images-1.medium.com/max/357/0*Cgrt__L9-F1PHdVX.png" /><figcaption>Monolithic applications have one large code base and lack modularity. If developers want to update or change something, they access the same code base. (Image source: Udemy)</figcaption></figure><p>Monoliths tend to be suitable for small-scale projects. With the application of monolith model, the benefits can be mentioned as follows:</p><ul><li>The development process is simple and direct, centralized management and basic development steps will not be repeated.</li><li>Effort for development is minimized: all development is on the same project. Development flow is as simple as submitting changes, reviewing, merging code and continuing.</li></ul><p><strong>Weaknesses of the Monolithic Architecture</strong></p><ul><li>Understanding. When a monolithic application scales up, it becomes too complicated to understand. Also, a complex system of code within one application is hard to manage.</li><li>Making changes. It is harder to implement changes in such a large and complex application with highly tight coupling. Any code change affects the whole system so it has to be thoroughly coordinated. This makes the overall development process much longer.</li><li>Scalability. You cannot scale components independently, only the whole application.</li><li>New technology barriers. It is extremely problematic to apply a new technology in a monolithic application because then the entire application has to be rewritten.</li></ul><p><strong>Why Microservices and Microservice Vulnerabilities</strong></p><p>In addition to the monolithic model mentioned above, there is currently another architecture that is receiving a lot of attention, which is microservices. Microservices refer to the relatively small, independent development process that divides the system into services. Each of these services has its own logic, its own responsibility, and can be deployed separately. The concept of microservices also refers to the trend of separating the architecture into loose coupling services, that is, these services will have a loose relationship with each other and the service relationship will be in a certain context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xPAjVOYjJCipjIdI.png" /><figcaption>By decoupling, splitting and managing we can reduce the complexity of the system, make it quick and easy to manage, and reflect change accurately (Image source: <a href="http://vodkaboris.com/">http://vodkaboris.com/</a>)</figcaption></figure><h3><strong>2. Four securitys best practices for Microservices</strong></h3><p><strong>2.1 Network Policy</strong></p><blockquote>If you want to control traffic flow at the IP address or port level (OSI layer 3 or 4), then you might consider using Kubernetes NetworkPolicies for particular applications in your cluster. NetworkPolicies are an application-centric construct which allow you to specify how a <a href="https://kubernetes.io/docs/concepts/workloads/pods/">pod</a> is allowed to communicate with various network “entities” (we use the word “entity” here to avoid overloading the more common terms such as “endpoints” and “services”, which have specific Kubernetes connotations) over the network. NetworkPolicies apply to a connection with a pod on one or both ends, and are not relevant to other connections — Official Kubernetes Definition</blockquote><p>The entities that a Pod can communicate with are identified through a combination of the following 3 identifiers:</p><ul><li>Other pods that are allowed (exception: a pod cannot block access to itself)</li><li>Namespaces that are allowed</li><li>IP blocks (exception: traffic to and from the node where a Pod is running is always allowed, regardless of the IP address of the Pod or the node)</li></ul><p>NetworkPolicy is a resource in k8s, so we will define it under the Yaml file and will control network traffic in (Ingress) and out (Egress).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*MoGg4Vk8fEIY3AcYS4ijxw.png" /><figcaption>Example Parten</figcaption></figure><p>File template .yaml network policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*nhQX4bI4KBOW-LN2eLVSEg.png" /></figure><p><strong>2.2 Rate Limit</strong></p><p>Suppose our system receives thousands of requests, but among them can only handle hundreds of requests / s, for example, and the rest of the requests fail (because the system CPU is overloaded and cannot handle it). To solve this problem, the Rate Limiting mechanism was born. Its purpose is only to allow receiving a certain number of requests in 1 unit of time. If it is too much, it will return an error response. Some common examples in Rate Limiting are:</p><ul><li>Each user we only allow to send 100 requests/s. If it is exceeded, an error response will be returned.</li><li>Each user is only allowed to enter the wrong credit card 3 times in 1 day</li><li>Each IP address can only create 2 accounts in 1 day.</li></ul><p><strong>Some commonly used algorithms?</strong></p><blockquote>When too many packets are present in the network it causes packet delay and loss of packet which degrades the performance of the system. This situation is called congestion.</blockquote><blockquote>The network layer and transport layer share the responsibility for handling congestions. One of the most effective ways to control congestion is trying to reduce the load that transport layer is placing on the network. To maintain this, the network and transport layers have to work together</blockquote><p>The implementation of rate limit will be done by algorithms, with this topic I will overview how it works, some basic theories of some common algorithms used to implement rate limit.</p><ul><li>Leaky bucket</li></ul><p>When too many packets are present in the network it causes packet delay and loss of packet which degrades the performance of the system. This situation is called congestion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*3GcBzjqILvDOiW9W3yfwrw.png" /><figcaption>Image Source: <a href="https://viblo.asia/">https://viblo.asia/</a></figcaption></figure><p>The network layer and transport layer shares the responsibility for handling congestions. One of the most effective ways to control congestion is trying to reduce the load that transport layer is placing on the network. To maintain this, the network and transport layers have to work together.<br>The algorithm works similarly to the way an actual leaky bucket holds water: The leaky bucket takes data and collects it up to a maximum capacity. Data in the bucket is only released from the bucket at a set rate and size of packet. When the bucket runs out of data, the leaking stops. If incoming data would overfill the bucket, then the packet is considered to be non-conformant and is not added to the bucket. Data is added to the bucket as space becomes available for conforming packets.</p><ul><li>Token bucket</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/0*RiNMry-D2IWXrKGk.png" /><figcaption>Image source: <a href="https://developpaper.com/microservice-technology-stack-traffic-shaping-algorithm-service-fusing-and-degradation/">https://developpaper.com/microservice-technology-stack-traffic-shaping-algorithm-service-fusing-and-degradation/</a></figcaption></figure><blockquote>“The leaky bucket algorithm enforces output patterns at the average rate, no matter how busy the traffic is. So, to deal with the more traffic, we need a flexible algorithm so that the data is not lost. One such approach is the token bucket algorithm.” — <a href="https://www.faceprep.in/computer-networks/computer-networks--congestion-control/">https://www.faceprep.in/computer-networks/computer-networks--congestion-control/</a></blockquote><p>In first figure the bucket holds two tokens, and three packets are waiting to be sent out of the interface. In second figure two packets have been sent out by consuming two tokens, and 1 packet is still left.</p><p>When compared to Leaky bucket the token bucket algorithm is less restrictive that means it allows more traffic. The limit of busyness is restricted by the number of tokens available in the bucket at a particular instant of time.</p><p>The implementation of the token bucket algorithm is easy − a variable is used to count the tokens. For every t seconds the counter is incremented and then it is decremented whenever a packet is sent. When the counter reaches zero, no further packet is sent out.</p><ul><li>Timing Window</li></ul><p>The algorithm itself is pretty simple without any analogy but let’s start with one anyway. Imagine a moving train. There’s a gateway and at any moment, people only can board one wagon (Yep, people are boarding a moving train, nothing weird).</p><p>Assume that the window of boarding for each wagon is 1 minute. So if a wagon gets full you need to wait for up to a minute for the next wagon.</p><p>In this analogy, the train is the time! The time is always moving forward and in each time frame, we have a fixed window of passing through.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKj_-DnDK9qERLwQ_j-LvA.png" /><figcaption>Image source: <a href="https://itzone.com.vn/en/article/design-api-rate-limiting/">https://itzone.com.vn/en/article/design-api-rate-limiting/</a></figcaption></figure><ul><li>Sliding Window Log</li></ul><p>Sliding Window is an improved algorithm from Sliding Window Log. We trade accuracy for speed and memory (less save, less query). We don’t log per request, we just log the count per time period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9SxlObK3wbG6Fl9m.png" /><figcaption>Image source: <a href="https://www.techtarget.com/searchnetworking/definition/sliding-windows">https://www.techtarget.com/searchnetworking/definition/sliding-windows</a></figcaption></figure><p>Some disadvantages:</p><ul><li>This method is very accurate, however, it also comes with some disadvantages</li><li>Consumes a lot of memory because you have to log the entire request,<br>Consumes resources because of having to log in every request</li><li>Running may be slow, because each time we have a request, we have to query to count the number of requests in a certain period of time to see if the request is received or not.</li><li>Imagine a system of about 1 million users, every day they send 1000 requests, we have to log nearly 1 billion events per day.</li></ul><p>2.3 Encryption Data Secret at Rest</p><blockquote>“Data at rest is data that has reached a destination and is not being accessed or used. It typically refers to stored data and excludes data that is moving across a network or is temporarily in computer memory waiting to be read or updated. Data at rest can be archival or reference files that are rarely or never changed. It can also be data that is subject to regular but not constant change”</blockquote><p><a href="https://www.techtarget.com/searchstorage/definition/data-at-rest">https://www.techtarget.com/searchstorage/definition/data-at-rest</a></p><p>Hackers are an ever-present threat to data at rest. To keep unauthorized people from accessing, stealing or altering this data, security measures such as encryption and hierarchical password protection are commonly used. For some types of data, laws mandate specific security measures.</p><p>Data at rest is relatively easy to secure compared with data in motione and data in use.</p><p>Some best practices for securing data at rest include the following:</p><ul><li>Data classification</li><li><strong>Data encryption (this blog)</strong></li><li>Data federation</li><li>Data tokenization</li><li>Hierarchical password protection</li></ul><p>Data Encryption</p><p>We can get secret from K8s-etcd from access through API-server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkQ1PDe6g8LR_7b6fc4wTA.png" /></figure><p>Result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*Fzb51atsmt74i65M3TGljw.png" /></figure><p>Use <strong>Encrypting Secret Data at Rest </strong>to encrypt data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*J6-79g5YLELua65171TjMg.png" /></figure><p>The kube-apiserver process accepts an argument --encryption-provider-config that controls how API data is encrypted in etcd. The configuration is provided as an API named <a href="https://kubernetes.io/docs/reference/config-api/apiserver-encryption.v1/">EncryptionConfiguration</a>.</p><p>For more detailed information: <a href="https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/">https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/</a></p><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75jJ8GFaDJFmmf5-VCO-BA.png" /></figure><p>2.4 Scan configuration (kube-bench)</p><ul><li>CIS</li></ul><p>“CIS is an independent, nonprofit organization with a mission to create confidence in the connected world.”</p><p>The Center for Internet Security (CIS) is a nonprofit organization, formed in October, 2000. Its mission is to make the connected world a safer place by developing, validating, and promoting timely best practice solutions that help people, businesses, and governments protect themselves against pervasive cyber threats. The organization is headquartered in East Greenbush, New York, with members including large corporations, government agencies, and academic institutions.</p><p>CIS employs a closed crowdsourcing model to identify and refine effective security measures, with individuals developing recommendations that are shared with the community for evaluation through a consensus decision-making process. At the national and international level, CIS plays an important role in forming security policies and decisions by maintaining the CIS Controls and CIS Benchmarks, and hosting the Multi-State Information Sharing and Analysis Center (MS-ISAC) and the Elections Infrastructure Information Sharing and Analysis Center (EI-ISAC).</p><p>CIS Benchmarks are a collaboration of the Consensus Community and CIS SecureSuite members (a class of CIS members with access to additional sets of tools and resources).</p><p>The Consensus Community is made up of experts in the field of IT security who use their knowledge and experience to help the global Internet community. CIS SecureSuite members are made up of several different types of companies ranging in size, including government agencies, colleges and universities, nonprofits, IT auditors and consultants, security software vendors and other organizations.</p><p>CIS Benchmarks and other tools that CIS provides at no cost allow IT workers to create reports that compares their system security to universal consensus standard. This fosters a new structure for internet security that everyone is accountable for that is shared by top executives, technology professionals and other internet users throughout the globe. Further, CIS provides internet security tools with a scoring feature that rates the configuration security of the system at hand.</p><p><a href="https://www.cisecurity.org/benchmark">https://www.cisecurity.org/benchmark</a></p><ul><li>Kube-bench</li></ul><p>kube-bench is a tool that checks whether Kubernetes is deployed securely by running the checks documented in the<strong> </strong><a href="https://www.cisecurity.org/benchmark/kubernetes/"><strong>CIS Kubernetes Benchmark</strong></a><strong>.</strong></p><p>Tests are configured with YAML files, making this tool easy to update as test specifications evolve. By default, kube-bench will determine the test set to run based on the Kubernetes version running on the machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*o92T0bfERPgrUl-JVxv-lw.png" /><figcaption>Result from kube-bench configure scan</figcaption></figure><p><a href="https://github.com/aquasecurity/kube-bench">https://github.com/aquasecurity/kube-bench</a></p><p><strong>3. Summary</strong></p><p>There are many security practices in the microservice system, above I present some new approaches to increase security. Securing the system of connections and services in microservices in general and kubernetes in particular is very important. Knowing the security will help us to ensure the system runs stably and operates safely.</p><p><strong>Reference</strong>:</p><p><a href="https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/">https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/</a></p><p><a href="https://viblo.asia/p/api-rate-limiting-la-gi-va-mot-so-thuat-toan-hay-dung-bJzKmPyr59N">https://viblo.asia/p/api-rate-limiting-la-gi-va-mot-so-thuat-toan-hay-dung-bJzKmPyr59N</a></p><p><a href="https://www.n-ix.com/microservices-vs-monolith-which-architecture-best-choice-your-business/">Microservices vs Monolith: which architecture is the best choice for your business?</a></p><p><a href="https://itzone.com.vn/en/article/design-api-rate-limiting/">https://itzone.com.vn/en/article/design-api-rate-limiting/</a></p><p><a href="https://developpaper.com/microservice-technology-stack-traffic-shaping-algorithm-service-fusing-and-degradation/">https://developpaper.com/microservice-technology-stack-traffic-shaping-algorithm-service-fusing-and-degradation/</a></p><p><a href="https://www.techtarget.com/searchnetworking/definition/sliding-windows">https://www.techtarget.com/searchnetworking/definition/sliding-windows</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7765b499167f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/best-practices-for-minimize-vulnerabilities-for-microservice-7765b499167f">Best practices for minimize vulnerabilities for Microservice</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure container runtime]]></title>
            <link>https://medium.com/coccoc-engineering-blog/secure-container-runtime-cb4eb75e9dcf?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/cb4eb75e9dcf</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[container-security]]></category>
            <dc:creator><![CDATA[Tuấn Anh Phạm]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 03:37:37 GMT</pubDate>
            <atom:updated>2022-04-27T07:07:32.896Z</atom:updated>
            <content:encoded><![CDATA[<p>Container is a great tech, but it has problems with security: weak isolation. To cover for it, our company has a policy that enforce all containers in our k8s cluster must run as non-root users. However, there ‘s still some exceptions that need root privileges, like our mail relay pod using postfix. To let those services run on our k8s while maintaining our security policies, we need a tighter isolation container runtime.</p><p>While the new container runtime has better isolation than runc — our current runtime, it also must satisfy:</p><ul><li>Easy to integrated to our current infras<br>The new container runtime must follow OCI standard.</li><li>Keep our current workflows and templates<br>We could use the current k8s manifests and workflows with minimum changes to get the new runtime works.</li><li>Ensure the performance and compatibility<br>Of course, there are always trade-offs while tightening security. However, it ‘s meaningless if the service failed to run or the performance is drastically reduced.</li></ul><p>At first, we had 3 candidates, picked up by our boss: kata container, gvisor and firecracker. However, I removed firecracker from the list because it ‘s actually not container runtime. It ‘s VMM (virtual machine monitor), which is optimized to run serverless functions. It ‘s not follow OCI standards, therefore there ‘s no easy way to make it work with our k8s. That leave us gvisor and firecracker to choose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*C3wU21GaU8RTf5TBvOpNJA.png" /></figure><h3>Gvisor</h3><p>Gvisor is an application kernel, written in Go. Its runtime is called runsc and follows OCI standard making it easy to integrate with k8s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*FpX3wd6YSVDFnX7Pgf1w3Q.png" /></figure><p>Gvisor creates a sandbox to run containers in the user-space kernel, implement a part of Linux system calls. The containers, instead of running on host kernel, will run on a separated gvisor kernel, which is very similar to a virtual machine. However, unlike VM, gvisor doesn’t need translation through virtual hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*Arm6k4cnVfzuvYDuusXRSA.png" /><figcaption><a href="https://gvisor.dev/docs/">https://gvisor.dev/docs/</a></figcaption></figure><p>Because gvisor create a filter between application and kernel, it intercepts with system calls, and will cause performance degradation in case of heavy system calls.</p><p>At the time of this post, gvisor provides an environment equivalent to Linux4.4 with limited system calls so incompatibilities may occur.</p><h3>Kata Container</h3><p>Is a combination of Clear Containers (intel) and runv (Hyper.sh) and follow OCI standard, so it could be seamlessly plugged into k8s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*0sQdQNyIyLYOfieNmsppBg.png" /></figure><p>Kata container make use of virtualization technology to secure containers, by putting containers into a light-weight Virtual machine. The machine image is optimized to run containers, with only needed virtual devices and software to run containers. Because of that, you could get isolation of VM on containers — the best of both worlds.</p><p>Kata container works by start a VM with standard linux kernel. Inside the VM, an agent will be used to manage the containers using libcontainer, kata runtime will manage the agent via vsock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1L7kt6frgEFej2nwg4Q85g.jpeg" /><figcaption><a href="https://katacontainers.io/learn/">https://katacontainers.io/learn/</a></figcaption></figure><p>The downside is it need some resources overhead for each VM. We could reduce the OS memory footprint by enabling KSM (kernel samepage merging), with the cost of some CPU power in case we have multiple kata pods running on the same host.</p><h3>Comparison</h3><p>Based on what we know, we could come to conclusions:</p><ul><li>Both Gvisor and kata provide better isolation than runc.</li><li>Kata should has better compatibility than gvisor.</li><li>Both should have little overhead on CPU/Mem but Gvisor should have smaller footprint over kata (on a single pod), and may boot faster.</li><li>Gvisor may have reduced performance on syscall heavily.</li></ul><p>At the time of this post, kata is a better candidate for runc replacement to run untrusted workload on production environment. One more thing to consider is kata needs virtualization enabled to run (CPU flag vmx for intel, or svm for amd), which is not a problem for our system, as our k8s nodes are bare-metal. However, you need nested virtualization enabled if you place your k8s nodes in VMs and that comes with restrictions and performance penalty. For more infos about nested virtualization: <a href="https://cloud.google.com/compute/docs/instances/nested-virtualization/overview">google cloud docs</a></p><h4>Benchmark</h4><p>To compare the performance of kata and gvisor, I created a simple sysbench container and start the container with 3 runtime in turn on the same host.</p><pre>limits:<br>  cpu: 4<br>  memory: 4000Mi<br>Test commands:<br>  sysbench cpu --threads=4 run --cpu-max-prime=20000<br>  sysbench memory run</pre><p>The result shows that for cpu bench, all 3 runtime has the same score (with very small margin, which we could ignore). That ‘s understandable, because sysbench evaluates cpu power by calculate the prime numbers smaller or equal to cpu-map-prime parameter. It ‘s arithmetic calculation and involved almost no syscalls .</p><pre>cpu benchmark results:<br>  runc:  13619<br>  kata:  13219<br>  gvisor:13761</pre><p>At the memory benchmark, runc performance is higher than kata and gvisor about 13%</p><pre>memory benchmark results:<br>  runc:  42132608<br>  kata:  37118940<br>  gvisor:36232345</pre><p>I found a result of <a href="https://object-storage-ca-ymq-1.vexxhost.net/swift/v1/6e4619c416ff4bd19e1c087f27a43eea/www-assets-prod/presentation-media/kata-containers-and-gvisor-a-quantitave-comparison.pdf">real-life benchmark</a> between runc, gvisor and kata:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*9wxlMqYZ9TkHTZB3XTlifg.png" /><figcaption><a href="https://object-storage-ca-ymq-1.vexxhost.net/swift/v1/6e4619c416ff4bd19e1c087f27a43eea/www-assets-prod/presentation-media/kata-containers-and-gvisor-a-quantitave-comparison.pdf">https://object-storage-ca-ymq-1.vexxhost.net/swift/v1/6e4619c416ff4bd19e1c087f27a43eea/www-assets-prod/presentation-media/kata-containers-and-gvisor-a-quantitave-comparison.pdf</a></figcaption></figure><p>You could see that gvisor ‘s performance is very poor in this case, which is the main reason why I choose kata over gvisor.</p><h3>Integrate new runtime to k8s</h3><h4>Presiquites:</h4><ul><li>K8s, kubelet (&gt;= v1.4.3)</li><li>Containerd (&gt;= v1.2.0) with cri plugin</li><li>Kata container (&gt;= v1.5.0)</li></ul><p>As both gvisor and kata follow OCI standard, integrate to k8s is easy.</p><h4>Integrate kata to k8s</h4><ol><li><strong>Define new runtime class on k8s cluster</strong></li></ol><p>Create kata-runtime.yaml file with content:</p><pre>apiVersion: node.k8s.io/v1<br>kind: RuntimeClass<br>  metadata:<br>    name: kata<br>handler: kata<br>overhead:<br>  podFixed:<br>    memory: &quot;70Mi&quot;<br>    cpu: &quot;150m&quot;</pre><p><em>Note</em>: <em>We need to define overhead of runtime class, this will count for resource quota calculations, node scheduling as well as Pod cgroup sizing.</em></p><p>Apply on k8s:</p><pre>$ kubectl apply -f kata-runtime.yaml</pre><p><strong>2. Install kata runtime on nodes</strong></p><p>Installation guide could be found at <a href="https://github.com/kata-containers/documentation/tree/master/install">kata docs on github</a></p><p>As we ‘re using debian:</p><pre>$ ARCH=$(arch)<br>$ BRANCH=”${BRANCH:-master}”<br>$ echo ‘deb <a href="http://download.opensuse.org/repositories/home:/katacontainers:/releases:/$%7BARCH%7D:/$%7BBRANCH%7D/Debian_$%7BVERSION_ID%7D/">http://download.opensuse.org/repositories/home:/katacontainers:/releases:/${ARCH}:/${BRANCH}/Debian_${VERSION_ID}/</a> /’ &gt; /etc/apt/sources.list.d/kata-containers.list”<br>$ curl -sL <a href="http://download.opensuse.org/repositories/home:/katacontainers:/releases:/$%7BARCH%7D:/$%7BBRANCH%7D/Debian_$%7BVERSION_ID%7D/Release.key">http://download.opensuse.org/repositories/home:/katacontainers:/releases:/${ARCH}:/${BRANCH}/Debian_${VERSION_ID}/Release.key</a> | sudo apt-key add -<br>$ apt-get update<br>$ apt-get install -y kata-runtime kata-proxy kata-shim</pre><p><strong>3. Configure containerd</strong> by adding to /etc/containerd/config.toml</p><pre>[plugins]<br>  [plugins.cri]<br>    [plugins.cri.containerd]<br><strong>      [plugins.cri.containerd.runtimes.kata]<br>        runtime_type = “io.containerd.kata.v2”<br>        privileged_without_host_devices = false</strong></pre><p>Restart containerd to apply the new config</p><pre>$ systemctl restart containerd</pre><p><strong>4. Deploy new pod with kata runtime</strong></p><p>We just need to define directive “runtimeClassName: kata” at pod spec:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: katademo<br>  namespace: inf-dev<br>spec:<br>  selector:<br>    matchLabels:<br>      app: katademo<br>  template:<br>    metadata:<br>      labels:<br>        app: katademo<br>    spec:<br>      <strong>runtimeClassName: kata</strong></pre><h3>Conclusion</h3><p>I setup an prototype pod using kata runtime. It run well for more than 1 month without problem. And the setup is simple, you could do it within minutes. Even the overhead is small, we ‘re willing to accept it for increased security. But when I presented this solution to my teammates, there ‘s one raised his concerns about adding one more layer to our stack will make the troubleshooting problems more difficult. That ‘s reasonable and he has his points. However, security comes at prices —and it ‘s a price we ‘re willing to pay.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb4eb75e9dcf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/secure-container-runtime-cb4eb75e9dcf">Secure container runtime</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[podman encountered selinux (it’s somewhat effective!)]]></title>
            <link>https://medium.com/coccoc-engineering-blog/podman-encountered-selinux-its-somewhat-effective-446a17fa7242?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/446a17fa7242</guid>
            <category><![CDATA[audit]]></category>
            <category><![CDATA[selinux]]></category>
            <category><![CDATA[fedora]]></category>
            <category><![CDATA[podman]]></category>
            <dc:creator><![CDATA[hdhoang]]></dc:creator>
            <pubDate>Tue, 19 Apr 2022 08:01:44 GMT</pubDate>
            <atom:updated>2022-04-19T08:01:44.546Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>I’ve been running <a href="https://spins.fedoraproject.org/">fedora 35</a> for a few months, ever since a mishap with VM image borked a previous OS. The whole time, SELinux is in Enforcing mode without trouble. It&#39;s quite a testament to Fedora, flatpak, &amp; many people for making the policies sensible out of the box. The below is my first denial trouble, and how I went about it.</p><p>I was running a <a href="https://github.com/edenhill/kcat">kcat</a> (née kafkacat) container with <a href="https://podman.io/">podman</a>. That works fine with network=host to reach brokers, using no authentication:</p><pre>$; podman run --rm -it --network=host edenhill/kcat:1.7.0 -b kafka:9092 -L -t test<br>Metadata for points-events (from broker 20: kafka:9092/2):<br>3 brokers:<br> broker 20 at kafka2:9092<br> broker 30 at kafka3:9092<br> broker 10 at kafka1:9092 (controller)<br>1 topics:<br> topic &quot;test&quot; with 12 partitions:<br>...</pre><p>Now I want to read data, which requires SASL authentication. In my config dir, I make a key=value file kcat.conf:</p><pre>bootstrap.seers=kafka:9093<br>security.protocol=SASL_PLAINTEXT <br>sasl.username=hdhoang <br>sasl.password=notreal <br>sasl.mechanism=SCRAM-SHA-512</pre><p>Then we can bind-mount the file into the container and let kcat use it:</p><pre>$; podman run --mount type=bind,src=./kcat.conf,dst=/kcat.conf,ro --rm -it --network=host edenhill/kcat:1.7.0 -F /kcat.conf -L -t test <br>% ERROR: Failed to open /kcat.conf: Permission denied</pre><p>Permission? Hum, I’m sure my editor can read/write it fine. Plus the image’s USER is 0, it can read (its own) /etc/shadow:</p><pre>?$; podman run --rm -it edenhill/kcat:1.7.0 -F /etc/shadow <br>% Reading configuration from file /etc/shadow <br>% ERROR: /etc/shadow:1: expected property=value</pre><p>Anything weird about the podman mount syntax, perhaps we submount a directory or so?</p><pre>?$; podman run --mount type=bind,src=./kcat.conf,dst=/kcat.conf,ro --rm -it --network=host edenhill/kcat:1.7.0 -F /kcat.conf/ -L -t test <br>% ERROR: Failed to open /kcat.conf/: Not a directory</pre><p>Nope, /kcat.conf inside is a file alright.</p><p>Next, we go to the 1-stop shop for system log: journald</p><pre>‽$; journalctl -S -2min<br>...<br>systemd[1223]: Started libcrun container.<br>podman[32416]: 2022- m=+0.228695948 container init 3761ccc06aed60bc55fa05c7e21e16766612d5b729f8410dfd5ee89ac40f7ca2 (image=docker.io/edenhill/kcat:1.7.0, name=tender_proskuriakova)<br>audit[32457]: AVC avc:  denied  { read } for  pid=32457 comm=&quot;kcat&quot; name=&quot;kcat.conf&quot; dev=&quot;dm-0&quot; ino=2265717 scontext=system_u:system_r:container_t:s0:c734,c838 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0<br>conmon[32454]: % ERROR: Failed to open /kcat.conf: Permission denied<br>podman[32416]: 2022- m=+0.239698372 container start 3761ccc06aed60bc55fa05c7e21e16766612d5b729f8410dfd5ee89ac40f7ca2 (image=docker.io/edenhill/kcat:1.7.0, name=tender_proskuriakova)<br>podman[32416]: 2022- m=+0.239904686 container attach 3761ccc06aed60bc55fa05c7e21e16766612d5b729f8410dfd5ee89ac40f7ca2 (image=docker.io/edenhill/kcat:1.7.0, name=tender_proskuriakova)<br>podman[32416]: 2022- m=+0.249848927 container died 3761ccc06aed60bc55fa05c7e21e16766612d5b729f8410dfd5ee89ac40f7ca2 (image=docker.io/edenhill/kcat:1.7.0, name=tender_proskuriakova)<br>podman[32416]: 2022- m=+0.340016809 container remove 3761ccc06aed60bc55fa05c7e21e16766612d5b729f8410dfd5ee89ac40f7ca2 (image=docker.io/edenhill/kcat:1.7.0, name=tender_proskuriakova)<br>setroubleshoot[32377]: AnalyzeThread.run(): Cancel pending alarm<br>setroubleshoot[32377]: SELinux is preventing kcat from read access on the file kcat.conf. For complete SELinux messages run: sealert -l 0ce26f33-daec-4ae8-a7b0-5526da0d0a16<br>setroubleshoot[32377]: SELinux is preventing kcat from read access on the file kcat.conf.<br><br>    *****  Plugin catchall (100. confidence) suggests   **************************<br><br>    If you believe that kcat should be allowed read access on the kcat.conf file by default.<br>    Then you should report this as a bug.<br>    You can generate a local policy module to allow this access.<br>    Do<br>    allow this access for now by executing:<br>  # ausearch -c &#39;kcat&#39; --raw | audit2allow -M my-kcat<br>  # semodule -X 300 -i my-kcat.pp<br>...</pre><p>It captured kcat’s output too (as <a href="https://github.com/containers/conmon/">conmon</a> helper), and before that, audit system logged an denial (AVC is “ <a href="https://wikiless.org/wiki/Security-Enhanced_Linux?lang=en#Features">access vector cache</a>” if you’re curious). At this point, we can do sudo setenforce 0 then reboot and get on with life, but sometimes avoiding a reboot is fun!!</p><p>The audit entry contains relevant info, but let’s first follow <a href="https://fedoramagazine.org/troubleshooting-selinux/">setroubleshoot</a>’s helpful advice to use sealert -l to analyze the denial by its UUID:</p><pre>$; sealert -l 0ce26f33-daec-4ae8-a7b0-5526da0d0a16<br>SELinux is preventing kcat from read access on the file kcat.conf.<br><br>*****  Plugin catchall (100. confidence) suggests   **************************<br><br>If you believe that kcat should be allowed read access on the kcat.conf file by default.<br>Then you should report this as a bug.<br>You can generate a local policy module to allow this access.<br>Do<br>allow this access for now by executing:<br># ausearch -c &#39;kcat&#39; --raw | audit2allow -M my-kcat<br># semodule -X 300 -i my-kcat.pp<br><br>Additional Information:<br>Source Context                system_u:system_r:container_t:s0:c734,c838<br>Target Context                unconfined_u:object_r:user_home_t:s0<br>Target Objects                kcat.conf [ file ]<br>Source                        kcat<br>Source Path                   kcat<br>Port                          &lt;Unknown&gt;<br>Host                          HOSTNAME<br>Source RPM Packages<br>Target RPM Packages<br>SELinux Policy RPM            selinux-policy-targeted-35.11-1.fc35.noarch<br>Local Policy RPM              selinux-policy-targeted-35.11-1.fc35.noarch<br>Selinux Enabled               True<br>Policy Type                   targeted<br>Enforcing Mode                Enforcing<br>Host Name                     HOSTNAME<br>Platform                      Linux HOSTNAME 5.15.16-200.fc35.x86_64 #1 SMP Thu Jan<br>                              20 15:38:18 UTC 2022 x86_64 x86_64<br>Alert Count                   1<br>First Seen                    2022-01-28 10:41:44 +07<br>Last Seen                     2022-01-28 10:41:44 +07<br>Local ID                      0ce26f33-daec-4ae8-a7b0-5526da0d0a16<br><br>Raw Audit Messages<br>type=AVC msg=audit(1643341304.588:387): avc:  denied  { read } for  pid=32457 comm=&quot;kcat&quot; name=&quot;kcat.conf&quot; dev=&quot;dm-0&quot; ino=2265717 scontext=system_u:system_r:container_t:s0:c734,c838 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0<br><br><br>Hash: kcat,container_t,user_home_t,file,read</pre><p>It begins with the same suggestion for ausearch | audit2allow ; semodule as root (ie prompt prefix #). The most salient point is the source &amp; target contexts</p><pre>Source Context system_u:system_r:container_t:s0:c734,c838<br>Target Context unconfined_u:object_r:user_home_t:s0</pre><p>This is a different layer of access-control on top of UN*X owner/perm system. I don’t want to dissect it now, just to connect to my kafka cluster. Target context comes from the file’s SElinux attribute:</p><pre>‽$; ls -Z kcat.conf<br>unconfined_u:object_r:user_home_t:s0 kcat.conf</pre><p>Then setroubleshoot shows a bunch of details about my environment, and the audit message we saw in journal earlier. That’s straight forward enough, we can apply the suggestion, no? Now I took pause and wanted to see what audit2allow will do:</p><pre>$; sudo ausearch -c &#39;kcat&#39; --raw | audit2allow<br>#============= container_t ==============<br>allow container_t user_home_t:file read;</pre><p>Many fewer words, and it allows a container_t to read user_home_t. Ah, that will allow all containers to read (when I pass more bind-mount on commandline), not just this config file, but all of my videos as well! I don&#39;t want to do that! How about we <a href="https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9-beta/html/using_selinux/troubleshooting-problems-related-to-selinux_using-selinux#fixing-an-analyzed-selinux-denial_troubleshooting-problems-related-to-selinux">relabel the kcat config as container-relevant</a> instead?</p><pre>‽$; sudo semanage fcontext -a -t container_t kcat.conf<br>ValueError: Type container_t is invalid, must be a file or device type</pre><p>Huh, container_t is not a type for files, I guess it&#39;s for processes instead (eg our in-container kcat). Where do I discover types of files that containers can access? Ahha, the images&#39; content or overlay directories should be a good place:</p><pre>$; podman images| rg kcat<br>docker.io/edenhill/kcat                   1.7.0                    19bf67fb247a  5 months ago   40.1 MB<br><br>$; ls -dZ .local/share/containers/storage/overlay-images/19bf67fb247a06236ec706184f071a70e87438af550f58fd2cc53a4a238fe548/<br>unconfined_u:object_r:container_ro_file_t:s0 .local/share/containers/storage/overlay-images/19bf67fb247a06236ec706184f071a70e87438af550f58fd2cc53a4a238fe548/</pre><p>container_ro_file_t fits well with our purpose: containers can read it, but not modify. It would be an additional Read-Only enforcement on top of bind,ro flag, to ensure the containers don&#39;t edit our config under us.</p><p>To apply to kcat.conf, we add a policy to the context store system-wide:</p><pre>‽$; sudo semanage fcontext -a -t container_ro_file_t kcat.conf</pre><p>And reapply the policy for our file, to “restore context” on it:</p><pre>$; restorecon kcat.conf</pre><p>Now kcat can read it, and huh I made a typo!</p><pre>$; podman run --mount type=bind,src=kcat.conf,dst=/kcat.conf,ro --rm -it --network=host edenhill/kcat:1.7.0 -F /kcat.conf<br>% Reading configuration from file /kcat.conf<br>% ERROR: /kcat.conf:1: No such configuration property: &quot;boostrap.seers&quot;</pre><p>Where does the user_home_t label comes from anyway? It was applied at file creation time, based on the path (or path glob) of the file. For example, I can create a random file under ~/.ssh/, and that file gains a different labels:</p><pre>$; touch ~/.ssh/test<br>$; ls -Z ~/.ssh/test<br>unconfined_u:object_r:ssh_home_t:s0 /home/hdhoang/.ssh/test</pre><p>But moving the kcat.conf file there keeps its current label</p><pre>$; mv kcat.conf ~/.ssh/test<br>$; ls -Z ~/.ssh/test<br>unconfined_u:object_r:container_ro_file_t:s0 /home/hdhoang/.ssh/test</pre><p>Until an explicit restorecon rereads current policies &amp; relabels it. Your videos &amp; your ssh config/keys have different labels by default!</p><p>I hope this post introduced some initial vocab around SElinux denial, and some considerations on how to address it on a case-by-case basis. It looks helpful as a systemwide access enforcement mechanism, not just for file but also <a href="https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9-beta/html/using_selinux/getting-started-with-selinux_using-selinux#benefits-of-selinux_getting-started-with-selinux">TCP/UDP ports/sockets</a>. However, I don’t know how well the debugging can scale to production use-cases.</p><p>After you leave, please try discovering some past denials on your workstation: sudo sealert.You may find something strange, eg gdb trying to read graphic device /dev/card0. Have fun sleuthing the reason!</p><p><em>Originally published at </em><a href="https://hdhoang.substack.com/p/podman-encountered-selinux"><em>https://hdhoang.substack.com</em></a><em> on January 28, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=446a17fa7242" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/podman-encountered-selinux-its-somewhat-effective-446a17fa7242">podman encountered selinux (it’s somewhat effective!)</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Log-Structured Merge-Tree storage engine to a toy database]]></title>
            <link>https://medium.com/coccoc-engineering-blog/from-log-structured-merge-tree-storage-engine-to-a-toy-database-672092091bde?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/672092091bde</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cassandra]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[CocCoc Techblog]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 05:11:23 GMT</pubDate>
            <atom:updated>2021-12-30T05:43:48.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpOPb2kx6oIDlxjbTYnbwg.jpeg" /></figure><h3>Preface</h3><p>We’ve heard of Log-Structured Merge-Tree (LSMTree) for many times recently, when many high scalable NoSQLs are gaining popularity such as Cassandra, HBase, LevelDB, Elasticsearch… We may have a very brief idea on how they work under the hood theoretically, but we haven’t touch that in depth. We know the engine’s pros and also the cons in comparison with BTree, we learn by heart that “LSMTree is write-preferrable, and BTree vise-versa”, but do we actually understand why it has these characteristics?</p><p>In this blogpost, we do not guarantee that you’ll understand every aspect of LSMTree DBMS, but we’ll together build a key-value toy database, that follows the idea of the engine. Consequently, we will know a little bit deeper on how it works through the toy we build, from theory to practice. Surprisingly, it’s not that hard as we only read and imagine first-hand!</p><h3>Log-Structured Merge-Tree</h3><p>LSMTree is a data structure that allows append-only operations, that’s why it stands on its name, “Log-structured”. The database is a simply a very big log containing all the key-value pairs, and all the modifications such as create, update, delete are treated the same — insert new records into the big log. The design sounds very unintuitive in the first look, but it brings to the table a remarkable benefit which no other engines can afford: being append-only means writes will always be sequential, maintaining high throughput, low latency, no disk seek, no write amplification (as in BTree)... Now you have a faint idea on why LSMTree is write-preferable. Let’s go on, a database is not that simple.</p><p>Of course LSMTree is not a silver bullet for everything, its read performance is sometimes horibly slow in comparison with traditional BTree counterparts. To understand why read is slow, we need to look at the read path (which happens when a read query comes)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipKru9lYpGEgfQ1tjHrpKw.png" /><figcaption>Read path in Cassandra</figcaption></figure><p>Leaving out all the complications on the diagram above, write path, which doesnt require disk seeks, are very opposite to read path, which needs to check data from all the database segments, containing Memtables (the data segments in memory) and SSTables (the data segments on disk). The indexes and caches can help a bit, but eventually large data need to be scanned because the key can be existed in many places (due to append-only). This is opposite to BTree, when the read can find exact location for a key without scanning all the data.</p><p>Understanding Read and Write is crucial for understanding a database, even it’s just a very surface of a full-featured DBMS. But for the purpose of this blogpost, it’s enough for us to get ahead building our toy. Let’s get our hand dirty.</p><h3>Simple Key-Value datastore</h3><p>First of all, I’m gonna use Python for that demonstration because of its human-readable code. Python dictionary — a built-in data structure — will be leveraged for our task.</p><p>The very first KV datastore, with whole database is inside memory. I call the memory data structure “memtable” — borrowed from Cassandra. All the modifications will be using set() , and get() is for read.</p><pre>#!/usr/bin/env python3<br><br>import json<br>import logging<br><br>logging.basicConfig(level=logging.DEBUG)<br><br>class LSMTree():<br>    def __init__(self):<br>        self.memtable = {}</pre><pre>    def set(self, key, value):<br>        self.memtable[key] = value</pre><pre>    def get(self, key):<br>        if key in self.memtable:<br>            data = self.memtable[key]</pre><p>Next, we’ll need a bit of durability, for that our precious data would not be lost when the database shutdown. Function flush() will be called when database exit, and it has to flush all the data from memtable to disk. The startup() function do the opposite job, read all the data from disk and push back to memtable , so we can operate on that in-memory database.</p><pre>from pathlib import Path<br><br>DBPATH = &quot;/var/lib/lsm/&quot;</pre><pre>class LSMTree():<br>    def __init__(self, dbpath=DBPATH):<br>        ...<br>        self.db_file = self.path + &quot;db&quot;<br>        Path(self.path).mkdir(exist_ok=True)<br>        Path(self.db_file).touch(exist_ok=True)</pre><pre>    # flush memtable to persistent db file<br>    def flush(self):<br>        logging.debug(&quot;event: FLUSHING&quot;)<br>        json.dump(self.memtable, open(self.db_file, &quot;w&quot;))</pre><pre>    # for durability<br>    def shutdown(self):<br>        logging.debug(&quot;event: SHUTTING DOWN&quot;)<br>        self.flush()</pre><pre>    def startup(self):<br>        logging.debug(&quot;event: STARTING&quot;)<br>        self.memtable = json.load(open(self.db_file, &quot;r&quot;))</pre><p>Whenever startup, the whole DB will be reloaded into our memory, so it’s unusable with large dataset. Anyway, without index there’s nearly impossible to operate without scanning the whole dataset, and implementing index is out of scope of this blogpost, so we leave it as is. There’s not any LSMTree characteristics for now.</p><h3>Journaling</h3><p>There’s problem with current setup, if the DB is crashed during operations then the data between DB startups will be lost. Nearly all DBMS now are having a mechanism called “journaling” (or commit log) to deal with this kind of loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*Sn0ptK_qg_MdHsVSFWh5Zw.png" /><figcaption>journaling</figcaption></figure><p>First, database after receiving a write query will append that update info into journal (which resides on disk), then if it succeed, update will be taken place on memtable (on memory, would be very fast). After step 2, it returns to the client to acknowledge that write is successful (non-blocking because it doesnt need to wait for disk write). If the crash happens during flushing memtable to disk, database when startup can replay the update on journal to recover lost updates.</p><p>Let’s implement journal for our db</p><pre>class LSMTree():<br>    def __init__(self, dbpath=DBPATH):<br>        ...<br>        self.journal_file = self.path + &quot;journal&quot;<br>        Path(self.journal_file).touch(exist_ok=True)</pre><pre>        # Configs<br>        self.journal_line_limit = 5</pre><pre>    def set(self, key, value):<br>        # journaling for durable writes<br>        self.journal(key, value)<br>        # update value in memtable<br>        self.memtable[key] = value<br>    <br>    def journal(self, key, value):<br>        data = {key: value}<br>        json.dump(data, open(self.journal_file, &quot;a&quot;))<br>        with open(self.journal_file, &quot;a&quot;) as f:<br>            f.write(&quot;\n&quot;)<br><br>        self.rotate()</pre><pre>    # rotate journal, keep only last line when exceeding limit<br>    def rotate(self):<br>        data = []<br>        with open(self.journal_file, &quot;r&quot;) as f:<br>            data = f.read().splitlines()<br><br>        if len(data) &gt;= self.journal_line_limit:<br>            logging.debug(&quot;event: ROTATING&quot;)<br>            new_data = data[-1]<br>            with open(self.journal_file, &quot;w&quot;) as f:<br>                f.write(new_data)<br>                f.write(&quot;\n&quot;)</pre><pre>    # read journal into memtable on startup<br>    def startup(self):<br>        logging.debug(&quot;event: STARTING&quot;)<br>        data = {}<br>        with open(self.journal_file, &quot;r&quot;) as f:<br>            for line in f.readlines():<br>                jline = json.loads(line)<br>                # merge<br>                data = {**data, **jline}<br>        self.memtable = data</pre><p>We even implement a cool feature that rotating the journal log when it exceeds a threshold, for not growing too large. Basically our DB is single threaded so no need to keep too many records on journal.</p><p>You can notice that for now, we haven’t load the whole DB into memtable, only journal for recovery after crash, so get() is not working properly at the moment. We’ll implement the idea of LSMTree to operate on part of dataset instead of a whole, for better performance.</p><h3>Write-Ahead Log</h3><p>If our memtable hold too much data while the journal is rotated, a crash can clear all the un-journaled in-memory data. We need to find a way to flushing in-memory dataset into persistent disk before the journal is cleared out. There’re 2 common approaches employed by databases nowadays:</p><ol><li>flush the memtable to persistence file on every update operation. This method slows down the database significantly in tradeoff with consistency.</li><li>flush the memtable to persistence file according to its size or how long it hasn’t been flushed, or periodically (determined by space and time). We’ll choose this approach with config memtable_obj_limit = 5</li></ol><p>If the memtable is flushed to main database file db_file , it’ll be very slow because whole db need to be reread and rewritten. In LSMTree DB, memtables flush to sstables, then sstables will be merged together to a bigger sstables (Merge-Trees) by other asynchronous threads/processes, so older sstables will be untouched until merges happen (compaction), and main processing threads’ performance wont be affected.</p><p>We will inherit this characteristic, by flushing our memtable to a file called Write-Ahead Log (WAL), and after sometimes, merge wal with main db file. In official term, our wal and db files can be considered as 2 separated SSTables. Basically, we can use as many WALs as needed, but for sake of simplicity we use only one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2myT7fwS8CK-TZlaQsCY-A.png" /><figcaption>flush process flow</figcaption></figure><p>In short, main advantages of using WAL (or SSTables in Cassandra or alike):</p><ul><li>updates will be appended to persistence, no in-place update</li><li>separate a big db files into many small chunks, read can check latest chunks to get the latest data without scanning all the chunks</li></ul><p>Our DB is quite enough with write, let’s get back to read.</p><h3>Reading in LSMTree</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJUscdtaCxYFkIgxCF8oiw.png" /><figcaption>Read path</figcaption></figure><p>We’re not having 3 chunks of data: memtable, wal and db. Memtable contains the latest data, so if we can get what it’s needed from memtable, disk access is not required. The idea applies to all DBMS as can be seen in Bufferpool in MySQL, WiredTiger cache in MongoDB and so on…</p><pre>    def get(self, key):<br>        data = None<br>        # check if value is in memtable<br>        if key in self.memtable:<br>            data = self.memtable[key]<br>        else:<br>            # else check all sstables (wal + db)<br>            wal = self.load(self.wal_file)<br>            if key in wal:<br>                data = wal[key]<br>            else:<br>                db = self.load(self.db_file)<br>                if key in db:<br>                    data = db[key]</pre><pre>        # If tombstone<br>        if data == self.tombstone:<br>            data = None</pre><pre>        return data</pre><p><strong>Delete by inserting tombstones</strong></p><p>The main problem of LSMTree is deleting is tricky because of no in-place replacement. For deleting we need to seek from all the chunks and delete that key if any. To overcome this issue the database insert a “tombstone” to the key which is suppose to be deleted (term and mechanism borrowed from Cassandra). For that, “delete” semantic is still append-only operation.</p><p>As in the read path depicted above, whenever it read the tombstone, the key is considered deleted. It will be truly deleted by merge (or compaction)</p><pre>    # For merging main db + wal<br>    def merge(self):<br>        wal = self.load(self.wal_file)<br>        db = self.load(self.db_file)<br>        # Dict merge python 3.5+ semantics<br>        merged = {**db, **wal}<br>        # remove tombstone<br>        removed = []<br>        for k in merged:<br>            if merged[k] == self.tombstone:<br>                removed.append(k)<br>        for k in removed:<br>            merged.pop(k)<br>        <br>        logging.debug(&quot;event: MERGING&quot;)<br><br>        json.dump(merged, open(self.db_file, &quot;w&quot;))<br><br>        # clear wal<br>        with open(self.wal_file, &quot;w&quot;) as f:<br>            f.truncate()</pre><h3>See what a toy can do</h3><pre>l = LSMTree()<br>l.startup()<br>l.upsert(&quot;1&quot;, &quot;1&quot;)<br>l.upsert(&quot;2&quot;, &quot;2&quot;)<br>l.upsert(&quot;2&quot;, &quot;3&quot;)<br>l.upsert(&quot;3&quot;, &quot;3&quot;)<br>l.upsert(&quot;4&quot;, &quot;4&quot;)<br>l.upsert(&quot;5&quot;, &quot;5&quot;)<br>l.upsert(&quot;6&quot;, &quot;6&quot;)<br>l.delete(&quot;6&quot;)<br>print(l.get(&quot;6&quot;))<br>print(l.get(&quot;5&quot;))<br>l.shutdown()</pre><pre>--- runtime output</pre><pre>DEBUG:root:event: STARTING<br>DEBUG:root:self.memtable: {&#39;1&#39;: &#39;1&#39;}<br>DEBUG:root:memtable_objs: 1<br>DEBUG:root:self.memtable: {&#39;1&#39;: &#39;1&#39;, &#39;2&#39;: &#39;2&#39;}<br>DEBUG:root:memtable_objs: 2<br>...<br>DEBUG:root:event: ROTATING<br>DEBUG:root:self.memtable: {&#39;6&#39;: &#39;delete_tombstone&#39;}<br>DEBUG:root:memtable_objs: 1<br>None<br>5<br>DEBUG:root:event: SHUTTING DOWN<br>DEBUG:root:wal: {&#39;1&#39;: &#39;1&#39;, &#39;2&#39;: &#39;3&#39;, &#39;3&#39;: &#39;3&#39;, &#39;4&#39;: &#39;4&#39;, &#39;5&#39;: &#39;5&#39;}<br>DEBUG:root:wal_objs: 5<br>DEBUG:root:event: FLUSHING<br>DEBUG:root:event: MERGING<br>DEBUG:root:event: MERGING</pre><p>As can be seen, key “6” was deleted so its value is “delete_tombstone”, and on MERGING event, it’s eventually deleted. get(&quot;6&quot;) returns None even before MERGING as designed.</p><p>We’ve completed a very first demonstration on how to build a functioning key-value database. As it’s not nearly applicable in any serious application, the idea of LSMTree is realized and being understandable in just ~100 lines of code, and can be developed even more for new features and better performance. Most of all, the toy opens paths for understanding LSMTree storage engine in more complex, complicated well-known databases such as Cassandra, Elasticsearch… which is the main purpose of this demonstration.</p><h3>References</h3><ul><li><a href="https://github.com/wintdw/python-lsmtdb">https://github.com/wintdw/python-lsmtdb</a></li><li><a href="https://dev.to/creativcoder/what-is-a-lsm-tree-3d75">https://dev.to/creativcoder/what-is-a-lsm-tree-3d75</a></li><li>Cassandra The Definitive Guide (3rd Edition) — Chapter 9: Reading and Writing Data</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=672092091bde" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/from-log-structured-merge-tree-storage-engine-to-a-toy-database-672092091bde">From Log-Structured Merge-Tree storage engine to a toy database</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DNS — I know what it is, but how does it work?]]></title>
            <link>https://medium.com/coccoc-engineering-blog/dns-i-know-what-it-is-but-how-does-it-work-d637bebe2223?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/d637bebe2223</guid>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Tuấn Anh Phạm]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 09:14:20 GMT</pubDate>
            <atom:updated>2022-01-12T09:14:20.223Z</atom:updated>
            <content:encoded><![CDATA[<h3>DNS — I know what it is, but how does it work?</h3><p>Domain name service (DNS) is one of the oldest services on the internet, and also one of the most importance out there — it ‘s even being mentioned as “the very heart of the Internet network”. Everyone in the field know what dns is — a phone book for internet which translate human-friendly hostnames into IP addresses, but not all know how it works (or I assume so). In this blogpost, I want to write about how dns works, trying to make it as easy to understand as possible.</p><h3>DNS terms</h3><p>First, there ‘s some terms that I use in this post that needed to be understand first. As usual, most are shameless copies from somewhere on the internet:</p><ul><li><strong>RR</strong> (Resource record): the unit of information entry in DNS zone files, used to resolve all DNS queries. There ‘s more than 100 types of RRs, the common ones you may work with everyday are <strong>A</strong>, <strong>PTR</strong> and <strong>CNAME</strong>. For the complete list of RR types, refer to <a href="https://en.wikipedia.org/wiki/List_of_DNS_record_types">this wiki page</a>.</li><li><strong>zone</strong>: is a specific portion of the DNS namespace in the Domain Name System (DNS), which is managed by a specific organization or administrator.</li><li><strong>Authoriative server</strong>: a dns server that gives answers for dns queries for a specific zone. A DNS server could be authoriative for multiple zones.</li><li><strong>Recursive server</strong>: dns server that finds the answer for client, also called caching server.</li><li><strong>Iterative server</strong>: dns server that instead of returning answer to clients, tells client to ask another dns server.</li><li><strong>Resolver</strong>: general name for authoriative, recursive and iterative servers</li><li><strong>Root servers</strong>: sit at the top of DNS hierarchy, they are scattered around the globe and operated by 12 independent organizations. There ‘re total 13 root servers today.</li><li><strong>TLD</strong> (Top level domain): the highest level in hierarchical DNS, after root domain.</li></ul><h3>Domain name</h3><p>A domain name, for example <em>“</em><a href="http://www.coccoc.com/"><em>www.coccoc.com</em></a>”<em> </em>contains multiple parts, each part separated by dot “.”. We interpret that domain name as two parts: <em>www</em> as the server name and <em>coccoc.com </em>as its domain. <br>But unlike human, dns clients and servers read a domain name from right to left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*W6d_TzVIoBIYbUCsBcGBZw.png" /></figure><p>Second level domain is managed by organizations or individuals. Organizations can run their own DNS servers or delegate management to supplier.</p><p>A domain name could have up to 127 subdomains levels, but I rarely see one that exceed 4 levels, ’cause anything deeper than that is considered unfriendly with human — therefore against the original purpose of DNS.</p><h3>How the DNS works from client side</h3><p>An application or service usually doesn’t send DNS queries directly itself, it delegates the job to DNS client. Then, dns client will try to find an answer by the following order by default:</p><ul><li>First, it will search for the answer from local host file (/etc/hosts for Linux OS).</li><li>Next, it will try to find the answer from local DNS cache.</li><li>If the answer ‘s not in cache, the DNS resolvers will be asked. We could register up to 3 nameserver as resolvers in /etc/resolv.conf.</li></ul><p>There is one thing you must be aware of is that the order of nameservers on resolv.conf matters, the upper will be chosen first. That means you could register 2 or 3 nameservers to avoid problem of name resolution fail when the resolver die. However, if the upper name server in your resolv.conf dies, it can still cause you trouble. I will demonstrate it in a simple test:</p><pre># time dig coccoc.com +short<br>123.30.175.29</pre><pre>real 0m0.018s</pre><p>The time needed for the query is short, in miliseconds. But when I tried to add a failed nameserver (one that doesn’t have dns service running), make it the top at /etc/resolv.conf:</p><pre># time dig coccoc.com +short<br>123.30.175.29</pre><pre>real 0m1.020s</pre><p>It took more than 1 second for the query. Why 1 second — you ask: it ‘s because the default timeout for dns client is 1 sec. When the client send query to the 1st nameserver which is dead, it wait 1 sec until query to the second. This may cause a lot of performance overhead for services depending on dns, and may take time for you to discover where the problem is.</p><p>At coccoc, we avoid this situation by setup unbound, a lightweight dns service on every physical servers, acting like a local dns recursive. In the host file, the first nameserver will be 127.0.0.1, point to the local recursive. Unlike the client, at the dns service you could register more than 3 nameservers, and it could choose the nameserver with smallest response time instead of a fixed order. While it ‘s still fall back to 1 second timeout scenario if the unbound service die, however the service ‘s always easier to detect and handle.</p><h3>How the resolver works</h3><p>In case of a query reaches a resolver that is authoriative server, the server simply answer the client. If the authoriative server doesn’t know the answer, It will return <em>NXDOMAIN</em> response.</p><p>But if resolver is not authoriative, it will follow those steps:<br><strong>1.</strong> First, resolver will try to find the answer from its cache if it is recursive.<br><strong>2.</strong> If the answer ‘s not in cache or the server is iterative, resolver will ask the root server, which will returns the address of TLD server ’cause the root server ‘s also iterative.<br><strong>3.</strong> The resolver will ask TLD server and will get the name of the requested domain ‘s SOA server as answer.<br><strong>4.</strong> Finally, the resolver knows which server manage the domain, and send the dns query to that server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*RqTvgo5T4X-osVJcBm5dSQ.png" /><figcaption>Demonstration of steps 2 to 4</figcaption></figure><p>There one thing at step <strong>3</strong>: if you manage the dns yourself, NS record will be in your zone configuration, which causes what we call a “<em>circular reference</em>”. That ‘s when we need a glue record.</p><h3>The glue records</h3><p>Glue records actually are A or AAAA records that point to addresses of authoriative servers for specific domain names. Glue records reside at TLD, so we could avoid <em>circular reference</em>.</p><p>For example, domain <strong>coccoc.com</strong> has nameservers <strong>ns1.coccoc.vn</strong>, <strong>ns2.coccoc.vn</strong>. To resolve the domain name, as the previous section also mentioned, the client would query in order: root, TLD <strong>vn.</strong>, and <strong>ns1.coccoc.vn</strong>. However, <strong>ns1.coccoc.vn</strong> ‘s A record is defined at itself, so client will ask root server who is <strong>ns1.coccoc.vn</strong>, and creating a loop - a <em>circular reference</em>. To avoid this case, we A record of <strong>ns1.coccoc.vn</strong> is placed at TLD, so client will know who <strong>ns1.coccoc.vn</strong> is. Hence, the glue records.</p><p>To check if a domain has glue records or not is quite simple:<br><strong>1.</strong> Get the list of TLD servers by using tool dig:</p><pre>$ dig +short vn. NS<br>c.dns-servers.vn.<br>......</pre><p><strong>2.</strong> Pick one TLD server from the list and query directly to it. It should return ADDITIONAL section if the domain has glue records on TLD.</p><pre>dig @c.dns-servers.vn coccoc.vn<br>...<br>;; ADDITIONAL SECTION:<br>ns1.coccoc.vn.  43200 IN A 123.30.175.7<br>ns2.coccoc.vn.  43200 IN A 123.30.175.113</pre><h3>And how does knowing these things help you?</h3><p>You may wonder why you need to understand all the complicated things while you only need to know how to create and modify simple A or PTR records? Yes, a driver ‘s no need to be a car engineer to be good, but that driver could hire technicians to maintain and fix his car. You may not be that lucky, if you own the dns service yourself, and you must maintain it. Knowing how the dns works could help you debug things faster, you can find the problem and fix it in short time instead of blindly restart everything (that still may not works).</p><p><em>To do: in the future, I may write about some case study in debug and fix problems with dns.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d637bebe2223" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/dns-i-know-what-it-is-but-how-does-it-work-d637bebe2223">DNS — I know what it is, but how does it work?</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raft — Consensus Algorithms]]></title>
            <link>https://medium.com/coccoc-engineering-blog/raft-consensus-algorithms-b48bb88afb17?source=rss----ac2691688f07---4</link>
            <guid isPermaLink="false">https://medium.com/p/b48bb88afb17</guid>
            <dc:creator><![CDATA[Lambq]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 09:02:50 GMT</pubDate>
            <atom:updated>2022-01-12T09:02:50.526Z</atom:updated>
            <content:encoded><![CDATA[<h3>Raft — Consensus Algorithms</h3><blockquote><strong>Consensus algorithms</strong> are mechanisms that allow a cluster of many computers (servers) to operate coherently and smoothly, even if some of the servers are disconnected from the cluster. Therefore, consensus algorithms have always played an important role in building reliable large-scale computational systems.</blockquote><p><strong>I. Consensus Mechanism</strong></p><p>Consensus is a fundamental problem in fault-tolerant distributed systems. Consensus involves multiple servers agreeing on values. Once they reach a decision on a value, that decision is final. Typical consensus algorithms make progress when any majority of their servers is available; for example, a cluster of 5 servers can continue to operate even if 2 servers fail. If more servers fail, they stop making progress (but will never return an incorrect result).<br>Consensus typically arises in the context of replicated state machines, a general approach to building fault-tolerant systems. Each server has a state machine and a log. The state machine is the component that we want to make fault-tolerant, such as a hash table.</p><p>Consensus algorithms for a real system typically have the following properties:</p><ul><li>They must be secure (never return incorrect results) under all non-Byzantine conditions, including situations such as network latency, packet loss, packet duplication, and reordering of commands in the network. package.</li><li>They must be fully functional so that active servers can communicate with each other and with the client. Therefore, a cluster of 5 servers can still function if two of the servers are suddenly turned off, then those two servers are turned on again, recovering from a previously saved state, and rejoining the cluster.</li><li>They must be time independent to ensure log consistency.</li><li>Usually, a command can be completed as soon as most servers have completed the command; A small number of slow servers will not affect the performance of the entire cluster system.</li></ul><p><strong>II. Raft Algorithms</strong></p><p><strong>Raft</strong> is a consensus algorithm designed as an alternative to the Paxos family of algorithms. It was meant to be more understandable than Paxos by means of separation of logic, but it is also formally proven safe and offers some additional features.Raft offers a generic way to distribute a state machine across a cluster of computing systems, ensuring that each node in the cluster agrees upon the same series of state transitions. It has a number of open-source reference implementations, with full-specification implementations in Go, C++, Java, and Scala. It is named after Reliable, Replicated, Redundant, And Fault-Tolerant.</p><p><strong>Raft </strong>is a relatively efficient consensus algorithm that has significant advantages over other consensus algorithms. It has three important characteristics:</p><ul><li><strong>Stronger Leader (stronger Leader role):</strong> Raft allows the Leader to have a stronger role than other consensus algorithms. For example, log entries are only broadcast from the Leader to other servers.</li><li><strong>Leader Election:</strong> Raft uses a random timer to elect a leader, which simply adds a small change to heartbeats compared to other consensus algorithms, but it helps to resolve conflicts between servers in the cluster simply and quickly.</li><li><strong>Membership changes (change the role of the server in the cluster):</strong> that is, change the role of a certain server from follower to leader . This allows the cluster as a whole to continue to function normally while the servers in the cluster are in the process of changing roles.</li></ul><p><strong>Replicated state machines: </strong>Each server in the cluster will have a state machine. The consensus algorithm must ensure that the state machines on the servers in the cluster must have the same state (replicated) and can continue to work even if some servers in the cluster lose connection. Replicated state machines are commonly used to solve a variety of fault tolerance problems in distributed systems.<br>The client sends a log of state update commands to the cluster, and the consensus algorithm manages the replication of this log to each server in the cluster. Therefore, the state machines on the servers will process the same log, and they will produce the same output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*WgJfagZ3nYl9yJxx2VnftQ.png" /></figure><p>Each server stores a log containing a sequence of commands that its state machine will execute in sequence. Since the log received by the servers is the same, the state machines will process the same sequence of commands, and produce the same state.</p><p>Keeping replicated logs so they are consistent is the job of the consensus algorithm. The Consensus module on a server will receive commands from and add them to its log. It then communicates with other servers also through the consensus module to ensure that their logs all contain the same commands in the same order, even if several servers fail in the cluster. Next, the replicated state machines on the servers will process the log and return the results to the client. and the results seem to be the same, with high confidence.</p><p><strong>Summary of concepts in Raft</strong></p><p><strong>III. Election problems</strong></p><p>Raft has divided the consensus problem into three subproblems:<br>1. Leader Election<br>2. Log Replication<br>3. Safety</p><p>In this, I focus on <strong>Leader Election</strong></p><p>Raft is a consensus algorithm based on Leader model, where a Leader will be elected and it will take full responsibility for managing all other machines (cluster), namely it will perform replication of log that it receives from the client side to all nodes in the cluster.<br>S1 is the node that is elected as Leader when the Raft cluster starts up and it will be responsible for receiving requests from the client and replicating the logs containing commands to the remaining nodes, after the cluster has reached consensus in computation, S1 will return a response to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*xfF_dY-V05Fi-tAetVgHUQ.png" /><figcaption>For a node to become a Leader, it must receive at least (N/2 + 1) votes, where N is the number of nodes in the cluster. Thus, a Raft cluster must have at least 3 or more nodes to operate and 5 or more nodes to operate effectively.</figcaption></figure><p>When a Raft cluster is up and running or a Raft cluster is up and running but the leader of that cluster is disconnected, a new Leader will be elected through the election process among the member nodes of that cluster. Therefore, at a given time a node can only carry one of the following three states: Follower, Candidate, Leader.<br>The leader will be fully responsible for managing the Raft cluster, capturing and processing commands sent from the client side. The Followers will be in a passive position and they will only fulfill the requirements of the Leader and Candidate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*W6bSQIPJT-k9K1B5peG-gA.png" /><figcaption>When the Raft cluster falls into a state without a Leader (due to the old Leader being faulty), any Follower can become a Candidate and send requests to other members to request votes from them.</figcaption></figure><p>In Raft, time is divided into units called Terms. Each Term will be started with an election and then the elected Leader will serve until the end of the Term if it doesn’t suffer any errors in the process of being Leader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*_DPUF2jgdz6HL9PPAr9wVA.png" /></figure><p>In some cases, an election may have 2 Candidate receiving the same number of votes (this is called split vote scenarios) then a new election needs to start immediately. Terms are numbered in ascending order to indicate which Term it is, and this value is always included in communication between cluster members. The nodes of the cluster will communicate with each other using RPC (remote procedure calls).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*SEfgrPh9iI1jS5o_RZ-vcw.png" /><figcaption>Heartbeat messages are sent periodically from Leader to Followers</figcaption></figure><p>In Raft, each node uses heartbeat mechanism to detect the current term has ended and start a new election. That is, during normal operation the Leader will have to periodically send heartbeat messages to all members of the cluster to notify that it is still active and the remaining nodes must maintain their Follower status. themselves, otherwise the other nodes will declare the current Leader dead and trigger a new election.</p><p><strong>Summarize the Leader election process</strong></p><p>All servers start as followers<br>No heartbeat (AppendEntries)? Start election:<br> + Increment current term<br> + Vote for self<br> + Send RequestVote requests to all other servers<br>Election outcomes:<br>+Receive votes from majority of cluster: become leader, start sending +heartbeats to prevent additional elections<br>+Receive AppendEntries from some other server in the new term: revert back to follower<br>Timeout: start a new election<br>Each server votes for at most one candidate in a given term<br>Election Safety: only one server can be elected leader in a given term<br>Availability: randomized election timeouts reduce split votes</p><p><strong>Summary</strong></p><p>Raft was designed for better understandings of how Consensus can be achieved in the distributed system. Raft is a distributed consensus algorithm, designed to be easily understood, solves the problem of getting multiple servers to agree on a shared state even in the face of failures. Having a clear and thorough grasp of how Raft works will help us to design a smooth and efficient system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b48bb88afb17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coccoc-engineering-blog/raft-consensus-algorithms-b48bb88afb17">Raft — Consensus Algorithms</a> was originally published in <a href="https://medium.com/coccoc-engineering-blog">Coccoc Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>