<?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"><channel><title><![CDATA[CosmicOppai]]></title><description><![CDATA[CosmicOppai]]></description><link>https://cosmicoppai.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1724174645042/64ab5c96-39cf-41a2-84a8-136ed0a15315.png</url><title>CosmicOppai</title><link>https://cosmicoppai.com</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 06 Nov 2026 19:22:32 GMT</lastBuildDate><atom:link href="https://cosmicoppai.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Traceroute: Not so hard]]></title><description><![CDATA[Writing traceroute from scratch]]></description><link>https://cosmicoppai.com/traceroute-not-so-hard</link><guid isPermaLink="true">https://cosmicoppai.com/traceroute-not-so-hard</guid><category><![CDATA[networking]]></category><category><![CDATA[C]]></category><category><![CDATA[IPv4]]></category><category><![CDATA[traceroute]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Sat, 04 Oct 2025 21:55:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/_Cvt8w6Uiso/upload/985ca87ddf052b98485f6cb656536c7a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I’m sure most of you might have already heard about <a target="_blank" href="https://en.wikipedia.org/wiki/Traceroute">traceroute</a>.</p>
<p>If not, it’s a command line tool generally used to trace the path of the packet over the network.</p>
<p>I recently came across the implementation detail of it, and it’s surprisingly simple to implement and reason about.</p>
<p>In OSI or TCP/IP model, when we create an IP packet to send across the network, we specify the bunch of parameters in headers. One of them is <code>TTL</code> in IPV4 and <code>HOP</code> in IPV6. By definition <code>TTL</code> indicates the time to live in seconds and <code>HOP</code> indicates the number of hops. But in practice both of them work as hop counter. Both of them indicates the number of machines that should process the packet before dropping.</p>
<pre><code class="lang-bash">                    IPv4 Header Format

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |Version|  IHL  |Type of Service|          Total Length         |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |         Identification        |Flags|      Fragment Offset    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |  Time to Live |    Protocol   |         Header Checksum       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                       Source Address                          |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                    Destination Address                        |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                    Options                    |    Padding    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
</code></pre>
<pre><code class="lang-bash">                    IPv6 Header Format

   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |Version| Traffic Class |           Flow Label                  |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |         Payload Length        |  Next Header  |   Hop Limit   |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                                                               +
   |                                                               |
   +                         Source Address                        +
   |                                                               |
   +                                                               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                                                               +
   |                                                               |
   +                      Destination Address                      +
   |                                                               |
   +                                                               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
</code></pre>
<p>For example: I transmitted a packet with TTL/HOP of 3, when the next machine will reduce it by one and transmit it to the next machine, if it’s not the final destination. This process will be repeated until destination is reached, or the packet is dropped. Once the packet is dropped by the machine/node, the same machine informs the source about it via the <code>ICMP</code> message. <code>ICMP - Time exceeded</code> message, more specifically.</p>
<p><em><mark>ICMP messages are used to send control messages and error reporting messages. Thet are not used for any data sending part but used for the feedback mechanism across the devices.</mark></em></p>
<p>The reason why we have this TTL/HOP in the first place is to avoid the infinite roaming of packet. In a misconfigured looped network, a packet will be passed around for eternity, wasting resources.</p>
<p>The traceroute leverages this particular field to get the complete route of the packet over the Internet. It sends the packets continuously starting with TTL <code>1</code> up to a max user defined limit. If the packet reaches the destination the returned error will be <code>ICMP PORT UNREACHABLE</code>. Any node in between will give the <code>ICMP Time exceeded</code> message, effectively sending back it’s IP as per the protocol.</p>
<p>A simplified pseudocode will look like this:</p>
<pre><code class="lang-python">sock = create_socket()
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">30</span>):
    ip_packet = IP_PACKET
    ip.packet.ttl = i
    status = send_packet(sock, remote_server, ip_packet)
    <span class="hljs-keyword">if</span> status:
        err_msg = sock.read_error()
        <span class="hljs-keyword">if</span> err_msg.type == ICMP_TIME_EXCEEDED:
            print(<span class="hljs-string">f"<span class="hljs-subst">{i}</span>: <span class="hljs-subst">{err_msg.remote_addr.ip}</span>"</span>)
        <span class="hljs-keyword">elif</span> err_msg.type == ICMP_UNREACHABLE:
            print(<span class="hljs-string">"Destination Reached"</span>)
            print(<span class="hljs-string">f"<span class="hljs-subst">{i}</span>: <span class="hljs-subst">{err_msg.remote_addr.ip}</span>"</span>)
            <span class="hljs-keyword">return</span>;
</code></pre>
<p>I have tried to write the whole thing in C, just to make things bit hard for myself as someone who’s not used to writing C daily.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;sys/socket.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;arpa/inet.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;sys/types.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;netdb.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;string.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unistd.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;netinet/in.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;linux/errqueue.h&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;netinet/ip_icmp.h&gt;</span></span>


<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">get_udp_socket</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    <span class="hljs-keyword">if</span> (fd &lt; <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"failed to create socket: %d\n"</span>, fd);
        <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
    }
    <span class="hljs-keyword">return</span> fd;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">get_udp_address</span><span class="hljs-params">(<span class="hljs-keyword">char</span> *server_name, <span class="hljs-keyword">char</span> server_port[], struct addrinfo **server_addr_info)</span> </span>{

    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">addrinfo</span> <span class="hljs-title">hint</span> = {</span><span class="hljs-number">0</span>};

        hint.ai_family = AF_INET;
        hint.ai_socktype = SOCK_DGRAM;

        <span class="hljs-keyword">int</span> status = getaddrinfo(server_name, server_port, &amp;hint, server_addr_info);

        <span class="hljs-keyword">if</span> (status != <span class="hljs-number">0</span>) {
                <span class="hljs-built_in">printf</span>(<span class="hljs-string">"getaddrinfo failed: %d\n"</span>, status);
                <span class="hljs-keyword">return</span> status;
        }
    <span class="hljs-keyword">return</span> status;

}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">int</span> argc, <span class="hljs-keyword">char</span> *argv[])</span> </span>{
    <span class="hljs-keyword">if</span> ( argc != <span class="hljs-number">2</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Need server address\n"</span>);
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    }

    <span class="hljs-keyword">char</span> *server_name = argv[<span class="hljs-number">1</span>];
    <span class="hljs-comment">// I initially kept this 50000, but the success rate wasn't good enough,</span>
    <span class="hljs-comment">// so I kept it same as traceroute default port, looks like more fw allows traffic on it</span>
    <span class="hljs-keyword">char</span> server_port[] = <span class="hljs-string">"33434"</span>;
    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">addrinfo</span> *<span class="hljs-title">server_addr_info</span>;</span>

    <span class="hljs-keyword">int</span> status = get_udp_address(server_name, server_port, &amp;server_addr_info);

    <span class="hljs-keyword">if</span> ( status != <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    };


    <span class="hljs-keyword">int</span> socket_fd = get_udp_socket();

    <span class="hljs-keyword">char</span> recv_buffer[<span class="hljs-number">1024</span>];
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">char</span> *msg = <span class="hljs-string">"辿"</span>;

    <span class="hljs-comment">// Each packet size will be: ipv4 header (20 bytes) + udp header(8 bytes) + msg (3 bytes) = Total(31 bytes)</span>

    fd_set readfds;
    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">timeval</span> <span class="hljs-title">tv</span>;</span>

    <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> allow dynamic size packets later</span>
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%s を辿る, 32 byte packets\n"</span>, server_name);

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> hop = <span class="hljs-number">1</span>; hop &lt; <span class="hljs-number">31</span>; hop++) { <span class="hljs-comment">// staring from 1 as ttl 0 not valid</span>
        <span class="hljs-keyword">int</span> status_code = setsockopt(socket_fd, IPPROTO_IP, IP_TTL, &amp;hop, <span class="hljs-keyword">sizeof</span>(hop));
        <span class="hljs-keyword">if</span> ( status_code !=<span class="hljs-number">0</span>) {
             perror(<span class="hljs-string">"setsockopt"</span>);
            <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
        }

        <span class="hljs-keyword">int</span> on = <span class="hljs-number">1</span>;
        status_code = setsockopt(socket_fd, IPPROTO_IP, IP_RECVERR, &amp;on, <span class="hljs-keyword">sizeof</span>(on));
        <span class="hljs-keyword">if</span> ( status_code !=<span class="hljs-number">0</span>) {
            perror(<span class="hljs-string">"setsockopt"</span>);
            <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
        }

        FD_ZERO(&amp;readfds);
        FD_SET(socket_fd, &amp;readfds);

        tv.tv_sec = <span class="hljs-number">2</span>;
        tv.tv_usec = <span class="hljs-number">0</span>;

        sendto(socket_fd, msg, <span class="hljs-built_in">strlen</span>(msg), <span class="hljs-number">0</span>, server_addr_info-&gt;ai_addr, server_addr_info-&gt;ai_addrlen);

        <span class="hljs-keyword">int</span> ret = select(socket_fd+<span class="hljs-number">1</span>, &amp;readfds, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, &amp;tv);

        <span class="hljs-keyword">if</span> ( ret &gt; <span class="hljs-number">0</span> &amp;&amp; FD_ISSET(socket_fd, &amp;readfds) ) {

            <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">msghdr</span> <span class="hljs-title">resp_msg</span> = {</span><span class="hljs-number">0</span>};
            <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">iovec</span> <span class="hljs-title">iov</span>;</span>
            <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">sockaddr_in</span> <span class="hljs-title">sender_addr</span>;</span> <span class="hljs-comment">// for remote addr</span>

            iov.iov_base = recv_buffer;  <span class="hljs-comment">// to store the data</span>
            iov.iov_len = <span class="hljs-keyword">sizeof</span>(recv_buffer) - <span class="hljs-number">1</span>;

            resp_msg.msg_name = &amp;sender_addr;  <span class="hljs-comment">// to store the ip and other info of the sender</span>
            resp_msg.msg_namelen = <span class="hljs-keyword">sizeof</span>(sender_addr);
            resp_msg.msg_iov = &amp;iov;
            resp_msg.msg_iovlen = <span class="hljs-number">1</span>;

            <span class="hljs-keyword">char</span> control_buffer[<span class="hljs-number">512</span>];  <span class="hljs-comment">// to store the errors</span>
            resp_msg.msg_control = control_buffer;
            resp_msg.msg_controllen = <span class="hljs-keyword">sizeof</span>(control_buffer);

            <span class="hljs-keyword">ssize_t</span> bytes_read = recvmsg(socket_fd, &amp;resp_msg, MSG_ERRQUEUE);
            <span class="hljs-keyword">if</span> (bytes_read &lt; <span class="hljs-number">0</span>) {
                perror(<span class="hljs-string">"recvmsg"</span>);
            }
            <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">cmsghdr</span> *<span class="hljs-title">cmsg</span>;</span>
                <span class="hljs-keyword">for</span> (cmsg = CMSG_FIRSTHDR(&amp;resp_msg); cmsg != <span class="hljs-literal">NULL</span>; cmsg = CMSG_NXTHDR(&amp;resp_msg, cmsg)) {

                    <span class="hljs-comment">// checking message level is ipv4 and type is error</span>
                    <span class="hljs-keyword">if</span> ( cmsg-&gt;cmsg_level == SOL_IP &amp;&amp; cmsg-&gt;cmsg_type == IP_RECVERR) {
                        <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">sock_extended_err</span> *<span class="hljs-title">err_msg</span> = (<span class="hljs-title">struct</span> <span class="hljs-title">sock_extended_err</span> *)<span class="hljs-title">CMSG_DATA</span>(<span class="hljs-title">cmsg</span>);</span>
                        <span class="hljs-keyword">if</span> ( err_msg-&gt;ee_origin == SO_EE_ORIGIN_ICMP ) {
                            <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">sockaddr_in</span> *<span class="hljs-title">sin</span> = (<span class="hljs-title">struct</span> <span class="hljs-title">sockaddr_in</span> *)(<span class="hljs-title">err_msg</span>+1);</span>
                            <span class="hljs-keyword">char</span> ip_str[INET_ADDRSTRLEN];
                            inet_ntop(AF_INET, &amp;<span class="hljs-built_in">sin</span>-&gt;sin_addr, ip_str, <span class="hljs-keyword">sizeof</span>(ip_str));
                            <span class="hljs-keyword">if</span> ( err_msg-&gt;ee_type == ICMP_TIME_EXCEEDED) {
                                <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d: %s\n"</span>, hop, ip_str);
                            } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> ( err_msg-&gt;ee_type == ICMP_UNREACH) {
                                <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d: Dest reached: %s\n"</span>, hop, ip_str);
                                <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
                            }
                        }
                    }
                }
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d: * * *\n"</span>, hop);
        }
    }
    close(socket_fd);
    freeaddrinfo(server_addr_info);
}
</code></pre>
<p>What I’m doing is, creating a socket and changing the TTL on each iteration and allowing the control messages on the socket explicitly, as only responses are buffered in the socket by the kernel, the error messages are discarded by default. I’m also setting a read timeout for the sanity.</p>
<p>Some pitfalls that I encountered:</p>
<ul>
<li><p>Usage of ports other than <code>33434</code> has very less success rate, my guess is that firewalls on the internet accustomed to it because of the historical reason of traceroute, idk.</p>
</li>
<li><p><code>select()</code> notifying when I set <code>read_fd</code> not <code>error_fd</code>.</p>
</li>
<li><p>The signature of <code>recvmsg</code>, <code>msghdr</code> and <code>cmsghdr</code>, aren’t very intuitive. I tried to understand the reasoning behind its design but wasn’t able to find any solid reading material.</p>
</li>
</ul>
<p>The above code is also available at my GitHub: <a target="_blank" href="https://github.com/cosmicoppai/tadoru">Cosmicoppai/tadoru: Traceroute clone built for fun</a></p>
]]></content:encoded></item><item><title><![CDATA[Bastion Host]]></title><description><![CDATA[Learn what a Bastion Host is, why it's essential for securing SSH access to private servers, and how to configure one using ProxyJump. Includes practical…]]></description><link>https://cosmicoppai.com/bastion-host</link><guid isPermaLink="true">https://cosmicoppai.com/bastion-host</guid><category><![CDATA[networking]]></category><category><![CDATA[network security]]></category><category><![CDATA[ssh]]></category><category><![CDATA[Bastion Hosts]]></category><category><![CDATA[jumpserver]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Thu, 19 Jun 2025 10:15:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/UVTXR-4wUY0/upload/76f210fc861c43febd6622fd150bacaf.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Bastion host or server is a server mainly for jumping connection, especially ssh connection. It’s also known as jump server</p>
<p>The reason is mainly for security and to reduce the attack surface. Only bastion server is exposed to the outer world and all rest of the server lives in the internal network or firewall.</p>
<p>This configuration ensures that you only need to take care of the security of one server resulting into strengthen security across all your infra.</p>
<h3 id="heading-setup">Setup:</h3>
<pre><code class="lang-yaml"><span class="hljs-attr">services:</span>
  <span class="hljs-attr">bastion:</span>
    <span class="hljs-attr">build:</span>
      <span class="hljs-attr">dockerfile:</span> <span class="hljs-string">bastion</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">'6969:22'</span>

  <span class="hljs-attr">server1:</span>
    <span class="hljs-attr">build:</span>
      <span class="hljs-attr">dockerfile:</span> <span class="hljs-string">client</span>


  <span class="hljs-attr">server2:</span>
    <span class="hljs-attr">build:</span>
      <span class="hljs-attr">dockerfile:</span> <span class="hljs-string">client</span>
</code></pre>
<p>Here, I have 3 servers, one is working as bastion host and exposed to the host and rest two are in the separate network not accessible from outside.</p>
<p>Let’s see how the Dockerfile for Bastion and clients look like</p>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># For Bastion</span>
<span class="hljs-keyword">FROM</span> ubuntu:<span class="hljs-number">25.04</span> <span class="hljs-comment"># Using ubuntu 25 as my base image</span>

<span class="hljs-comment"># installing openssh and creating necessary dir</span>
<span class="hljs-keyword">RUN</span><span class="bash"> apt update -y &amp;&amp; apt install openssh-server -y &amp;&amp; mkdir -p /root/.ssh/</span>

<span class="hljs-comment"># Here I'm copying my ssh config into the container, we'll look at it later</span>
<span class="hljs-keyword">COPY</span><span class="bash"> ssh_config/bastion/config /etc/ssh/sshd_config</span>

<span class="hljs-comment"># Copying my public key, so I can access it</span>
<span class="hljs-keyword">COPY</span><span class="bash"> ssh_config/bastion/authorized_keys /root/.ssh/</span>

<span class="hljs-keyword">EXPOSE</span> <span class="hljs-number">22</span>

<span class="hljs-comment"># changing file permission of my key and testing sshd config </span>
<span class="hljs-keyword">RUN</span><span class="bash"> ls /root/.ssh/ &amp;&amp; chmod 700 /root/.ssh/ &amp;&amp; \
    chmod 600 /root/.ssh/authorized_keys &amp;&amp; \
    sshd -t -f /etc/ssh/sshd_config</span>

<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"/usr/sbin/sshd"</span>, <span class="hljs-string">"-D"</span>]  <span class="hljs-comment"># Running ssd in foreground</span></span>
</code></pre>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># For client same as bastion, only change is in ssh config, I'll show you that in the next step</span>

<span class="hljs-keyword">FROM</span> ubuntu:<span class="hljs-number">25.04</span>

<span class="hljs-keyword">RUN</span><span class="bash"> apt update -y &amp;&amp; apt install openssh-server -y &amp;&amp; mkdir -p /root/.ssh/</span>

<span class="hljs-keyword">COPY</span><span class="bash"> ssh_config/client/config /etc/ssh/sshd_config</span>

<span class="hljs-keyword">COPY</span><span class="bash"> ssh_config/client/authorized_keys /root/.ssh/</span>

<span class="hljs-keyword">EXPOSE</span> <span class="hljs-number">22</span>

<span class="hljs-keyword">RUN</span><span class="bash"> chmod 700 /root/.ssh/ &amp;&amp; \
    chmod 600 /root/.ssh/authorized_keys &amp;&amp; \
    sshd -t -f /etc/ssh/sshd_config</span>

<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"/usr/sbin/sshd"</span>, <span class="hljs-string">"-D"</span>]</span>
</code></pre>
<p>The sshd server config for bastion and normal servers:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># minimal sshd config for bastion</span>

Port 22  <span class="hljs-comment"># exposing my ssh server to port 22, in prod you can set to some diff port to trick basic bots</span>
LogLevel VERBOSE

<span class="hljs-comment"># PermitRootLogin should be disbaled and there should be seperate user for jump,</span>
<span class="hljs-comment"># I kept root cuz of laziness while writing this article</span>
PermitRootLogin yes
PubkeyAuthentication yes  <span class="hljs-comment"># to authenticate via pub/private keys</span>
AuthorizedKeysFile     .ssh/authorized_keys
PasswordAuthentication no  <span class="hljs-comment"># to disable login via password</span>

<span class="hljs-comment"># Below, for user roor we are disabling tunneling, port forwarding, tty session</span>
<span class="hljs-comment"># Because this server should only act as a jump and shouldn't be allow to access for any other purpose.</span>
<span class="hljs-comment"># In prod, any other type of access should be done via cloud console</span>
Match User root  
    PermitTTY no
    AllowAgentForwarding no
    AllowStreamLocalForwarding no
    X11Forwarding no
    PermitTunnel no
    GatewayPorts no
    ForceCommand /usr/sbin/nologin
</code></pre>
<p>The above <code>sshd</code> config is to disallow any type of ssh request except the Jump request</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sshd config for servers behind the bastion server</span>
Port 22
PermitRootLogin yes  <span class="hljs-comment"># can be kept like this</span>
PubkeyAuthentication yes  <span class="hljs-comment"># auth via keys are allowed</span>
PasswordAuthentication no  <span class="hljs-comment"># password login is  disabled</span>
</code></pre>
<p>The above configuration is for server behind the bastion, and it should only be accessible via bastion. So, these servers should be placed in internal network or there should be proper firewall to disable access from any other source.</p>
<p>That’s all, now to access any server all you have to do is:</p>
<p><code>ssh -J &lt;jump_user&gt;@&lt;jump_server&gt; &lt;user&gt;@&lt;actual_server&gt;</code>  </p>
<p>To avoid running long command you can setup ssh config file:<br />Open <code>~/.ssh/config</code> and paste</p>
<pre><code class="lang-bash">Host jump-host
    HostName localhost  <span class="hljs-comment"># jump serevr host</span>
    Port 6969  <span class="hljs-comment">#jump server port</span>
    User root  <span class="hljs-comment"># jump server user</span>
    IdentityFile ~/temp/<span class="hljs-built_in">test</span>  <span class="hljs-comment"># location of the private key</span>
    IdentitiesOnly yes

Host server1
    HostName server1  <span class="hljs-comment"># actual server host</span>
    User root  <span class="hljs-comment"># actual server user</span>
    ProxyJump jump-host  <span class="hljs-comment"># to tell, to use jump server during ssh</span>
    IdentityFile ~/temp/<span class="hljs-built_in">test</span>
    IdentitiesOnly yes

Host server2
    HostName server2
    User root
    ProxyJump jump-host
    IdentityFile ~/temp/<span class="hljs-built_in">test</span>
    IdentitiesOnly yes
</code></pre>
<p>Now, you can simply do<br /><code>ssh server1</code> or <code>ssh server2</code>, and it’ll leverage the jump server for the connection.</p>
<p>You can check out the whole containerized version of this article <a target="_blank" href="https://github.com/Cosmicoppai/bastion">here</a>:<br /><a target="_blank" href="https://github.com/Cosmicoppai/bastion">Cosmicoppai/bastion: Demonstration of Bastion Config via containers</a></p>
]]></content:encoded></item><item><title><![CDATA[Restoring MySQL replica from source]]></title><description><![CDATA[Restoring replica from master]]></description><link>https://cosmicoppai.com/storing-mysql-replica-from-source</link><guid isPermaLink="true">https://cosmicoppai.com/storing-mysql-replica-from-source</guid><category><![CDATA[MySQL]]></category><category><![CDATA[master slave]]></category><category><![CDATA[Relational Database]]></category><category><![CDATA[Relationship]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Mon, 24 Mar 2025 18:53:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/uTFiFYeQhlI/upload/1ead4694e4ac8282eff0627d40d391c8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, I’m going to dig into, how you can restore your replica from the source. The reason can vary from huge lag to data discrepancy etc…</p>
<p>The overview of steps would look like:</p>
<ol>
<li><p>Note the master LOG_POS and LOG_FILE</p>
</li>
<li><p>Take snapshot of data volume of the source and attach to replica</p>
</li>
<li><p>Stop the MySQL and update config on replica</p>
</li>
<li><p>RESET SLAVE CONFIG</p>
</li>
</ol>
<ol>
<li>First, we need to note down the position of master, later we’ll need it to reset the replica  </li>
</ol>
<pre><code class="lang-bash">SHOW MASTER STATUS \G;
&gt;&gt;&gt;*************************** 1. row ***************************
File: mysql-bin.1084550
Position: 240645285
Binlog_Do_DB: <span class="hljs-built_in">test</span>,lol,hehe
Binlog_Ignore_DB:
Executed_Gtid_Set:
1 row <span class="hljs-keyword">in</span> <span class="hljs-built_in">set</span> (0.00 sec)
</code></pre>
<p>You need to note down the Filename and Position.</p>
<ol start="2">
<li>After, noting down the File name and Log position we can take a snapshot of the data-volume/disk, I’m assuming you’re on cloud ecosystem. For cloud provider like DO, this step would look like:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-comment"># Take snapshot</span>
doctl compute volume snapshot &lt;vol_id&gt; --snapshot-name &lt;snapshot_name&gt;

<span class="hljs-comment"># Create Volume from that snapshot</span>
doctl compute volume create &lt;vol_name&gt; --snapshot &lt;snapshot_id&gt; --size &lt;size <span class="hljs-keyword">in</span> Tb&gt;

<span class="hljs-comment"># Attach that volume to the replica</span>
doctl compute volume-action attach &lt;vol_id&gt; &lt;droplet_id&gt;

<span class="hljs-comment"># Create fs and attach block device</span>
sudo mkdir -p /new_replica_data_dir

sudo mount /dev/sdb /mnt/new_replica_data_dir
</code></pre>
<ol start="3">
<li>Stop the MySQL and update config</li>
</ol>
<pre><code class="lang-bash">systemctl stop mysql

<span class="hljs-comment"># change data-dir  in mysql conf</span>
datadir         = /mnt/new_replica_data_dir

<span class="hljs-comment"># remove the auto.cnf file, this file will get regenerated on restart</span>
rm /mnt/wsdbhr_mysql/mysql/auto.cnf

<span class="hljs-comment"># start the DB</span>
systemctl start mysql

<span class="hljs-comment"># monitor error logs</span>
tail -f /var/<span class="hljs-built_in">log</span>/mysql/error.log
</code></pre>
<ol start="4">
<li>RESET SLAVE CONFIG</li>
</ol>
<pre><code class="lang-bash">STOP SLAVE;

RESET SLAVE;

CHANGE MASTER TO MASTER_HOST=<span class="hljs-string">'x.x.x.x'</span>, MASTER_USER=<span class="hljs-string">'replica_user'</span>, MASTER_PASSWORD=<span class="hljs-string">'...'</span>, MASTER_LOG_FILE=<span class="hljs-string">'mysql-bin.1084550'</span>, MASTER_LOG_POS=240645285;

START SLAVE;

<span class="hljs-comment"># verify if all correct and there are no IO and SQL errors</span>
SHOW SLAVE STATUS \G;
</code></pre>
<p>After these steps, there will be some replication lag directly related to amount of time spent on whole process, but if there is no error, your replica will catchup and lag should be gone along with any data discrepancy.</p>
<p>Note: Some of you might need to update apparmor and fstab configs, if it was previously setup.</p>
]]></content:encoded></item><item><title><![CDATA[pt-table-sync]]></title><description><![CDATA[Fix database inconsistency and data discrepancies]]></description><link>https://cosmicoppai.com/pt-table-sync</link><guid isPermaLink="true">https://cosmicoppai.com/pt-table-sync</guid><category><![CDATA[pt-table-sync]]></category><category><![CDATA[MySQL]]></category><category><![CDATA[percona]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Mon, 17 Mar 2025 21:30:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/pGHRUV5tPVI/upload/741a29b51a73ca443321ddad7d69bca5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently had a situation when a lot of rows from one of our replicas was missing.<br />One of the solutions that came in mind is to use the snapshot of the source and reconfigure it as replica. While this would have worked, it seemed like an extreme approach for what might be a localized issue.</p>
<p>After digging into the logs after a while, the problem seems to be only isolated to a single table. So, I tried <code>pt-table-sync</code>.</p>
<h3 id="heading-what-is-pt-table-sync">What is pt-table-sync?</h3>
<p><strong>pt-table-sync</strong> is a command-line utility that helps synchronize data across different MySQL servers. It can be used in various scenarios, such as:</p>
<ul>
<li><p>Synchronizing data between a <strong>source and its replica</strong></p>
</li>
<li><p>Resolving inconsistencies between two <strong>source servers</strong></p>
</li>
<li><p>Comparing and fixing differences between <strong>any two MySQL data sources</strong></p>
</li>
</ul>
<p>The synchronization command looks like this:</p>
<pre><code class="lang-bash">pt-table-sync --execute h=x.x.x.x,D=database,t=table,u=user,p=pass h=localhost,u=user,p=pass
</code></pre>
<p>Here’s what each parameter does:</p>
<ul>
<li><p><code>h=x.x.x.x</code> → The <strong>host</strong> of the source database (where data is correct)</p>
</li>
<li><p><code>D=database</code> → The <strong>database name</strong></p>
</li>
<li><p><code>t=table</code> → The <strong>table name</strong> that needs synchronization</p>
</li>
<li><p><code>u=user</code> / <code>p=pass</code> → <strong>MySQL credentials</strong> for authentication</p>
</li>
<li><p><code>h=localhost</code> → The <strong>replica server</strong> where data needs to be fixed</p>
</li>
</ul>
<p><code>pt-table-sync</code> generally sync data from the replica to the source, i.e. from the 2nd data source to the first as changes to the replica are usually the source of the problems in the first place. i.e. the changes made on the source will be replicated down the replica via the normal replication process.</p>
<h3 id="heading-how-pt-table-sync-works">How pt-table-sync Works</h3>
<p>The synchronization process in <strong>pt-table-sync</strong> consists of three main operations:</p>
<ul>
<li><p><strong>UPDATE</strong> →For stale data NOOP operation is triggered on source, that only affects the replica.</p>
</li>
<li><p><strong>DELETE</strong> → DELETE statements on the source for rows that don't exist there but exist in replica.</p>
</li>
<li><p><strong>INSERT</strong> → For missing data, that exist on source but not on replica. It’s retriggered so it can pass via binary logs</p>
</li>
</ul>
<p>By default, <strong>pt-table-sync</strong> generates and executes these statements to bring the replica in sync with the source. If you want to preview these operations before executing them, you can use:</p>
<pre><code class="lang-bash">pt-table-sync --<span class="hljs-built_in">print</span> h=x.x.x.x,D=database,t=table,u=user,p=pass h=localhost,u=user,p=pass
</code></pre>
<p>This prints out the SQL statements that would be executed, allowing you to review changes before applying them.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Python Slots]]></title><description><![CDATA[Save memory using python slots]]></description><link>https://cosmicoppai.com/slots-in-python</link><guid isPermaLink="true">https://cosmicoppai.com/slots-in-python</guid><category><![CDATA[python-slots]]></category><category><![CDATA[Python]]></category><category><![CDATA[low level design]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Fri, 08 Nov 2024 23:54:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/_68ATDXuBLo/upload/45ccb25686b5f4edd4aedc35f18bd8b9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>How about explicitly declaring class attributes or reducing memory footprint of class variables. Slots seems to be an answer.  </p>
<p>slots (__slots__) a special class variable that is assigned a sequence of strings that are variable names used by instance.</p>
<p>Example:  </p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>:</span>
    __slots__ = (<span class="hljs-string">"brand_name"</span>, )

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.brand_name = <span class="hljs-string">"kia"</span>


c = Car()
print(c.brand_name)

```
kia
```
</code></pre>
<p>The <code>__slot__</code> declaration allows us to explicitly declare data members, which helps python to explicitly reserve space for them in memory and prevents the creation of <code>__dict__</code> and <code>__weakref__</code> attributes.  </p>
<p>It also prevents the creation of any variables that aren’t declared in the <code>__slots__</code> , doing so will result in AttributeError  </p>
<pre><code class="lang-python">c.price=<span class="hljs-number">1000</span>

Traceback (most recent call last):
  File <span class="hljs-string">"C:\Users\cosmi\PycharmProjects\python-mastery\my_solutions\test.py"</span>, line <span class="hljs-number">32</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    b.price = <span class="hljs-number">1000</span>
    ^^^^^^^
AttributeError: <span class="hljs-string">'Car'</span> object has no attribute <span class="hljs-string">'price'</span> <span class="hljs-keyword">and</span> no __dict__ <span class="hljs-keyword">for</span> setting new attributes
</code></pre>
<p>It also more efficient in terms of memory and speed.</p>
<p>Let’s compare the memory usage of a normal class and and <code>__slot__</code> class.  </p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>:</span>
    <span class="hljs-string">"""
    Regular classes use a __dict__ for attributes
    """</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.brand_name = <span class="hljs-string">"hyundai"</span>


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ECar</span>:</span>
    __slots__ = (<span class="hljs-string">"brand_name"</span>, )  <span class="hljs-comment"># this will prevent declaration of new slots</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self.brand_name = <span class="hljs-string">"kia"</span>


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    <span class="hljs-keyword">import</span> tracemalloc

    tracemalloc.start()

    a = Car()
    <span class="hljs-comment"># a.price = 1000</span>
    print(<span class="hljs-string">"current memory: {} \n peak memory: {}"</span>.format(*tracemalloc.get_traced_memory()))

    tracemalloc.stop()

    <span class="hljs-keyword">del</span> a

    tracemalloc.start(<span class="hljs-number">10</span>)

    b = ECar()
    <span class="hljs-comment"># b.price = 1000</span>

    print(<span class="hljs-string">"current memory: {} \n peak memory: {}"</span>.format(*tracemalloc.get_traced_memory()))

current memory: <span class="hljs-number">400</span> 
 peak memory: <span class="hljs-number">400</span>
current memory: <span class="hljs-number">112</span> 
 peak memory: <span class="hljs-number">112</span>
</code></pre>
<p>As we can see it’s uses almost 4x less memory, my example is sort of insignificant from real life perspective, but hope you got the idea.</p>
<p>Conclusion: <code>__slots__</code> are simple efficient and safe approach to python’s default attribute access.</p>
]]></content:encoded></item><item><title><![CDATA[Schema change without locking.]]></title><description><![CDATA[Performing schema changes on production databases comes with significant overhead, such as locking entire tables and potentially causing replication lag.]]></description><link>https://cosmicoppai.com/schema-change-without-locking</link><guid isPermaLink="true">https://cosmicoppai.com/schema-change-without-locking</guid><category><![CDATA[Databases]]></category><category><![CDATA[MySQL]]></category><category><![CDATA[percona]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Fri, 13 Sep 2024 14:03:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/EqC7y72PLAY/upload/01e09f0ffaead64fd1f1fe0491277cdd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Performing schema changes on production databases comes with significant overhead, such as locking entire tables and potentially causing replication lag in master-slave architectures. For MySQL and its variants, there's a powerful tool that mitigates these issues: pt-online-schema-change.</p>
<h2 id="heading-what-is-pt-online-schema-change">What is pt-online-schema-change?</h2>
<p>pt-online-schema-change is a tool that alters a table's structure without blocking reads or writes, making it ideal for use in production environments.</p>
<h2 id="heading-how-it-works">How It Works</h2>
<ol>
<li><p><strong>Table Copying</strong>: It creates an empty copy of the table with the desired alterations.</p>
</li>
<li><p><strong>Data Migration</strong>: It copies rows from the original table to the new one in small, manageable chunks.</p>
</li>
<li><p><strong>Real-time Updates</strong>: During the copy process, any modifications to the original table are reflected in the new table using triggers.</p>
</li>
<li><p><strong>Atomic Swap</strong>: Once copying is complete, it uses an atomic <code>RENAME TABLE</code> operation to switch the old and new tables.</p>
</li>
<li><p><strong>Cleanup</strong>: Finally, it drops the original table.</p>
</li>
</ol>
<h2 id="heading-key-features-and-safety-measures">Key Features and Safety Measures</h2>
<ul>
<li><p><strong>Chunk-based Processing</strong>: Data is copied in small chunks, optimized for performance (configurable with <code>--chunk-time</code>).</p>
</li>
<li><p><strong>Trigger Mechanism</strong>: Ensures data consistency during the migration process.</p>
</li>
<li><p><strong>Foreign Key Handling</strong>: Supports methods to update foreign key references after the schema change.</p>
</li>
<li><p><strong>Safety Checks</strong>:</p>
<ul>
<li><p>Requires a PRIMARY KEY or UNIQUE INDEX in most cases.</p>
</li>
<li><p>Detects and respects replication filters.</p>
</li>
<li><p>Pauses operations if replicas lag behind.</p>
</li>
<li><p>Monitors server load and can pause or abort if thresholds are exceeded.</p>
</li>
<li><p>Sets conservative lock wait timeouts to minimize disruption.</p>
</li>
<li><p>Careful handling of foreign key constraints.</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-considerations">Considerations</h2>
<ul>
<li><p>By default, it doesn't modify the table unless the <code>--execute</code> option is specified.</p>
</li>
<li><p>It may rename foreign keys and indexes slightly to avoid naming collisions.</p>
</li>
<li><p>Existing triggers on the table will prevent the tool from working.</p>
</li>
</ul>
<h2 id="heading-example-usage">Example Usage</h2>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

USERNAME=<span class="hljs-string">"root"</span>
PASSWORD=<span class="hljs-string">"your_password_here"</span>
HOST=<span class="hljs-string">"localhost"</span>
DATABASE=<span class="hljs-string">"critical_db"</span>
TABLE=<span class="hljs-string">"critical_table"</span>
ALTER_STATEMENT=<span class="hljs-string">"ADD COLUMN guest VARCHAR(45), ADD COLUMN name VARCHAR(100)"</span>

<span class="hljs-keyword">if</span> [[ <span class="hljs-string">"<span class="hljs-variable">$1</span>"</span> == <span class="hljs-string">"--execute"</span> ]]; <span class="hljs-keyword">then</span>
    EXECUTE=<span class="hljs-literal">true</span>
<span class="hljs-keyword">else</span>
    EXECUTE=<span class="hljs-literal">false</span>
<span class="hljs-keyword">fi</span>

<span class="hljs-built_in">echo</span> <span class="hljs-string">"Performing dry run..."</span>
pt-online-schema-change \
    --user=<span class="hljs-string">"<span class="hljs-variable">$USERNAME</span>"</span> \
    --password=<span class="hljs-string">"<span class="hljs-variable">$PASSWORD</span>"</span> \
    --host=<span class="hljs-string">"<span class="hljs-variable">$HOST</span>"</span> \
    D=<span class="hljs-string">"<span class="hljs-variable">$DATABASE</span>"</span>,t=<span class="hljs-string">"<span class="hljs-variable">$TABLE</span>"</span> \
    --alter=<span class="hljs-string">"<span class="hljs-variable">$ALTER_STATEMENT</span>"</span> \
    --preserve-triggers \
    --dry-run

<span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$EXECUTE</span>"</span> = <span class="hljs-literal">true</span> ]; <span class="hljs-keyword">then</span>
    <span class="hljs-built_in">echo</span> <span class="hljs-string">"Applying changes..."</span>
    pt-online-schema-change \
        --user=<span class="hljs-string">"<span class="hljs-variable">$USERNAME</span>"</span> \
        --password=<span class="hljs-string">"<span class="hljs-variable">$PASSWORD</span>"</span> \
        --host=<span class="hljs-string">"<span class="hljs-variable">$HOST</span>"</span> \
        D=<span class="hljs-string">"<span class="hljs-variable">$DATABASE</span>"</span>,t=<span class="hljs-string">"<span class="hljs-variable">$TABLE</span>"</span> \
        --alter=<span class="hljs-string">"<span class="hljs-variable">$ALTER_STATEMENT</span>"</span> \
        --preserve-triggers \
        --execute
<span class="hljs-keyword">fi</span>
</code></pre>
<p>To use this script:</p>
<ol>
<li><p>Save it to a file (e.g., <code>alter_</code><a target="_blank" href="http://table.sh"><code>table.sh</code></a>)</p>
</li>
<li><p>Make it executable: <code>chmod +x alter_</code><a target="_blank" href="http://table.sh"><code>table.sh</code></a></p>
</li>
<li><p>Run a dry run: <code>./alter_</code><a target="_blank" href="http://table.sh"><code>table.sh</code></a></p>
</li>
<li><p>Execute the changes: <code>./alter_</code><a target="_blank" href="http://table.sh"><code>table.sh</code></a> <code>--execute</code></p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>pt-online-schema-change offers a robust solution for performing schema changes in production environments, minimizing downtime and reducing the risks associated with traditional ALTER TABLE operations.</p>
]]></content:encoded></item><item><title><![CDATA[Character Vs Byte]]></title><description><![CDATA[The "characters vs bytes bug" usually refers to an issue that arises in programming when there is confusion between the number of characters and the number…]]></description><link>https://cosmicoppai.com/character-vs-byte</link><guid isPermaLink="true">https://cosmicoppai.com/character-vs-byte</guid><category><![CDATA[Computer Science]]></category><category><![CDATA[encoding]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Mon, 29 Jul 2024 23:36:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/wGKx2iEPqbo/upload/06aad3e8d339c5681c2c5cc7438a748d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The "characters vs bytes bug" usually refers to an issue that arises in programming when there is confusion between the number of characters and the number of bytes in a string. This is a common issue in languages and systems where the encoding of characters can mean that the number of characters and the number of bytes is not the same.</p>
<p>Here's an overview of the concept:</p>
<ol>
<li><p><strong>Characters</strong>: These are the individual symbols in a string, like letters, numbers, punctuation marks, and so on. In English and other languages that use a Latin-based alphabet, characters are often equivalent to the letters of the alphabet.</p>
</li>
<li><p><strong>Bytes</strong>: A byte is a unit of digital information that most commonly consists of eight bits. In computer systems, a byte is the amount of memory needed to store one character, but only when that character is part of an encoding that uses 8-bit code units (like ASCII).</p>
</li>
</ol>
<p>The bug often occurs due to the following reasons:</p>
<ul>
<li><p><strong>Variable-Length Encoding</strong>: In encodings like UTF-8, characters can use different numbers of bytes. For instance, ASCII characters use one byte, but many non-ASCII characters use two or more bytes.</p>
</li>
<li><p><strong>Assumption of One Byte Per Character</strong>: Some programmers incorrectly assume one byte per character, which is true for ASCII but not for UTF-8 or other multi-byte character encodings.</p>
</li>
<li><p><strong>String Operations</strong>: When slicing strings, finding lengths, or manipulating them based on byte indices instead of character indices, you can end up with garbled text. For instance, if you split a UTF-8 string thinking that each character is one byte, you may cut a multi-byte character in half, leading to invalid characters.</p>
</li>
<li><p><strong>Data Storage and Transmission</strong>: When a system is not configured to handle multi-byte characters correctly, it can cause errors in storing or transmitting text, such as truncation of strings or incorrect string lengths.</p>
</li>
<li><p><strong>Localization and Internationalization Issues</strong>: Software that is not designed with internationalization in mind may work fine with languages that have characters represented by a single byte but will fail with languages that require more complex encoding.</p>
</li>
</ul>
<p>To avoid such bugs, it's important to handle strings in a way that respects the encoding being used and to use functions and methods that are aware of the encoding to count characters and manipulate strings. This often involves using specific string functions that count characters rather than bytes or using programming languages and libraries that default to character-safe</p>
<p>operations. For example, in Ruby, you should use <code>String#length</code> or <code>String#chars</code> to deal with characters correctly in UTF-8 strings, rather than relying on byte-oriented operations unless you're doing specific byte-level data manipulation.</p>
<p>Let's look at one example  </p>
<pre><code class="lang-python"><span class="hljs-comment"># Example string containing both ASCII and non-ASCII characters</span>
example_string = <span class="hljs-string">"Hello, 世界!"</span>

<span class="hljs-comment"># Length in terms of characters</span>
print(len(example_string))

<span class="hljs-comment"># Encoding the string to UTF-8 bytes</span>
utf8_bytes = example_string.encode(<span class="hljs-string">'utf-8'</span>)
print(len(utf8_bytes))

<span class="hljs-keyword">try</span>:
    invalid_slice = utf8_bytes[<span class="hljs-number">0</span>:<span class="hljs-number">10</span>].decode(<span class="hljs-string">'utf-8'</span>)
    print(<span class="hljs-string">f"Invalid slice: <span class="hljs-subst">{invalid_slice}</span>"</span>)
<span class="hljs-keyword">except</span> UnicodeDecodeError <span class="hljs-keyword">as</span> e:
    print(<span class="hljs-string">f"UnicodeDecodeError: <span class="hljs-subst">{e}</span>"</span>)

print(example_string[<span class="hljs-number">0</span>:<span class="hljs-number">10</span>])
</code></pre>
<pre><code class="lang-bash">10
14
Invalid slice: Hello, 世
Hello, 世界!
</code></pre>
<p>Look when we try to slice the bytes, we get unexpected result which is not the case when we slice the characters.</p>
]]></content:encoded></item><item><title><![CDATA[Zero, Zero, What Are You? A Deep Dive into Type Conversion]]></title><description><![CDATA[Understanding character encoding and type conversion]]></description><link>https://cosmicoppai.com/zero-zero-what-are-you-a-deep-dive-into-type-conversion</link><guid isPermaLink="true">https://cosmicoppai.com/zero-zero-what-are-you-a-deep-dive-into-type-conversion</guid><category><![CDATA[Python]]></category><category><![CDATA[ascii]]></category><category><![CDATA[unicode]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Wed, 24 Jul 2024 21:07:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721855163589/9d8eb72e-5ce8-445d-86a7-f27ed4c7c3f3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Almost every computer uses a text input buffer for handling user input, providing feasibility and wide-ranging support across various applications. However, it may not be immediately apparent how the characters we type are converted internally for numeric manipulation. Let's dive into how computers store and process input from the keyboard.</p>
<p>When you type a number like "10" on your keyboard, your first assumption might be that it's stored as the integer 10 or its binary representation "00001010". However, that's not the case. Let's explore why.</p>
<p>Character Encoding Systems</p>
<p>Computers use character encoding systems to represent text in binary or hexadecimal format. Some popular encoding systems include ASCII, UTF-8, and UTF-16. For this example, we'll focus on ASCII (American Standard Code for Information Interchange).</p>
<p>ASCII Representation</p>
<p>When you type "10" on your keyboard, it's actually stored as two separate characters: "1" and "0". In <a target="_blank" href="https://en.wikipedia.org/wiki/ASCII">ASCII</a>:</p>
<ul>
<li><p>"1" is represented as "0110001" (decimal 49)</p>
</li>
<li><p>"0" is represented as "0110000" (decimal 48)</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721852737373/17f15dec-b6f1-4dcd-81f4-3ebcf90c23bb.png" alt class="image--center mx-auto" /></p>
<p>This means we can't perform arithmetic operations directly on these values. If we were to add "1" and "0" in their ASCII representations, we'd be adding 49 and 48, which is clearly not what we want.</p>
<p>Let's verify this with a simple Python program:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sys <span class="hljs-keyword">import</span> stdin

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    text = stdin.buffer.readline()
    print(<span class="hljs-string">"you entered: "</span>, text)
    print(<span class="hljs-string">"ASCII codes:"</span>, [b <span class="hljs-keyword">for</span> b <span class="hljs-keyword">in</span> text])
</code></pre>
<pre><code class="lang-bash">&gt; py test.py
10
you entered:  b<span class="hljs-string">'10\r\n'</span>
ASCII codes: [49, 48, 13, 10]
</code></pre>
<p>So how can we get around this problem, if you take a close look at the above table, you'll see all numbers are in sequence not only in ascii but in all major character encoding system and that's not the coincidence.</p>
<p>We can get the actual number by subtracting the first representation of character, which is <code>0</code> in our case.</p>
<p>Example:<br /><code>0 -&gt; 48 = 48 - 48 = 0</code></p>
<p><code>1 -&gt; 49 = 49 - 48 = 1</code></p>
<p>But what about multi-digit numbers, let's take 455 as an example. We know that it's a combination of units, tens and hundreds. So, in case of 455 its <code>5x(10^0) + 5x(10^1) + 5x(10^2)</code>.</p>
<p>So, the whole process would be like convert each character to their original number by subtracting its first representation and multiplying it by respective unit and adding it the result to the result of next character.</p>
<p>Example:</p>
<pre><code class="lang-bash">455:
4 -&gt; 52 - 48 = 4 x 10^2
5 -&gt; 53 - 48 = 4 x 10^1
5 -&gt; 53 - 48 = 4 x 10^0
</code></pre>
<p>But obviously the whole thing would be in binary in the computer, so the accurate operation would be:  </p>
<pre><code class="lang-bash">(0110100 - 0110000)*10^2 + (0110101 - 0110000)*10^1 + (0110101 - 0110000)*10^0
</code></pre>
<p>Let's look at the python equivalent of it:  </p>
<pre><code class="lang-python">result = <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> chr_code <span class="hljs-keyword">in</span> text:
    result = (chr_code - ord(<span class="hljs-string">"0"</span>)) + result*<span class="hljs-number">10</span>
</code></pre>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sys <span class="hljs-keyword">import</span> stdin

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    text = stdin.buffer.readline().strip()
    print(<span class="hljs-string">"you entered: "</span>, text)
    print(<span class="hljs-string">"ASCII codes:"</span>, [b <span class="hljs-keyword">for</span> b <span class="hljs-keyword">in</span> text])

    result = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> chr_code <span class="hljs-keyword">in</span> text:
        result = (chr_code - ord(<span class="hljs-string">"0"</span>)) + result*<span class="hljs-number">10</span>

    print(<span class="hljs-string">"Actual number is: "</span>, result)
</code></pre>
<p>This code iterates through each character, converts it to its numeric value, and builds up the final number by multiplying the previous result by 10 and adding the new digit.</p>
<pre><code class="lang-bash">&gt;py test.py
10
you entered:  b<span class="hljs-string">'10'</span>
ASCII codes: [49, 48]
Actual number is:  11
&gt; py test.py
455
you entered:  b<span class="hljs-string">'455'</span>
ASCII codes: [52, 53, 53]
Actual number is:  455
</code></pre>
<p>That's all, we understood the native implementation of str to int in most of the programming languages.</p>
]]></content:encoded></item><item><title><![CDATA[Docker Security Profile]]></title><description><![CDATA[Recently I was diagnosing a frequent crash of my xtrabackup container which is in a docker network along with the MySQL container. After digging through…]]></description><link>https://cosmicoppai.com/docker-security-profile</link><guid isPermaLink="true">https://cosmicoppai.com/docker-security-profile</guid><category><![CDATA[Devops]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Kernel]]></category><category><![CDATA[MySQL]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Tue, 02 Jul 2024 22:06:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1719957888207/27efd543-13ba-469f-a055-9d95fd0f9a25.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently I was diagnosing a frequent crash of my <a target="_blank" href="https://docs.percona.com/percona-xtrabackup/2.4/index.html"><mark>xtrabackup</mark></a> container which is in a docker network along with the MySQL container.</p>
<p>After digging through logs for a very good minute, I came across this error:  </p>
<pre><code class="lang-plaintext">mbind: Operation not permitted
mbind: Operation not permitted
2024-06-28T15:07:48.187675Z 10 [ERROR] [MY-012592] [InnoDB] Operating system error number 5 in a file operation.
2024-06-28T15:07:48.187724Z 10 [ERROR] [MY-012596] [InnoDB] Error number 5 means 'Input/output error'
2024-06-28T15:07:48.187735Z 10 [ERROR] [MY-012646] [InnoDB] File ./#innodb_temp/temp_10.ibt: 'truncate' returned OS error 105.
</code></pre>
<p>In the Docker ecosystem, seccomp is used as a security feature to restrict the system calls that the container can make to the host kernel. The default seccomp profiles prohibit 44 system calls out of 300+. The full list can be found <a target="_blank" href="https://docs.docker.com/engine/security/seccomp/"><mark>here</mark></a>.</p>
<p>The error we are encountering is because the <code>mbind</code> operation is not allowed by Docker's default seccomp configuration. The <code>mbind</code> operation is mostly used for memory access and management across nodes in <a target="_blank" href="https://en.wikipedia.org/wiki/Non-uniform_memory_access"><mark>NUMA</mark></a> architecture, which is important in the case of DBMS as it allows them to improve performance by storing data closer to the processor that needs it most.</p>
<p>So how we can override the default prevention, there are multiple ways of doing it none of them are wrong as everything is relative to the use case.</p>
<ol>
<li><p>Custom Seccomp Profile:</p>
<p> We can create a custom Seccomp profile which is a JSON file, in which all allowed and prohibited actions are specified.</p>
<p> <code>The profile works by defining a defaultAction of SCMP_ACT_ERRNO and overriding that action only for specific system calls. The effect of SCMP_ACT_ERRNO is to cause a Permission Denied error. Next, the profile defines a specific list of system calls which are fully allowed, because their action is overridden to be SCMP_ACT_ALLOW. Finally, some specific rules are for individual system calls such as personality, and others, to allow variants of those system calls with specific arguments.</code></p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"defaultAction"</span>: <span class="hljs-string">"SCMP_ACT_ERRNO"</span>,
   <span class="hljs-attr">"archMap"</span>: [
     {
       <span class="hljs-attr">"architecture"</span>: <span class="hljs-string">"SCMP_ARCH_X86_64"</span>,
       <span class="hljs-attr">"subArchitectures"</span>: [
         <span class="hljs-string">"SCMP_ARCH_X86"</span>,
         <span class="hljs-string">"SCMP_ARCH_X32"</span>
       ]
     }
   ],
   <span class="hljs-attr">"syscalls"</span>: [
     {
       <span class="hljs-attr">"names"</span>: [
         <span class="hljs-string">"mbind"</span>
       ],
       <span class="hljs-attr">"action"</span>: <span class="hljs-string">"SCMP_ACT_ALLOW"</span>
     }
   ]
 }
</code></pre>
<p> We can use this profile while running our container or can specify in the compose file:</p>
<pre><code class="lang-bash"> docker run --security-opt seccomp=custom-seccomp.json ...

 OR

 services:
   mysql:
     ...
     security_opt:
       - seccomp:custom-seccomp.json
</code></pre>
</li>
<li><p>Disable Seccomp:<br /> We can disable seccomp entirely for the container, but this is not recommended for production use as it reduces security:</p>
<pre><code class="lang-bash"> docker run --security-opt seccomp=unconfined ...

 OR

 services:
   mysql:
     ...
     security_opt:
       - seccomp:unconfined
</code></pre>
</li>
<li><p>Use <code>--cap-add SYS_NICE</code>:</p>
<p> This capability allows the container to use <code>mbind</code></p>
<pre><code class="lang-bash"> docker run --cap-add SYS_NICE ...

 OR

 services:
   mysql:
     ...
     cap_add:
       - SYS_NICE
</code></pre>
</li>
<li><p>Run in Privileged Mode:</p>
<p> This gives the container full access to the host's devices, but should be used with extreme caution:</p>
<pre><code class="lang-bash"> docker run --privileged ...

 OR

 services:
   mysql:
     ...
     privileged: <span class="hljs-literal">true</span>
</code></pre>
<p> <strong>Conclusion</strong>: I chose the <code>--cap-add SYS_NICE</code> option. If the least privilege option fixes the issue, it's better to use it before trying more permissive options.  </p>
</li>
</ol>
<p>    Other Consideration:</p>
<p>    This feature is available only if Docker has been built with <code>seccomp</code> and the kernel is configured with <code>CONFIG_SECCOMP</code> enabled. To check if your kernel supports <code>seccomp</code>:</p>
<pre><code class="lang-bash">    $ grep CONFIG_SECCOMP= /boot/config-$(uname -r)
    CONFIG_SECCOMP=y
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Consistent Hashing]]></title><description><![CDATA[In distributed systems, efficiently distributing data or load across multiple servers is critical. Two common methods for achieving this are Simple Hashing…]]></description><link>https://cosmicoppai.com/consistent-hashing</link><guid isPermaLink="true">https://cosmicoppai.com/consistent-hashing</guid><category><![CDATA[distributed system]]></category><category><![CDATA[consistent hashing]]></category><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Fri, 31 May 2024 01:30:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717118938256/7166a943-932e-4fbe-84ba-f6fa9aae3732.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In distributed systems, efficiently distributing data or load across multiple servers is critical. Two common methods for achieving this are Simple Hashing and Consistent Hashing. Let's look into how each method works and compare their advantages and disadvantages.</p>
<h4 id="heading-1-simple-hashing">1. Simple Hashing</h4>
<p>Simple Hashing uses a hash function <code>h(k)</code> to map a data item with key <code>'k'</code> to an integer value. This value is then used to determine the server index by performing a modulo operation with the number of servers, <code>N</code>:</p>
<pre><code class="lang-plaintext">server_index = h(k) % N
</code></pre>
<p>The data is stored on the server with the corresponding index.</p>
<p><strong>Example:</strong></p>
<p>Consider 4 servers indexed 0, 1, 2, and 3. For a data item with key <code>"user1234"</code>, the hash function might produce a value of 15. The server index is calculated as:</p>
<pre><code class="lang-plaintext">15 % 4 = 3
</code></pre>
<p>Thus, <code>"user1234"</code> would be stored on server 3.</p>
<p><strong>Drawback:</strong></p>
<p>When a new server is added (increasing <code>N</code>), all data needs to be remapped using the new value of <code>N</code>:</p>
<pre><code class="lang-plaintext">server_index = h(k) % (N + 1)
</code></pre>
<p>This results in a significant reshuffling of data and invalidation of caches, leading to inefficiency and potential downtime.</p>
<h4 id="heading-2-consistent-hashing">2. Consistent Hashing</h4>
<p>Consistent Hashing addresses the drawbacks of Simple Hashing by minimizing data reallocation when servers are added or removed. Instead of a linear array, Consistent Hashing uses a circular array (or hash ring).</p>
<p><strong>How it works:</strong></p>
<ol>
<li><p><strong>Hash the Servers:</strong> Each server (identified by server name or IP) is hashed and placed on the circular array.</p>
</li>
<li><p><strong>Hash the Data:</strong> Each data key is also hashed and placed on the ring.</p>
</li>
<li><p><strong>Locate the Server:</strong> To find the server for a particular data key, move clockwise from the data key's position until a server is encountered.</p>
</li>
</ol>
<p><strong>Example:</strong></p>
<p>With servers placed on a circular array, the key is mapped directly on the ring. For instance, if the servers are <code>s0</code>, <code>s1</code>, <code>s2</code>, and <code>s3</code>, and a new server <code>s4</code> is added:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717118480942/0ce969c7-0192-491f-a9f6-89b0cfca4927.png" alt="Consistent Hashing Diagram" /></p>
<p>When <code>s4</code> is inserted to the left of <code>s0</code>, only the data key <code>k0</code> needs to be moved from <code>s0</code> to <code>s4</code>. Other keys remain unaffected, significantly reducing the need for data redistribution.</p>
<h4 id="heading-conclusion">Conclusion</h4>
<ul>
<li><p><strong>Simple Hashing:</strong> Easy to implement but causes massive reshuffling of data when servers are added or removed, leading to inefficiency.</p>
</li>
<li><p><strong>Consistent Hashing:</strong> Efficient in handling changes in the number of servers, requiring only a fraction of the data to be redistributed. This reduces cache invalidation and improves overall system performance.</p>
</li>
</ul>
<p><strong>Visual Comparison:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1717118345264/8655f78e-32b6-46f3-ae84-b4794de5ffd4.png" alt="Simple Hashing vs. Consistent Hashing" /></p>
<p>By adopting Consistent Hashing, systems can achieve better scalability and robustness, ensuring minimal disruption during server changes. This makes it a preferred choice for distributed data storage and load balancing in modern distributed systems.</p>
<p>image credit: BytesBytesGo</p>
]]></content:encoded></item><item><title><![CDATA[How To: Add Custom Metric Panel in PMM]]></title><description><![CDATA[How to add and create custom metrics panel in perceona]]></description><link>https://cosmicoppai.com/how-to-add-custom-metric-panel-in-pmm</link><guid isPermaLink="true">https://cosmicoppai.com/how-to-add-custom-metric-panel-in-pmm</guid><category><![CDATA[perceona-monitroing]]></category><category><![CDATA[Devops]]></category><category><![CDATA[#prometheus]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Sat, 25 Nov 2023 14:01:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700920790413/0096caf5-8745-47ab-a4f9-9044ab74c85f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Custom Metrics are defined in a file deployed on each server that we are monitoring.</p>
<p>To add the custom metrics navigate to the following DIR:</p>
<ul>
<li><p>For MySQL:  <strong>/usr/local/percona/pmm2/collectors/custom-queries/mysql</strong></p>
</li>
<li><p>For PostgreSQL:  /<strong>usr/local/percona/pmm2/collectors/custom-queries/postgresql</strong></p>
</li>
</ul>
<p>You will notice the following directories under each directory:</p>
<ul>
<li><p>high-resolution/  – every 5 seconds</p>
</li>
<li><p>medium-resolution/ – every 10 seconds</p>
</li>
<li><p>low-resolution/ – every 60 seconds</p>
</li>
</ul>
<p>Create a yml file with appropriate name under the resolution you want.</p>
<p>This custom query will get executed and pushed to the PMM database.</p>
<p>if you deploy lots of custom queries you will see a steady number of connections (this is something you will want to consider if you are doing custom collections).  Alternatively, you can add queries and metrics to the same file, but they are executed sequentially.  If, however, the entire YML file can not be completed in less time than the defined resolution ( i.e. finished within five seconds for high resolution), then the data will not be stored, but the query will continue to run.  This can lead to a query pile-up if you are not careful.</p>
<h2 id="heading-example"><strong>Example:</strong></h2>
<p>I've a file defining custom query which will push scarping count of last hour and it's located under <strong>/usr/local/percona/pmm2/collectors/custom-queries/mysql/low-resolution</strong></p>
<pre><code class="lang-plaintext">scraping_count_last_hr:
    query: "SELECT COUNT(1) as scraping_count, CASE WHEN id % 2 = 0 THEN 'bot-1' ELSE 'bot-2' END as bot_num, scrape_status FROM scraping_db.stock_listings WHERE scrape_status IN ('SCRAPED', 'ERROR') AND updated_at &gt; NOW() - INTERVAL 1 HOUR GROUP BY bot_num, scrape_status;"
    metrics:
      - scraping_count:
          usage: "GAUGE"
          description: "Count of scraping status updated in the last one hour."
      - scrape_status:
          usage: "LABEL"
          description: "The status of the scrape"
      - bot_num:
          usage: "LABEL"
          description: "The label to distinguish between bots."
</code></pre>
<blockquote>
<p>The above file will push the query result after every 60 sec and we can use it in the panel by querying <code>scraping_db.stock_listings</code> i.e <code>nameSpace_metricName</code></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Understanding Sockets and UDP with a SHOUT Server Example]]></title><description><![CDATA[Networking is a fundamental concept in computer science, enabling communication between devices over a variety of protocols and mediums. One of the key…]]></description><link>https://cosmicoppai.com/understanding-sockets-and-udp-with-a-shout-server-example</link><guid isPermaLink="true">https://cosmicoppai.com/understanding-sockets-and-udp-with-a-shout-server-example</guid><category><![CDATA[Python]]></category><category><![CDATA[socket]]></category><category><![CDATA[networking]]></category><dc:creator><![CDATA[Cosmicoppai]]></dc:creator><pubDate>Tue, 12 Sep 2023 16:55:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1694538088960/499f8ec4-c1ce-480e-9448-a1dec9fda11c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Networking is a fundamental concept in computer science, enabling communication between devices over a variety of protocols and mediums. One of the key elements in networking is the use of sockets, which act as the endpoints for data communication. In this blog, we will explore the basics of sockets and delve into the world of UDP (User Datagram Protocol) with the help of a simple example – the SHOUT server.</p>
<p><strong><em>Sockets*</em></strong>: The Building Blocks of Network Communication*</p>
<p>Sockets are Interface/programming abstraction that allow two processes (usually on different devices) to communicate with each other, much like the File interface for accessing the storage. They provide a way to send and receive data over a network or the Internet. Sockets come in two main flavours: TCP and UDP.</p>
<ul>
<li><p><strong><em>TCP</em></strong> <em>(Transmission Control Protocol):</em> TCP sockets provide a reliable, connection-oriented communication mechanism. Data sent over TCP is guaranteed to be delivered in the correct order and without loss. It's widely used for applications like web browsing and email.</p>
</li>
<li><p><strong><em>UDP</em></strong> <em>(User Datagram Protocol):</em> UDP sockets provide a simpler, connectionless communication mechanism. Unlike TCP, UDP does not guarantee the order or reliability of data transmission. This makes UDP more suitable for real-time applications, such as video conferencing, online gaming, and networked sensors.</p>
</li>
</ul>
<p><strong><em>SHOUT Server*</em></strong>:*</p>
<p>Now, let's take a look at a simple example of a UDP server known as the SHOUT server. The SHOUT server receives a message from a client, converts it to uppercase, and sends it back to the client. Here's the server code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> socket

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind((<span class="hljs-string">"0.0.0.0"</span>, <span class="hljs-number">9999</span>))

<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
    msg, address = server.recvfrom(<span class="hljs-number">4096</span>)
    server.sendto(msg.upper(), address)
</code></pre>
<p>This Python script creates a UDP socket, binds it to all available network interfaces (0.0.0.0) on port 9999, and enters an infinite loop to listen for incoming messages. When a message is received, it converts the message to uppercase using the <code>upper()</code> method and sends it back to the client using the <code>sendto()</code> method.</p>
<p><em>Testing the SHOUT Server</em></p>
<p>To test our SHOUT server, we can use a command-line utility like <code>nc</code> (netcat). The following command sends a message to the SHOUT server:</p>
<pre><code class="lang-bash">nc -u 127.0.0.1 9999
</code></pre>
<p>In this command, <code>-u</code> specifies UDP mode, <code>127.0.0.1</code> is the server's IP address, and <code>9999</code> is the port number. You can replace <code>127.0.0.1</code> with the IP address of your server if it's running on a different machine.</p>
<p>When you run this command, you can type a message and press Enter. The server will receive the message, convert it to uppercase, and send it back to you. It's a simple demonstration of how UDP sockets can be used for communication.</p>
<h3 id="heading-conclusion"><em>Conclusion</em></h3>
<p>Sockets are a powerful tool for network communication, allowing devices to exchange data seamlessly. UDP provides a lightweight and efficient way to send and receive data when reliability and strict ordering are not critical. While it might be not the best abstraction but undeniably the most widely used.</p>
]]></content:encoded></item></channel></rss>