<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.5">Jekyll</generator><link href="https://akhileshmoghe.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://akhileshmoghe.github.io/" rel="alternate" type="text/html" /><updated>2024-05-11T17:04:11+05:30</updated><id>https://akhileshmoghe.github.io/feed.xml</id><title type="html">Every THING is Internet of Thing</title><subtitle>A Journey in the direction of ---&gt; IoT ---&gt; Edge ---&gt; Cloud ---&gt; DevOps ---&gt; ML ---&gt; AI
</subtitle><author><name>Akhilesh Moghe</name><email>akhileshmoghe@live.com</email></author><entry><title type="html">A Demystifying Introduction to Initrd and Initramfs</title><link href="https://akhileshmoghe.github.io/_post/embedded/linux/initramfs-initrd" rel="alternate" type="text/html" title="A Demystifying Introduction to Initrd and Initramfs" /><published>2023-08-02T01:33:22+05:30</published><updated>2023-08-02T01:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_post/embedded/linux/Initramfs-Initrd</id><content type="html" xml:base="https://akhileshmoghe.github.io/_post/embedded/linux/initramfs-initrd"><![CDATA[<p>In Linux systems, <strong><em><u>initrd</u></em></strong> (<u>initial ramdisk</u>) or <strong><em><u>Initramfs</u></em></strong> are used for loading a temporary root file system into memory, to be further used as part of the Linux startup process.
Both are commonly used to make preparations before the real root file system can be mounted. The initramfs is a complete set of directories that you would find on a normal root filesystem. It is bundled into a single <code class="language-plaintext highlighter-rouge">cpio</code> archive and compressed with one of several compression algorithms.</p>

<h2 id="why-initrd-or-initramfs-came-in-existance">Why Initrd or Initramfs came in existance</h2>
<ul>
  <li>Many Linux distributions create a single, generic <u>Linux kernel image</u> to boot on a wide variety of hardware.</li>
  <li>The <strong><em>device drivers</em></strong> for this generic kernel image are included as <em><u>loadable kernel modules</u></em> because statically compiling many drivers into one kernel causes the kernel image to be much larger, to boot on computers with limited memory, sometimes even results in boot crashes.</li>
  <li>Many a times, the root file system may be on a <strong>LVM</strong>, <strong>NFS</strong> (on diskless workstations), or on an <strong>encrypted partition</strong>. All of these require special preparations to mount.</li>
  <li>To avoid having to hardcode handling for so many unique scenarios into the kernel, a temporary root file-system is utilized during the initial boot stage, known as <strong><em><u>early user space</u></em></strong>. In order to mount the actual root file-system, user-space tools that perform hardware detection, module loading, and device discovery can be found in this root file-system.</li>
  <li>So in a broader sense, the <strong><em>Initramfs</em></strong> or <strong><em>Initrd</em></strong> has essentially one purpose: <u>locating and mounting the real root file system</u> so that the boot process can transition to it.</li>
  <li>To elaborate in detail with example of <strong><em>Encrypted Partitions</em></strong> mounting, some system configurations like using a <code class="language-plaintext highlighter-rouge">cryptodevices</code> requires a <u>user space utility to provoke the kernel to configure the devices appropriately</u>, as <u>they need to have a password from the user</u>. This password requesting utility being a user space utility, could pose <u>a chicken and egg problem</u> i.e your rootfs contains the user space utilities, but the rootfs cannot come up till the user space utilities are available. In such cases, the <strong><em>Initramfs</em></strong> plays a mediator in between giving <u>a temporary rootfs</u> which has the user space utilities needed for mounting the real rootfs.</li>
</ul>

<hr />

<h2 id="linux-boot-process-with-initrd-or-initramfs">Linux boot process with Initrd or Initramfs</h2>
<ul>
  <li>The <strong>Image</strong> of this Initial ROOT File System (along with the kernel image) is required be stored somewhere accessible by the <strong><em>Linux bootloader</em></strong> or the boot firmware of the computer.</li>
  <li>This <strong>Image</strong> storage location can be the <em><u>root file system</u></em> itself, a <em><u>boot image on an optical disc</u></em>, on a <em><u>small partition on a local disk</u></em> (usually using <strong>ext4</strong> or <strong>FAT</strong> file systems), or a <em><u>TFTP server</u></em> (for systems that can boot from Ethernet).</li>
  <li>The <strong><em>Bootloader</em></strong> will <u>start the kernel</u> by sending in the memory address of the image after loading the kernel and initial root file system image into memory.
    <ul>
      <li><strong>U-Boot</strong> Example: <code class="language-plaintext highlighter-rouge">bootz ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr}</code></li>
    </ul>
  </li>
  <li>The kernel attempts to determine the image’s format from its initial few data blocks at the end of the boot process, which can either be the Initrd or Initramfs.<br />
 </li>
  <li><u>In case of</u> <strong><em><u>Initrd</u></em></strong>:
    <ul>
      <li>The initrd image may be a file system image (optionally compressed), which is made available in a special <strong><em>block device (/dev/ram)</em></strong> which is then mounted as the initial root file system.</li>
      <li>:pencil: The <em>device driver for this file system must be compiled statically into the kernel</em>.</li>
      <li>Many distributions use <u>compressed </u><strong><u>ext2</u></strong><u> file system images</u>, while the <strong>Debian</strong> uses <a href="/_post/linux/file_systems_types#cramfs">cramfs</a> (Compressed ROM/RAM file system) in order to boot on memory constrained systems, since the <strong><u>cramfs</u></strong><u> image can be mounted in-place without requiring extra space for decompression</u>.</li>
      <li>Once the initial root file system is up, the <u>kernel executes</u> <a href="https://www.novell.com/documentation/suse91/suselinux-adminguide/html/ch12s04.html"><code class="language-plaintext highlighter-rouge">/linuxrc</code></a> <u>as its first process</u>.
        <ul>
          <li><code class="language-plaintext highlighter-rouge">/linuxrc</code> must be located in the root directory of the Initrd and needs to be executable which is run with root permissions by the kernel.</li>
          <li>In case <code class="language-plaintext highlighter-rouge">/linuxrc</code> is <strong>dynamically linked</strong>, all required shared libraries from <code class="language-plaintext highlighter-rouge">/lib</code> must be available in Initrd also.</li>
          <li><code class="language-plaintext highlighter-rouge">/linuxrc</code> can also be a <strong>shell script</strong>, in that case a shell must exist in <code class="language-plaintext highlighter-rouge">/bin</code>.</li>
          <li>In <a href="https://www.suse.com/products/">SUSE Linux</a>, a <strong>statically-linked</strong> <code class="language-plaintext highlighter-rouge">/linuxrc</code> is used to keep initrd as small as possible.</li>
        </ul>
      </li>
      <li>When <code class="language-plaintext highlighter-rouge">/linuxrc</code> process exits, the <u>kernel assumes that the real root file system has been mounted and executes</u> <code class="language-plaintext highlighter-rouge">/sbin/init</code> to begin the normal user-space boot process.</li>
      <li>On an <strong><em>Initrd</em></strong>, the new final <code class="language-plaintext highlighter-rouge">root</code> is mounted at a temporary mount point and rotated into place with <a href="https://man7.org/linux/man-pages/man8/pivot_root.8.html"><code class="language-plaintext highlighter-rouge">pivot_root(8)</code></a> (to change the root filesystem). This leaves the <em><u>Initial root file system at a mount point</u></em> (such as <code class="language-plaintext highlighter-rouge">/initrd</code>) where normal <em><u>boot scripts can later unmount it</u></em> to free up memory held by the <strong><em>Initrd</em></strong>.<br />
 </li>
    </ul>
  </li>
  <li><u>For</u> <strong><em><u>Initramfs</u></em></strong>:
    <ul>
      <li><strong><em>Initramfs</em></strong> is available since the <em><u>Linux kernel 2.6.13</u></em>.</li>
      <li>The <strong><em>Initramfs</em></strong> image may be a <a href="TBD">cpio archive</a> (optionally compressed).</li>
      <li>The archive is unpacked by the kernel into a special instance of a <a href="/_post/linux/file_systems_types#tmpfs">tmpfs</a> that becomes the initial root file system.</li>
      <li>:pencil: The <strong><em>Initramfs</em></strong> has the advantage over the <strong><em>Initrd</em></strong> of <u>not requiring an</u> <strong><u>intermediate file system</u></strong> or <strong><u>block device drivers</u></strong> <u>to be compiled into the kernel</u>.</li>
      <li><u>Red Hat Linux</u> distribution uses the <a href="https://en.wikipedia.org/wiki/Dracut_(initramfs)">dracut</a> package to create an initramfs image.</li>
      <li>With <strong><em>Initramfs</em></strong>, the kernel executes <code class="language-plaintext highlighter-rouge">/init</code> as its <em><u>first process that is not expected to exit</u></em>. The <code class="language-plaintext highlighter-rouge">/init</code> program is typically a <u>shell script</u>.</li>
      <li>For some applications like <em><u>Ubuntu live cds</u></em>, <strong><em>Initramfs</em></strong> can use the <a href="https://manpages.ubuntu.com/manpages/focal/man7/casper.7.html">casper</a> utility to create a writable environment using <a href="/_post/linux/file_systems_types#unionfs">unionfs</a> <em><u>to overlay</u></em><strong><em><u> a persistence layer</u></em></strong><em><u> over a</u></em><strong><em><u> read-only</u></em></strong><em><u> root filesystem</u></em> image. For example, <u>overlay data can be stored on a USB flash drive</u>, while a compressed <a href="/_post/linux/file_systems_types#squashfs">SquashFS</a> read-only image stored on a live CD acts as a root filesystem.</li>
      <li>:pencil: On an <strong><em>Initramfs</em></strong>, the <em><u>initial root file system cannot be rotated away</u></em> like that on <strong>Initrd</strong> using <code class="language-plaintext highlighter-rouge">pivot_root(8)</code>. Instead, Initramfs is simply emptied and the <em><u>final root file system mounted over the top</u></em>.<br />
 </li>
    </ul>
  </li>
  <li>kernel can unpack Initrd or Initramfs images compressed with gzip, bzip2, LZMA, XZ, LZO, LZ4 and zstd.</li>
  <li><strong><em>Initrd</em></strong> and <strong><em>Initramfs</em></strong> implement <code class="language-plaintext highlighter-rouge">/linuxrc</code> or <code class="language-plaintext highlighter-rouge">/init</code> <u>as a shell script</u>.</li>
  <li>Both include a <u>minimal shell</u> (usually <code class="language-plaintext highlighter-rouge">/bin/ash</code>) along with some <u>essential user-space utilities</u> (usually <a href="https://en.wikipedia.org/wiki/BusyBox">BusyBox</a> toolkit).</li>
  <li>To further save space, the <u>shell, utilities and their supporting libraries are typically compiled with</u> <em><u>space optimizations enabled</u></em> (such as <code class="language-plaintext highlighter-rouge">gcc -O</code> flag) and <u>linked against</u> <a href="https://en.wikipedia.org/wiki/Klibc">klibc</a>, <u>a minimal version of the</u> <strong><em><u>libc</u></em></strong> library written specifically for this purpose.</li>
</ul>

<hr />

<h2 id="few-more-details-about">Few more details about:</h2>

<h3 id="initial-ram-disk-initrd"><u>Initial RAM Disk (Initrd)</u>:</h3>
<ul>
  <li><strong><em>Initrd</em></strong> provides the capability to load a <strong>RAM disk</strong> Image and <u>mount it as the Root File System</u> by the Bootloader. Then user-space programs can be run from it.</li>
  <li>Afterwards, a new larger Root File System can be mounted from a different device. The <em>previous root (from initrd) is then moved to a directory and can be subsequently unmounted</em>.</li>
  <li><strong><em>Initrd</em></strong> is mainly designed to allow system startup to occur in two phases, where the kernel comes up with a minimum set of compiled-in drivers, and where additional modules are loaded from initrd.<br />
 </li>
  <li><strong>IMPORTANT</strong>: <strong><em><u>Initrd mechanism has been deprecated and the support for it is removed from Linux Kernel from 2021.</u></em></strong>
    <ul>
      <li><strong><em>Initramfs</em></strong> had been introduced since <strong><em>Linux Kernel 2.6</em></strong>.</li>
      <li>It is the recommended way for implementing initial root file system all modern Linux distributions.</li>
      <li>Even if you see files named as <code class="language-plaintext highlighter-rouge">initrd-$(uname -r)</code> in <code class="language-plaintext highlighter-rouge">/boot</code> folders on modern Linux distributions like Ubuntu/Debian, keep in mind that this is not an initrd but actually an <strong><em>Initramfs</em></strong> only. That means, it can be a concatenation of multiple <a href="">cpio</a> archives, each of which may or may not be compressed.</li>
      <li>References:
        <ul>
          <li><a href="https://www.mail-archive.com/linux-kernel@vger.kernel.org/msg2233909.html">[PATCH 14/23] initrd: mark initrd support as deprecated</a></li>
          <li><a href="https://lkml.org/lkml/2021/3/4/173">Re: using deprecated initrd support, will be removed in 2021</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<hr />

<h3 id="init-ram-file-system-initramfs"><u>Init RAM File System (Initramfs)</u>:</h3>
<ul>
  <li><strong>Linux Kernel version 2.6</strong> onwards, contain a <a href="/_post/embedded/linux/initramfs-cpio#gzip-command">gzipped</a> <a href="/_post/embedded/linux/initramfs-cpio#cpio-command">cpio</a> format archive, which is extracted into ROOTFS when the kernel boots up.</li>
  <li>An <strong><em>Initramfs</em></strong> archive is a <u>complete self-contained ROOTFS for Linux</u>.</li>
  <li>The <strong>Linux Kernel version 2.6</strong> build process <em><u>always creates a gzipped cpio format initramfs
archive and links it into the resulting kernel binary</u></em>. By default, <u>this archive is empty (consuming 134 bytes on x86)</u>.</li>
  <li>After extracting, the kernel checks to see if ROOTFS contains a file <code class="language-plaintext highlighter-rouge">/init</code>, and if so it executes it as <code class="language-plaintext highlighter-rouge">PID=1</code>. This <code class="language-plaintext highlighter-rouge">init</code> process is responsible for bringing rest of the system up, including locating and <u>mounting the real root device</u> (if any).</li>
  <li>If ROOTFS <em><u>does not contain</u></em> an <code class="language-plaintext highlighter-rouge">init</code> program after the embedded <code class="language-plaintext highlighter-rouge">cpio</code> archive is extracted into it, the <u>kernel will try to locate and mount a ROOT partition</u>, then <code class="language-plaintext highlighter-rouge">exec</code> some variant of <code class="language-plaintext highlighter-rouge">/sbin/init</code> out of that.</li>
  <li><strong>Using <em>External initramfs images</em></strong>:
    <ul>
      <li>If the kernel has <strong><em><u>initrd </u></em></strong> <u>support enabled</u>, an external <strong><em>cpio.gz archive</em></strong> can also be passed into a v2.6 kernel in place of an Initrd. The <u>kernel will autodetect the type as</u> <strong><em>Initramfs</em></strong>, and <u>extract the external </u><strong><em><u>cpio archive</u></em></strong><u> as a ROOTFS before trying to run</u> <code class="language-plaintext highlighter-rouge">/init</code>.</li>
      <li>This approach of separately packaging of <strong><em>Initramfs</em></strong> has an <em><u>Advantage</u></em> that, you can run a <u>non-GPL code from within</u> <strong><em><u>Initramfs</u></em></strong>,<u> without conflating it with the GPL licensed Linux kernel binary</u>.</li>
      <li>External <strong><em>Initramfs</em></strong> can supplement the kernel’s built-in initramfs image. The external archive will overwrite any conflicting files in the built-in initramfs archive.</li>
    </ul>
  </li>
  <li><strong><em>Initramfs</em></strong> usually contains either <a href="https://en.wikipedia.org/wiki/Klibc">klibc</a> or <a href="https://en.wikipedia.org/wiki/UClibc">uClibc</a> which are C libraries designed to statically link early userspace code against, along with some related utilities. Also contains <a href="https://en.wikipedia.org/wiki/BusyBox">BusyBox</a>.</li>
</ul>

<hr />

<h2 id="why-kernel-replaced-initrd-with-initramfs">Why Kernel replaced <u>Initrd</u> with <u>Initramfs</u></h2>
<ul>
  <li><strong>RAMdisk vs RAMfs</strong>
    <ul>
      <li>A <strong>RAMdisk</strong> (like <strong><em>Initrd</em></strong>) is a <em><u>RAM based </u></em><strong><em><u>Block device</u></em></strong>, which means it’s a <u>fixed size of memory</u> that can be <u>formatted and mounted like a disk</u>.</li>
      <li>The contents of the <strong>RAMdisk</strong> have to be formatted with <a href="/_post/linux/disk_img_creation_process#mkfs"><code class="language-plaintext highlighter-rouge">mke2fs</code></a> and mounted with <a href="/_post/linux/disk_img_creation_process#losetup"><code class="language-plaintext highlighter-rouge">losetup</code></a> tools, and like all block devices it requires a <u>filesystem driver</u> to interpret the data at runtime.</li>
      <li>Normally these tools are kept on a file system as user-space program, but as there’s no real file system mounted at this boot stage, <u>these tools and drivers are required to be compiled in the Kernel itself</u>.</li>
      <li><strong><em>Fixed size</em></strong> requirement of <strong>RAMdisk</strong> puts a limitation on the size, that will either wastes the excess memory or will not be adequate for the purpose. You <em><u>can't expand or shrink it without formatting again</u></em>.</li>
      <li><strong>RAMdisk</strong> also <em><u>wastes memory as it gets cached</u></em>, as Linux caches all the files read from or written to block devices. This is the downside of the <strong>RAMdisk</strong> being treated as a block device.</li>
      <li>Whereas, <strong><em>Initramfs</em></strong> is an instance of <a href="/_post/linux/file_systems_types#tmpfs">tmpfs</a>, which <em><u>automatically grow or shrink to fit the size of the data</u></em> they contain. Adding files to a <strong><em>Initramfs</em></strong> (or extending existing files) automatically allocates more memory, and deleting or truncating files frees that memory.</li>
      <li>With <strong><em>Initramfs</em></strong>, as there’s <em><u>no block device</u></em>, there’s <em><u>no duplication of data between block device and cache</u></em>.</li>
      <li><strong><em>Initramfs</em></strong> doesn’t need any file system driver built in the Kernel.<br />
 </li>
    </ul>
  </li>
  <li><u>Few other design limitations of </u><strong><em><u>Initrd</u></em></strong><u> overcame by </u><strong><em><u>Initramfs</u></em></strong>:
    <ul>
      <li>The <code class="language-plaintext highlighter-rouge">/linuxrc</code> <u>tries to determine the several available devices for real ROOTFS</u> before returning the identified device number to the Kernel so the kernel could mount the real root device and execute the real init program.</li>
      <li><strong><em>Initrd</em></strong> assums that real <em><u>ROOTFS will always be a Block device</u></em>, rather than a network share.</li>
      <li>Also <strong><em>Initrd</em></strong> was never considered to be the real ROOTFS for memory constrained embedded devices.</li>
      <li>In <strong><em>Initrd</em></strong>, <code class="language-plaintext highlighter-rouge">/linuxrc</code> <u>is not run like an</u> <code class="language-plaintext highlighter-rouge">init</code> <u>program with PID=1</u>, which actually provides special properties reserved for <code class="language-plaintext highlighter-rouge">init</code> like it cannot be killed with <code class="language-plaintext highlighter-rouge">kill -9</code> command.</li>
      <li>In <strong><em>Initramfs</em></strong>, the Kernel doesn’t care where the real ROOTFS is (it’s <strong><em>Initramfs</em></strong> until <code class="language-plaintext highlighter-rouge">init</code> program from real ROOTFS is executed).</li>
      <li>In <strong><em>Initramfs</em></strong>, the <code class="language-plaintext highlighter-rouge">init</code> program of <strong><em>Initramfs</em></strong> is always run as a real <code class="language-plaintext highlighter-rouge">init</code>, with PID=1.</li>
      <li>When <strong><em>Initramfs</em></strong> <code class="language-plaintext highlighter-rouge">init</code> needs to hand that special Process ID off to another program, it can use the <code class="language-plaintext highlighter-rouge">exec()</code> syscall just like everybody else.</li>
    </ul>
  </li>
</ul>

<hr />

<h2 id="use-cases-for-initramfs-or-initrd">Use cases for Initramfs or Initrd</h2>
<h3 id="1-minimizing-linux-kernel-size">1. <em><u>Minimizing Linux Kernel size</u></em></h3>
<ul>
  <li>The idea here is that there’s a lot of initialization tasks done in the <strong><em>Linux Kernel</em></strong> that could be just as easily done in userspace.</li>
  <li>Many modules required for mounting different typesf of ROOTFS like <strong>NFS</strong>, <strong>LVM</strong>, etc can be offloaded to <strong><em>Initramfs</em></strong> or <strong><em>Initrd</em></strong> instead of compiling all of them into the kernel, as not all of these modules will be required for every type of ROOTFS mounting.</li>
</ul>

<h3 id="2-mounting-real-rootfs">2. <em><u>Mounting Real ROOTFS</u></em></h3>
<ul>
  <li>Some Linux distributions like <strong><em>Debian</em></strong> generates a customized <strong><em>Initrd</em></strong> image which contains only necessary stuffs to boot some particular computer, such as <a href="https://en.wikipedia.org/wiki/Advanced_Technology_Attachment">ATA</a>, <a href="https://en.wikipedia.org/wiki/SCSI">SCSI</a> and <u>filesystem kernel modules</u>. Such images typically embed the location and type of the root file system.</li>
  <li>Other Linux distributions like <strong><em>Ubuntu</em></strong> generates a generic <strong><em>Initrd</em></strong> image. These images start only with the device name of the root file system (or its UUID) and discovers everything else at boot time. In this case, the software must perform a complex cascade of tasks to get the root file system mounted. Few examples of what else would be required to be done to boot the ROOTFS are:
    <ul>
      <li>Load all storage device drivers that are required by the boot process. For this, kernel modules of common storage devices can be added to <strong><em>Initrd</em></strong> image and then an event-driven hotplug agent like <a href="https://en.wikipedia.org/wiki/Udev">udev</a> can be used to load the modules matching the computer’s detected hardware.</li>
      <li>If <em><u>Boot Splash Screen</u></em> is required, the video hardware must be initialized along with user-space utilities to paint the splash screen animation during the boot process.</li>
      <li>If the <strong>NFS</strong> needs to be accessed, <strong><em>Initrd</em></strong> must bring up the primary network interface, invoke a <u>DHCP client</u>, to obtain a DHCP lease, extract the name of the NFS shared location and the address of the NFS server from the lease, and mount the NFS shared location.</li>
      <li>If root file system is on a <strong>logical volume</strong>, the <strong>LVM utilities</strong> must be invoked to scan for the activate the volume group containing it.</li>
      <li>If root file system is on an <strong>encrypted block device</strong>, the <strong><em>Initrd</em></strong> needs to invoke a utility script to prompt the user to type in a passphrase and/or insert a hardware token (such as a smart card or a USB security dongle), and then create a decryption target with the device mapper.</li>
    </ul>
  </li>
</ul>

<h3 id="3-maintenance-tasks-on-rootfs-before-mounting">3. <em><u>Maintenance Tasks on ROOTFS before mounting</u></em></h3>
<ul>
  <li>When the Root file system finally becomes visible, <em><u>any maintenance tasks that cannot be ran on a mounted Root file system are required to be done</u></em>, the Root file system is mounted <em><u>read-only</u></em>, and any processes that must continue running (such as the splash screen utility) are hoisted into the newly mounted root file system.</li>
</ul>

<h3 id="4-recovery-disks-creation">4. <em><u>Recovery disks creation</u></em></h3>
<ul>
  <li><strong><em>Initrd</em></strong> or <strong><em>Initramfs</em></strong> can be used to create a <em><u>Recovery Disk Image</u></em> or <em><u>Backup a Partition</u></em>.</li>
  <li>Because with <strong><em>Initrd</em></strong> or <strong><em>Initramfs</em></strong> mechanism, the real ROOTFS is not required to be loaded, so the backup of the ROOTFS can be created and saved to some external device like USB/CD-ROM.</li>
  <li>The system loaded from initrd can invoke a user-friendly dialog or it can also perform some form of auto-detection for available backup media.</li>
</ul>

<h3 id="5-linux-installers">5. <em><u>Linux Installers</u></em></h3>
<ul>
  <li>Linux distribution Installers typically <u>run entirely from an</u> <strong><em>Initramfs</em></strong>, as they must be able to host the installer interface and supporting tools before any persistent storage has been set up.</li>
  <li>CD-ROM distributors may use <strong><em>Initrd</em></strong> for better installation from CD, by bootstrapping a bigger RAM disk via initrd from CD; or by booting via a bootloader like <a href="https://en.wikipedia.org/wiki/Loadlin">loadlin</a> or directly from the CD-ROM.</li>
  <li><a href="https://en.wikipedia.org/wiki/Tiny_Core_Linux">Tiny Core Linux (TCL)</a> and <a href="https://en.wikipedia.org/wiki/Puppy_Linux">Puppy Linux</a> can run entirely from <strong><em>Initrd</em></strong>.</li>
</ul>

<hr />

<h2 id="references">References</h2>
<ul>
  <li><a href="https://tldp.org/LDP/Linux-Filesystem-Hierarchy/html/initrd.html">initrd</a></li>
  <li><a href="https://archive.ph/20130104033427/http://www.linuxfordevices.com/c/a/Linux-For-Devices-Articles/Introducing-initramfs-a-new-model-for-initial-RAM-disks/#selection-254.1-267.56">Introducing initramfs, a new model for initial RAM disks</a></li>
  <li><a href="https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt">Kernel.org: ramfs-rootfs-initramfs</a></li>
</ul>]]></content><author><name>Akhilesh Moghe</name></author><category term="Linux" /><category term="Embedded Linux" /><category term="Systems Engineering" /><category term="Linux" /><category term="Embedded Linux" /><category term="Systems Engineering" /><summary type="html"><![CDATA[In Linux systems, initrd (initial ramdisk) or Initramfs are used for loading a temporary root file system into memory, to be further used as part of the Linux startup process. Both are commonly used to make preparations before the real root file system can be mounted. The initramfs is a complete set of directories that you would find on a normal root filesystem. It is bundled into a single cpio archive and compressed with one of several compression algorithms. Why Initrd or Initramfs came in existance Many Linux distributions create a single, generic Linux kernel image to boot on a wide variety of hardware. The device drivers for this generic kernel image are included as loadable kernel modules because statically compiling many drivers into one kernel causes the kernel image to be much larger, to boot on computers with limited memory, sometimes even results in boot crashes. Many a times, the root file system may be on a LVM, NFS (on diskless workstations), or on an encrypted partition. All of these require special preparations to mount. To avoid having to hardcode handling for so many unique scenarios into the kernel, a temporary root file-system is utilized during the initial boot stage, known as early user space. In order to mount the actual root file-system, user-space tools that perform hardware detection, module loading, and device discovery can be found in this root file-system. So in a broader sense, the Initramfs or Initrd has essentially one purpose: locating and mounting the real root file system so that the boot process can transition to it. To elaborate in detail with example of Encrypted Partitions mounting, some system configurations like using a cryptodevices requires a user space utility to provoke the kernel to configure the devices appropriately, as they need to have a password from the user. This password requesting utility being a user space utility, could pose a chicken and egg problem i.e your rootfs contains the user space utilities, but the rootfs cannot come up till the user space utilities are available. In such cases, the Initramfs plays a mediator in between giving a temporary rootfs which has the user space utilities needed for mounting the real rootfs. Linux boot process with Initrd or Initramfs The Image of this Initial ROOT File System (along with the kernel image) is required be stored somewhere accessible by the Linux bootloader or the boot firmware of the computer. This Image storage location can be the root file system itself, a boot image on an optical disc, on a small partition on a local disk (usually using ext4 or FAT file systems), or a TFTP server (for systems that can boot from Ethernet). The Bootloader will start the kernel by sending in the memory address of the image after loading the kernel and initial root file system image into memory. U-Boot Example: bootz ${kernel_addr_r} ${ramdisk_addr_r} ${fdt_addr} The kernel attempts to determine the image’s format from its initial few data blocks at the end of the boot process, which can either be the Initrd or Initramfs.   In case of Initrd: The initrd image may be a file system image (optionally compressed), which is made available in a special block device (/dev/ram) which is then mounted as the initial root file system. :pencil: The device driver for this file system must be compiled statically into the kernel. Many distributions use compressed ext2 file system images, while the Debian uses cramfs (Compressed ROM/RAM file system) in order to boot on memory constrained systems, since the cramfs image can be mounted in-place without requiring extra space for decompression. Once the initial root file system is up, the kernel executes /linuxrc as its first process. /linuxrc must be located in the root directory of the Initrd and needs to be executable which is run with root permissions by the kernel. In case /linuxrc is dynamically linked, all required shared libraries from /lib must be available in Initrd also. /linuxrc can also be a shell script, in that case a shell must exist in /bin. In SUSE Linux, a statically-linked /linuxrc is used to keep initrd as small as possible. When /linuxrc process exits, the kernel assumes that the real root file system has been mounted and executes /sbin/init to begin the normal user-space boot process. On an Initrd, the new final root is mounted at a temporary mount point and rotated into place with pivot_root(8) (to change the root filesystem). This leaves the Initial root file system at a mount point (such as /initrd) where normal boot scripts can later unmount it to free up memory held by the Initrd.   For Initramfs: Initramfs is available since the Linux kernel 2.6.13. The Initramfs image may be a cpio archive (optionally compressed). The archive is unpacked by the kernel into a special instance of a tmpfs that becomes the initial root file system. :pencil: The Initramfs has the advantage over the Initrd of not requiring an intermediate file system or block device drivers to be compiled into the kernel. Red Hat Linux distribution uses the dracut package to create an initramfs image. With Initramfs, the kernel executes /init as its first process that is not expected to exit. The /init program is typically a shell script. For some applications like Ubuntu live cds, Initramfs can use the casper utility to create a writable environment using unionfs to overlay a persistence layer over a read-only root filesystem image. For example, overlay data can be stored on a USB flash drive, while a compressed SquashFS read-only image stored on a live CD acts as a root filesystem. :pencil: On an Initramfs, the initial root file system cannot be rotated away like that on Initrd using pivot_root(8). Instead, Initramfs is simply emptied and the final root file system mounted over the top.   kernel can unpack Initrd or Initramfs images compressed with gzip, bzip2, LZMA, XZ, LZO, LZ4 and zstd. Initrd and Initramfs implement /linuxrc or /init as a shell script. Both include a minimal shell (usually /bin/ash) along with some essential user-space utilities (usually BusyBox toolkit). To further save space, the shell, utilities and their supporting libraries are typically compiled with space optimizations enabled (such as gcc -O flag) and linked against klibc, a minimal version of the libc library written specifically for this purpose. Few more details about: Initial RAM Disk (Initrd): Initrd provides the capability to load a RAM disk Image and mount it as the Root File System by the Bootloader. Then user-space programs can be run from it. Afterwards, a new larger Root File System can be mounted from a different device. The previous root (from initrd) is then moved to a directory and can be subsequently unmounted. Initrd is mainly designed to allow system startup to occur in two phases, where the kernel comes up with a minimum set of compiled-in drivers, and where additional modules are loaded from initrd.   IMPORTANT: Initrd mechanism has been deprecated and the support for it is removed from Linux Kernel from 2021. Initramfs had been introduced since Linux Kernel 2.6. It is the recommended way for implementing initial root file system all modern Linux distributions. Even if you see files named as initrd-$(uname -r) in /boot folders on modern Linux distributions like Ubuntu/Debian, keep in mind that this is not an initrd but actually an Initramfs only. That means, it can be a concatenation of multiple cpio archives, each of which may or may not be compressed. References: [PATCH 14/23] initrd: mark initrd support as deprecated Re: using deprecated initrd support, will be removed in 2021 Init RAM File System (Initramfs): Linux Kernel version 2.6 onwards, contain a gzipped cpio format archive, which is extracted into ROOTFS when the kernel boots up. An Initramfs archive is a complete self-contained ROOTFS for Linux. The Linux Kernel version 2.6 build process always creates a gzipped cpio format initramfs archive and links it into the resulting kernel binary. By default, this archive is empty (consuming 134 bytes on x86). After extracting, the kernel checks to see if ROOTFS contains a file /init, and if so it executes it as PID=1. This init process is responsible for bringing rest of the system up, including locating and mounting the real root device (if any). If ROOTFS does not contain an init program after the embedded cpio archive is extracted into it, the kernel will try to locate and mount a ROOT partition, then exec some variant of /sbin/init out of that. Using External initramfs images: If the kernel has initrd support enabled, an external cpio.gz archive can also be passed into a v2.6 kernel in place of an Initrd. The kernel will autodetect the type as Initramfs, and extract the external cpio archive as a ROOTFS before trying to run /init. This approach of separately packaging of Initramfs has an Advantage that, you can run a non-GPL code from within Initramfs, without conflating it with the GPL licensed Linux kernel binary. External Initramfs can supplement the kernel’s built-in initramfs image. The external archive will overwrite any conflicting files in the built-in initramfs archive. Initramfs usually contains either klibc or uClibc which are C libraries designed to statically link early userspace code against, along with some related utilities. Also contains BusyBox. Why Kernel replaced Initrd with Initramfs RAMdisk vs RAMfs A RAMdisk (like Initrd) is a RAM based Block device, which means it’s a fixed size of memory that can be formatted and mounted like a disk. The contents of the RAMdisk have to be formatted with mke2fs and mounted with losetup tools, and like all block devices it requires a filesystem driver to interpret the data at runtime. Normally these tools are kept on a file system as user-space program, but as there’s no real file system mounted at this boot stage, these tools and drivers are required to be compiled in the Kernel itself. Fixed size requirement of RAMdisk puts a limitation on the size, that will either wastes the excess memory or will not be adequate for the purpose. You can't expand or shrink it without formatting again. RAMdisk also wastes memory as it gets cached, as Linux caches all the files read from or written to block devices. This is the downside of the RAMdisk being treated as a block device. Whereas, Initramfs is an instance of tmpfs, which automatically grow or shrink to fit the size of the data they contain. Adding files to a Initramfs (or extending existing files) automatically allocates more memory, and deleting or truncating files frees that memory. With Initramfs, as there’s no block device, there’s no duplication of data between block device and cache. Initramfs doesn’t need any file system driver built in the Kernel.   Few other design limitations of Initrd overcame by Initramfs: The /linuxrc tries to determine the several available devices for real ROOTFS before returning the identified device number to the Kernel so the kernel could mount the real root device and execute the real init program. Initrd assums that real ROOTFS will always be a Block device, rather than a network share. Also Initrd was never considered to be the real ROOTFS for memory constrained embedded devices. In Initrd, /linuxrc is not run like an init program with PID=1, which actually provides special properties reserved for init like it cannot be killed with kill -9 command. In Initramfs, the Kernel doesn’t care where the real ROOTFS is (it’s Initramfs until init program from real ROOTFS is executed). In Initramfs, the init program of Initramfs is always run as a real init, with PID=1. When Initramfs init needs to hand that special Process ID off to another program, it can use the exec() syscall just like everybody else. Use cases for Initramfs or Initrd 1. Minimizing Linux Kernel size The idea here is that there’s a lot of initialization tasks done in the Linux Kernel that could be just as easily done in userspace. Many modules required for mounting different typesf of ROOTFS like NFS, LVM, etc can be offloaded to Initramfs or Initrd instead of compiling all of them into the kernel, as not all of these modules will be required for every type of ROOTFS mounting. 2. Mounting Real ROOTFS Some Linux distributions like Debian generates a customized Initrd image which contains only necessary stuffs to boot some particular computer, such as ATA, SCSI and filesystem kernel modules. Such images typically embed the location and type of the root file system. Other Linux distributions like Ubuntu generates a generic Initrd image. These images start only with the device name of the root file system (or its UUID) and discovers everything else at boot time. In this case, the software must perform a complex cascade of tasks to get the root file system mounted. Few examples of what else would be required to be done to boot the ROOTFS are: Load all storage device drivers that are required by the boot process. For this, kernel modules of common storage devices can be added to Initrd image and then an event-driven hotplug agent like udev can be used to load the modules matching the computer’s detected hardware. If Boot Splash Screen is required, the video hardware must be initialized along with user-space utilities to paint the splash screen animation during the boot process. If the NFS needs to be accessed, Initrd must bring up the primary network interface, invoke a DHCP client, to obtain a DHCP lease, extract the name of the NFS shared location and the address of the NFS server from the lease, and mount the NFS shared location. If root file system is on a logical volume, the LVM utilities must be invoked to scan for the activate the volume group containing it. If root file system is on an encrypted block device, the Initrd needs to invoke a utility script to prompt the user to type in a passphrase and/or insert a hardware token (such as a smart card or a USB security dongle), and then create a decryption target with the device mapper. 3. Maintenance Tasks on ROOTFS before mounting When the Root file system finally becomes visible, any maintenance tasks that cannot be ran on a mounted Root file system are required to be done, the Root file system is mounted read-only, and any processes that must continue running (such as the splash screen utility) are hoisted into the newly mounted root file system. 4. Recovery disks creation Initrd or Initramfs can be used to create a Recovery Disk Image or Backup a Partition. Because with Initrd or Initramfs mechanism, the real ROOTFS is not required to be loaded, so the backup of the ROOTFS can be created and saved to some external device like USB/CD-ROM. The system loaded from initrd can invoke a user-friendly dialog or it can also perform some form of auto-detection for available backup media. 5. Linux Installers Linux distribution Installers typically run entirely from an Initramfs, as they must be able to host the installer interface and supporting tools before any persistent storage has been set up. CD-ROM distributors may use Initrd for better installation from CD, by bootstrapping a bigger RAM disk via initrd from CD; or by booting via a bootloader like loadlin or directly from the CD-ROM. Tiny Core Linux (TCL) and Puppy Linux can run entirely from Initrd. References initrd Introducing initramfs, a new model for initial RAM disks Kernel.org: ramfs-rootfs-initramfs]]></summary></entry><entry><title type="html">Why Docker Compose Safeguards Container Runtime Changes Through Host Reboots: A Comprehensive Exploration</title><link href="https://akhileshmoghe.github.io/_posts/containers/container_lifecycle_with_docker_compose" rel="alternate" type="text/html" title="Why Docker Compose Safeguards Container Runtime Changes Through Host Reboots: A Comprehensive Exploration" /><published>2023-07-12T12:33:22+05:30</published><updated>2023-07-12T12:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_posts/containers/Conatiner-Lifecycle-With-Docker-And-DockerCompose</id><content type="html" xml:base="https://akhileshmoghe.github.io/_posts/containers/container_lifecycle_with_docker_compose"><![CDATA[<p>In the container’s lifecycle, a container undergoes various stages from creation to deletion, mainly <strong><em>Created</em></strong>, <strong><em>Running</em></strong>, <strong><em>Paused</em></strong>, <strong><em>Stopped</em></strong>, and <strong><em>Deleted</em></strong>. Managing containers involves considering different conditions for creation/recreation, restarting, or deletion based on specific requirements &amp; conditions. In a microservices architecture, where multiple containers coexist, the decision to recreate a running container or simply restarting it can significantly impact the overall performance of the deployment or application.<br />
 
Containers can be created and started using the Docker CLI but they can also be efficiently managed through orchestration tools such as Docker Compose. These tools are designed to optimize the container lifecycle, incorporating predefined rules for efficient container management. Whether using the Docker CLI or orchestration tools, understanding these rules and the underlying mechanisms is crucial for effective containerization. Docker Compose, as a powerful orchestration tool, streamlines the process of container management, ensuring a seamless and optimized experience for users. Exploring the intricacies of these tools and their hidden efficiencies can enhance your overall container orchestration strategy.<br />
 
While leveraging orchestration tools like Docker Compose, discrepancies may arise between our anticipated container state in a given situation and the actual state managed by these tools. Such mismatches can lead to unexpected behaviors and operational challenges.<br />
 
In this concise blog, I’ll shed light on a specific condition I encountered during my Docker Compose usage, aiming to clarify and provide insights into handling such scenarios effectively.</p>

<hr />

<h2 id="container-lifecycle-transitions-illustration">Container lifecycle Transitions Illustration:</h2>
<ul>
  <li>Below is a fine representation of the Container lifecycle, this is how the container transitions from creation to deletion.
<img src="/assets/images/devops/container/docker-containers-lifecycle-stages.png" alt="docker-containers-lifecycle-stages" /></li>
</ul>

<hr />

<h2 id="unraveling-the-confusion-misunderstanding-due-to-one-of-docker-composes-feature">Unraveling the Confusion: Misunderstanding due to one of Docker Compose’s Feature</h2>
<ul>
  <li>We know, Containers are ephemeral, they are not suppose to preserve the data or the changes to the filesystem after running. Also, any tempororily copied files should not be expected to be there during the container restarts.</li>
  <li>That’s fine, but while working with Docker Compose, I ran into a situation where it was evident that during multiple restarts of the container, the container was able to preserve the runtime changes to it’s filesystem and data.</li>
  <li>The extent of the conceptual misunderstanding became more complex and hampering, when I even restarted the host device on which the Docker compose and the containers were running. During multiple reboots also the restarted container had preserved the filesystem and data changes.</li>
  <li>This was completely out-of-line about what I had learnt about container lifecycle, that on restarts, the temporory changes made in a container will no longer be there.</li>
  <li>But with Docker Compose, I was observing a completely different behaviour of containers. Chnages to the container persists during restarts of container.</li>
  <li>HOW????</li>
</ul>

<hr />

<h2 id="decoding-the-source-of-confusion-understanding-the-docker-compose-feature-behind-the-misunderstanding">Decoding the Source of Confusion: Understanding the Docker Compose Feature Behind the Misunderstanding</h2>
<ul>
  <li><a href="https://docs.docker.com/compose/features-uses/#only-recreate-containers-that-have-changed">Only recreate containers that have changed</a>
    <ul>
      <li>Docker Compose caches the configuration used to create a container.</li>
      <li>When you restart a service that has not changed, Compose re-uses the existing containers.</li>
      <li>Re-using containers means that you can make changes to your environment very quickly.</li>
    </ul>
  </li>
  <li>It’s clear from above documentation, that Docker compose does not create the container from the container images everytime. It preserves the containers during multiple invocations of the containers.</li>
  <li>This is why the temporary changes made to the container are available even after container and the host it is running on are restarted multiple times.</li>
</ul>

<hr />

<h2 id="docker-compose-up-behaviour-and-options"><u>docker compose up</u> behaviour and options</h2>
<ul>
  <li>Docker Compose <strong>Builds</strong>, <em>(re)</em><strong>creates</strong>, <strong>starts</strong>, and <strong>attaches</strong> to containers for a service.</li>
  <li>Unless they are already running, this command also <strong>starts any linked services</strong>.</li>
  <li><u>By default, Docker Compose does not re-create the existing containers for a service</u>.</li>
  <li>Docker Compose <u>only re-creates a container if the service’s configuration or image was changed after the container’s creation</u>. <code class="language-plaintext highlighter-rouge">docker compose up</code> picks up the changes by stopping and recreating the containers (preserving mounted volumes).</li>
  <li><u>Options for </u><code class="language-plaintext highlighter-rouge">docker compose up</code>:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">--force-recreate</code>:
        <ul>
          <li>If you want to force Compose to stop and recreate all containers, use the <code class="language-plaintext highlighter-rouge">--force-recreate</code> flag.</li>
        </ul>
      </li>
      <li><code class="language-plaintext highlighter-rouge">--no-recreate</code>:
        <ul>
          <li><code class="language-plaintext highlighter-rouge">docker compose up</code> picks up the changes by stopping and recreating the containers (preserving mounted volumes). To prevent Compose from picking up changes, use the <code class="language-plaintext highlighter-rouge">--no-recreate</code> flag.</li>
        </ul>
      </li>
      <li><code class="language-plaintext highlighter-rouge">--always-recreate-deps</code>
        <ul>
          <li>Recreate dependent containers.</li>
          <li>This option is incompatible with <code class="language-plaintext highlighter-rouge">--no-recreate</code>.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h3 id="other-options-for-docker-compose-up">Other options for docker compose up</h3>
<ul>
  <li><code class="language-plaintext highlighter-rouge">--abort-on-container-exit</code><br />
Stops all containers if any container was stopped.<br />
Incompatible with <code class="language-plaintext highlighter-rouge">-d</code></li>
  <li><code class="language-plaintext highlighter-rouge">--attach</code><br />
Attach to service output.</li>
  <li><code class="language-plaintext highlighter-rouge">--attach-dependencies</code><br />
Attach to dependent containers.</li>
  <li><code class="language-plaintext highlighter-rouge">--build</code><br />
Build images before starting containers.</li>
  <li><code class="language-plaintext highlighter-rouge">--detach</code> , <code class="language-plaintext highlighter-rouge">-d</code><br />
Detached mode: Run containers in the background</li>
  <li><code class="language-plaintext highlighter-rouge">--exit-code-from</code><br />
Return the exit code of the selected service container.<br />
Implies <code class="language-plaintext highlighter-rouge">--abort-on-container-exit</code></li>
  <li><code class="language-plaintext highlighter-rouge">--force-recreate</code><br />
Recreate containers even if their configuration and image haven’t changed.</li>
  <li><code class="language-plaintext highlighter-rouge">--no-attach</code><br />
Don’t attach to specified service.</li>
  <li><code class="language-plaintext highlighter-rouge">--no-build</code><br />
Don’t build an image, even if it’s missing.</li>
  <li><code class="language-plaintext highlighter-rouge">--no-color</code><br />
Produce monochrome output.</li>
  <li><code class="language-plaintext highlighter-rouge">--no-deps</code><br />
Don’t start linked services.</li>
  <li><code class="language-plaintext highlighter-rouge">--no-log-prefix</code><br />
Don’t print prefix in logs.</li>
  <li><code class="language-plaintext highlighter-rouge">--no-recreate</code><br />
If containers already exist, don’t recreate them.<br />
Incompatible with <code class="language-plaintext highlighter-rouge">--force-recreate</code>.</li>
  <li><code class="language-plaintext highlighter-rouge">--no-start</code><br />
Don’t start the services after creating them.</li>
  <li><code class="language-plaintext highlighter-rouge">--pull</code><br />
Missing	Pull image before running (“always”,”missing”,”never”)</li>
  <li><code class="language-plaintext highlighter-rouge">--quiet-pull</code><br />
Pull without printing progress information.</li>
  <li><code class="language-plaintext highlighter-rouge">--remove-orphans</code><br />
Remove containers for services not defined in the Compose file.</li>
  <li><code class="language-plaintext highlighter-rouge">--renew-anon-volumes</code> , <code class="language-plaintext highlighter-rouge">-V</code><br />
Recreate anonymous volumes instead of retrieving data from the previous containers.</li>
  <li><code class="language-plaintext highlighter-rouge">--scale</code><br />
Scale SERVICE to NUM instances.<br />
Overrides the scale setting in the Compose file if present.</li>
  <li><code class="language-plaintext highlighter-rouge">--timeout</code> , <code class="language-plaintext highlighter-rouge">-t</code><br />
Use this timeout in seconds for container shutdown when attached or when containers are already running.</li>
  <li><code class="language-plaintext highlighter-rouge">--timestamps</code><br />
Show timestamps.</li>
  <li><code class="language-plaintext highlighter-rouge">--wait</code><br />
Wait for services to be running|healthy.<br />
Implies detached mode.</li>
  <li><code class="language-plaintext highlighter-rouge">--wait-timeout</code><br />
Timeout waiting for application to be running|healthy.</li>
  <li><code class="language-plaintext highlighter-rouge">--dry-run</code><br />
Execute command in dry run mode</li>
</ul>

<hr />

<h6 id="references">References:</h6>
<ul>
  <li><a href="https://docs.docker.com/compose/features-uses/">Docker Compose: Key features and use cases</a></li>
  <li><a href="https://docs.docker.com/engine/reference/commandline/compose_up/#:~:text=If%20there%20are%20existing%20containers,the%20%2D%2Dno%2Drecreate%20flag.">docker compose up</a></li>
  <li><a href="https://dev.to/docker/docker-architecture-life-cycle-of-docker-containers-and-data-management-1a9c">Docker Architecture, Life Cycle of Docker Containers and Data Management</a></li>
</ul>]]></content><author><name>Akhilesh Moghe</name></author><category term="Containers" /><category term="Docker" /><category term="Docker-Compose" /><category term="DevOps" /><category term="Containers" /><category term="Docker" /><category term="Docker-Compose" /><category term="DevOps" /><summary type="html"><![CDATA[In the container’s lifecycle, a container undergoes various stages from creation to deletion, mainly Created, Running, Paused, Stopped, and Deleted. Managing containers involves considering different conditions for creation/recreation, restarting, or deletion based on specific requirements &amp; conditions. In a microservices architecture, where multiple containers coexist, the decision to recreate a running container or simply restarting it can significantly impact the overall performance of the deployment or application.   Containers can be created and started using the Docker CLI but they can also be efficiently managed through orchestration tools such as Docker Compose. These tools are designed to optimize the container lifecycle, incorporating predefined rules for efficient container management. Whether using the Docker CLI or orchestration tools, understanding these rules and the underlying mechanisms is crucial for effective containerization. Docker Compose, as a powerful orchestration tool, streamlines the process of container management, ensuring a seamless and optimized experience for users. Exploring the intricacies of these tools and their hidden efficiencies can enhance your overall container orchestration strategy.   While leveraging orchestration tools like Docker Compose, discrepancies may arise between our anticipated container state in a given situation and the actual state managed by these tools. Such mismatches can lead to unexpected behaviors and operational challenges.   In this concise blog, I’ll shed light on a specific condition I encountered during my Docker Compose usage, aiming to clarify and provide insights into handling such scenarios effectively. Container lifecycle Transitions Illustration: Below is a fine representation of the Container lifecycle, this is how the container transitions from creation to deletion. Unraveling the Confusion: Misunderstanding due to one of Docker Compose’s Feature We know, Containers are ephemeral, they are not suppose to preserve the data or the changes to the filesystem after running. Also, any tempororily copied files should not be expected to be there during the container restarts. That’s fine, but while working with Docker Compose, I ran into a situation where it was evident that during multiple restarts of the container, the container was able to preserve the runtime changes to it’s filesystem and data. The extent of the conceptual misunderstanding became more complex and hampering, when I even restarted the host device on which the Docker compose and the containers were running. During multiple reboots also the restarted container had preserved the filesystem and data changes. This was completely out-of-line about what I had learnt about container lifecycle, that on restarts, the temporory changes made in a container will no longer be there. But with Docker Compose, I was observing a completely different behaviour of containers. Chnages to the container persists during restarts of container. HOW???? Decoding the Source of Confusion: Understanding the Docker Compose Feature Behind the Misunderstanding Only recreate containers that have changed Docker Compose caches the configuration used to create a container. When you restart a service that has not changed, Compose re-uses the existing containers. Re-using containers means that you can make changes to your environment very quickly. It’s clear from above documentation, that Docker compose does not create the container from the container images everytime. It preserves the containers during multiple invocations of the containers. This is why the temporary changes made to the container are available even after container and the host it is running on are restarted multiple times. docker compose up behaviour and options Docker Compose Builds, (re)creates, starts, and attaches to containers for a service. Unless they are already running, this command also starts any linked services. By default, Docker Compose does not re-create the existing containers for a service. Docker Compose only re-creates a container if the service’s configuration or image was changed after the container’s creation. docker compose up picks up the changes by stopping and recreating the containers (preserving mounted volumes). Options for docker compose up: --force-recreate: If you want to force Compose to stop and recreate all containers, use the --force-recreate flag. --no-recreate: docker compose up picks up the changes by stopping and recreating the containers (preserving mounted volumes). To prevent Compose from picking up changes, use the --no-recreate flag. --always-recreate-deps Recreate dependent containers. This option is incompatible with --no-recreate. Other options for docker compose up --abort-on-container-exit Stops all containers if any container was stopped. Incompatible with -d --attach Attach to service output. --attach-dependencies Attach to dependent containers. --build Build images before starting containers. --detach , -d Detached mode: Run containers in the background --exit-code-from Return the exit code of the selected service container. Implies --abort-on-container-exit --force-recreate Recreate containers even if their configuration and image haven’t changed. --no-attach Don’t attach to specified service. --no-build Don’t build an image, even if it’s missing. --no-color Produce monochrome output. --no-deps Don’t start linked services. --no-log-prefix Don’t print prefix in logs. --no-recreate If containers already exist, don’t recreate them. Incompatible with --force-recreate. --no-start Don’t start the services after creating them. --pull Missing Pull image before running (“always”,”missing”,”never”) --quiet-pull Pull without printing progress information. --remove-orphans Remove containers for services not defined in the Compose file. --renew-anon-volumes , -V Recreate anonymous volumes instead of retrieving data from the previous containers. --scale Scale SERVICE to NUM instances. Overrides the scale setting in the Compose file if present. --timeout , -t Use this timeout in seconds for container shutdown when attached or when containers are already running. --timestamps Show timestamps. --wait Wait for services to be running|healthy. Implies detached mode. --wait-timeout Timeout waiting for application to be running|healthy. --dry-run Execute command in dry run mode References: Docker Compose: Key features and use cases docker compose up Docker Architecture, Life Cycle of Docker Containers and Data Management]]></summary></entry><entry><title type="html">Enhancing Container Security: A Guide to Runtime Privileges and Linux Capabilities in Docker Containers</title><link href="https://akhileshmoghe.github.io/_posts/devops/containers/docker-container-runtime-privileges-linux-capabilities" rel="alternate" type="text/html" title="Enhancing Container Security: A Guide to Runtime Privileges and Linux Capabilities in Docker Containers" /><published>2023-04-19T01:33:22+05:30</published><updated>2023-04-19T01:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_posts/devops/containers/Docker-Container-Runtime-Privilege-Linux-Capabilities</id><content type="html" xml:base="https://akhileshmoghe.github.io/_posts/devops/containers/docker-container-runtime-privileges-linux-capabilities"><![CDATA[<p>Docker containers are a popular way to package and deploy applications, but they can also pose security risks if not properly configured. One important aspect of container security is managing runtime privileges - that is, controlling the level of access and permissions that a container has when it is running.<br />
In Linux, one way to manage runtime privileges is through the use of Linux Capabilities. Capabilities are a granular way of assigning privileges to processes, allowing them to perform certain privileged operations without needing to run as the root user. This helps to reduce the attack surface of a system and improve security.<br />
In this blog, we’ll explore the concept of runtime privileges and Linux capabilities in the context of Docker containers. We’ll look at some common capabilities and how they can be used to enhance container security. We’ll provide guidance on how to use Linux capabilities to grant additional privileges to Docker containers in a secure and controlled manner. Whether you’re new to Docker security or an experienced user, this blog will provide valuable insights into managing runtime privileges and permissions in containerized environments.</p>

<h2 id="options-to-run-containers-with-priviliged-access">Options to run containers with priviliged access</h2>
<ul>
  <li>By default, Docker containers run as “<strong><u>unprivileged</u></strong>”, which means they lack device access, preventing certain processes like Docker daemon from running within them.</li>
  <li>Easiest but most unsecured way to enable access to all devices for a container is to run the container with <code class="language-plaintext highlighter-rouge">--privileged</code> flag.</li>
  <li>The <code class="language-plaintext highlighter-rouge">--privileged</code> flag gives all capabilities to the container and enables access to all devices on the host as well as set some configuration in <em>AppArmor</em> or <em>SELinux</em>. This allows the container nearly all the same access to the host as processes running outside containers on the host.</li>
  <li>Other options which enable user to provide better granular access to running containers are explained in detail further in this blog with few examples:</li>
</ul>

<table>
  <thead>
    <tr>
      <th>Option</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--cap-add</code></td>
      <td>:small_blue_diamond: Add Linux capabilities</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--cap-drop</code></td>
      <td>:small_blue_diamond: Drop Linux capabilities</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--privileged</code></td>
      <td>:small_blue_diamond: Give extended privileges to this container</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--device=[]</code></td>
      <td>:small_blue_diamond: Allows you to run devices inside the container without the <code class="language-plaintext highlighter-rouge">--privileged</code> flag.</td>
    </tr>
  </tbody>
</table>

<h2 id="provide-host-devices-access-to-containers">Provide Host devices access to Containers</h2>
<ul>
  <li>In a Linux system, devices refer to physical or virtual components that can be accessed through the operating system. Types of devices:
    <ul>
      <li>Character devices: These devices provide a stream of data in a sequential manner. Examples of character devices include Keyboards, Mouse, Serial Ports, and Audio devices.</li>
      <li>Block devices: These devices provide access to fixed-size blocks of data, and are often used for storage devices such as hard disks, SSDs, and USB drives.</li>
      <li>Network devices: which allow for communication with other devices on a network, like Network Interface Cards (NICs), Modems, Routers, Switches, Bridges.</li>
      <li>Virtual devices: which are created by software for specific purposes like Virtual COM Port.</li>
    </ul>
  </li>
  <li>By default, containers do not have access to any of the host devices.</li>
  <li>If you want to limit access to a specific device or few devices you can use the <code class="language-plaintext highlighter-rouge">--device</code> flag. It allows you to specify one or more devices that will be accessible within the container.</li>
</ul>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>docker run <span class="nt">--device</span><span class="o">=</span>/dev/snd:/dev/snd ...
</code></pre></div></div>

<ul>
  <li>By default, the container will be able to <code class="language-plaintext highlighter-rouge">read</code>, <code class="language-plaintext highlighter-rouge">write</code>, and <code class="language-plaintext highlighter-rouge">mknod</code> these devices.</li>
  <li>But, this can be <em>overridden</em> using a third <code class="language-plaintext highlighter-rouge">:rwm</code> set of options to each <code class="language-plaintext highlighter-rouge">--device</code> flag:</li>
</ul>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>docker run <span class="nt">--device</span><span class="o">=</span>/dev/sda:/dev/xvdc <span class="nt">--rm</span> <span class="nt">-it</span> ubuntu fdisk  /dev/xvdc

<span class="nv">$ </span>docker run <span class="nt">--device</span><span class="o">=</span>/dev/sda:/dev/xvdc:r <span class="nt">--rm</span> <span class="nt">-it</span> ubuntu fdisk  /dev/xvdc
<span class="nt">--</span><span class="o">&gt;</span> You will not be able to write the partition table.

<span class="nv">$ </span>docker run <span class="nt">--device</span><span class="o">=</span>/dev/sda:/dev/xvdc:w <span class="nt">--rm</span> <span class="nt">-it</span> ubuntu fdisk  /dev/xvdc
<span class="nt">--</span><span class="o">&gt;</span> crash....

<span class="nv">$ </span>docker run <span class="nt">--device</span><span class="o">=</span>/dev/sda:/dev/xvdc:m <span class="nt">--rm</span> <span class="nt">-it</span> ubuntu fdisk  /dev/xvdc
<span class="nt">--</span><span class="o">&gt;</span> fdisk: unable to open /dev/xvdc: Operation not permitted
</code></pre></div></div>

<h2 id="linux-capabilities">Linux Capabilities:</h2>
<ul>
  <li>Linux capabilities are a powerful feature that provides fine-grained access control over system resources to processes without granting them full root privileges.</li>
  <li>Capabilities can be used to restrict or enhance the access rights of a process to a specific set of resources, such as the ability to bind to privileged ports, modify system time, or read and write to system files.</li>
  <li>Each capability is a bit that can be set or cleared to indicate whether the corresponding privilege is allowed or not for a process. By default, a process has a set of basic capabilities, but additional capabilities can be added or removed using the <code class="language-plaintext highlighter-rouge">setcap</code> and <code class="language-plaintext highlighter-rouge">getcap</code> utilities.</li>
  <li>Capabilities are widely used in modern Linux systems to improve security, reduce the attack surface, and enforce the principle of least privilege.</li>
  <li>For a full list of Linux Capabilities and their details refer to below Linux man page:
    <ul>
      <li><a href="https://man7.org/linux/man-pages/man7/capabilities.7.html">capabilities(7) — Linux manual page</a></li>
    </ul>
  </li>
</ul>

<h2 id="default-linux-capabilities-included-with-docker-containers">Default Linux Capabilities included with Docker Containers</h2>
<ul>
  <li>Instead of providing priviliged access to containers, with <code class="language-plaintext highlighter-rouge">--privileged</code> flag, the users can have fine grain control over the capabilities using <code class="language-plaintext highlighter-rouge">--cap-add</code> and <code class="language-plaintext highlighter-rouge">--cap-drop</code> flags.</li>
  <li>Docker keeps following Linux capability options allowed by default and but these can be dropped, if required:</li>
</ul>

<table>
  <thead>
    <tr>
      <th>Capability Key</th>
      <th>Capability Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">AUDIT_WRITE</code></td>
      <td>Write records to kernel auditing log.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CHOWN</code></td>
      <td>Make arbitrary changes to file UIDs and GIDs (see chown(2)).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">DAC_OVERRIDE</code></td>
      <td>Bypass file read, write, and execute permission checks.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">FOWNER</code></td>
      <td>Bypass permission checks on operations that normally require the file system UID of the process to match the UID of the file.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">FSETID</code></td>
      <td>Don’t clear set-user-ID and set-group-ID permission bits when a file is modified.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">KILL</code></td>
      <td>Bypass permission checks for sending signals.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">MKNOD</code></td>
      <td>Create special files using mknod(2).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">NET_BIND_SERVICE</code></td>
      <td>Bind a socket to internet domain privileged ports (port numbers less than 1024).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">NET_RAW</code></td>
      <td>Use RAW and PACKET sockets.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SETFCAP</code></td>
      <td>Set file capabilities.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SETGID</code></td>
      <td>Make arbitrary manipulations of process GIDs and supplementary GID list.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SETPCAP</code></td>
      <td>Modify process capabilities.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SETUID</code></td>
      <td>Make arbitrary manipulations of process UIDs.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_CHROOT</code></td>
      <td>Use chroot(2), change root directory.</td>
    </tr>
  </tbody>
</table>

<h2 id="providing-additional-capabilities-to-containers">Providing additional capabilities to containers</h2>
<ul>
  <li>As an eample, for interacting with the network stack, instead of using <code class="language-plaintext highlighter-rouge">--privileged</code> one should use <code class="language-plaintext highlighter-rouge">--cap-add=NET_ADMIN</code> to modify the network interfaces.</li>
</ul>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>docker run <span class="nt">-it</span> <span class="nt">--rm</span>  ubuntu:22.04 ifconfig
<span class="nt">--</span><span class="o">&gt;</span> Allowed

<span class="nv">$ </span>docker run <span class="nt">-it</span> <span class="nt">--rm</span>  ubuntu:22.04 ifconfig lan2 down
<span class="nt">--</span><span class="o">&gt;</span> SIOCSIFFLAGS: Operation not permitted

<span class="nv">$ </span>docker run <span class="nt">-it</span> <span class="nt">--rm</span> <span class="nt">--cap-add</span><span class="o">=</span>NET_ADMIN ubuntu:22.04 ifconfig lan2 down
<span class="nt">--</span><span class="o">&gt;</span> Allowed
</code></pre></div></div>

<ul>
  <li>Both <code class="language-plaintext highlighter-rouge">--cap-add</code> &amp; <code class="language-plaintext highlighter-rouge">--cap-drop</code> flags support the value <code class="language-plaintext highlighter-rouge">ALL</code>, so to allow a container to use all capabilities except for <code class="language-plaintext highlighter-rouge">MKNOD</code>:</li>
</ul>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">--cap-add</span><span class="o">=</span>ALL <span class="nt">--cap-drop</span><span class="o">=</span>MKNOD ...
</code></pre></div></div>

<ul>
  <li>The <code class="language-plaintext highlighter-rouge">--cap-add</code> and <code class="language-plaintext highlighter-rouge">--cap-drop</code> flags accept capabilities to be specified with a <code class="language-plaintext highlighter-rouge">CAP_</code> prefix. The following examples are therefore equivalent:</li>
</ul>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">--cap-add</span><span class="o">=</span>SYS_ADMIN ...
docker run <span class="nt">--cap-add</span><span class="o">=</span>CAP_SYS_ADMIN ...
</code></pre></div></div>

<ul>
  <li>Following are the capabilities which are not granted by default and may be added with <code class="language-plaintext highlighter-rouge">--cap-add</code> and can be dropped with <code class="language-plaintext highlighter-rouge">--cap-drop</code> options.</li>
</ul>

<table>
  <thead>
    <tr>
      <th>Capability Key</th>
      <th>Capability Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">AUDIT_CONTROL</code></td>
      <td>Enable and disable kernel auditing; change auditing filter rules; retrieve auditing status and filtering rules.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">AUDIT_READ</code></td>
      <td>Allow reading the audit log via multicast netlink socket.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BLOCK_SUSPEND</code></td>
      <td>Allow preventing system suspends.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">BPF</code></td>
      <td>Allow creating BPF maps, loading BPF Type Format (BTF) data, retrieve JITed code of BPF programs, and more.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">CHECKPOINT_RESTORE</code></td>
      <td>Allow checkpoint/restore related operations. Introduced in kernel 5.9.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">DAC_READ_SEARCH</code></td>
      <td>Bypass file read permission checks and directory read and execute permission checks.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">IPC_LOCK</code></td>
      <td>Lock memory (mlock(2), mlockall(2), mmap(2), shmctl(2)).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">IPC_OWNER</code></td>
      <td>Bypass permission checks for operations on System V IPC objects.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">LEASE</code></td>
      <td>Establish leases on arbitrary files (see fcntl(2)).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">LINUX_IMMUTABLE</code></td>
      <td>Set the FS_APPEND_FL and FS_IMMUTABLE_FL i-node flags.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">MAC_ADMIN</code></td>
      <td>Allow MAC configuration or state changes. Implemented for the Smack LSM.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">MAC_OVERRIDE</code></td>
      <td>Override Mandatory Access Control (MAC). Implemented for the Smack Linux Security Module (LSM).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">NET_ADMIN</code></td>
      <td>Perform various network-related operations.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">NET_BROADCAST</code></td>
      <td>Make socket broadcasts, and listen to multicasts.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">PERFMON</code></td>
      <td>Allow system performance and observability privileged operations using perf_events, i915_perf and other kernel subsystems</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_ADMIN</code></td>
      <td>Perform a range of system administration operations.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_BOOT</code></td>
      <td>Use reboot(2) and kexec_load(2), reboot and load a new kernel for later execution.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_MODULE</code></td>
      <td>Load and unload kernel modules.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_NICE</code></td>
      <td>Raise process nice value (nice(2), setpriority(2)) and change the nice value for arbitrary processes.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_PACCT</code></td>
      <td>Use acct(2), switch process accounting on or off.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_PTRACE</code></td>
      <td>Trace arbitrary processes using ptrace(2).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_RAWIO</code></td>
      <td>Perform I/O port operations (iopl(2) and ioperm(2)).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_RESOURCE</code></td>
      <td>Override resource Limits.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_TIME</code></td>
      <td>Set system clock (settimeofday(2), stime(2), adjtimex(2)); set real-time (hardware) clock.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYS_TTY_CONFIG</code></td>
      <td>Use vhangup(2); employ various privileged ioctl(2) operations on virtual terminals.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SYSLOG</code></td>
      <td>Perform privileged syslog(2) operations.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">WAKE_ALARM</code></td>
      <td>Trigger something that will wake up the system.</td>
    </tr>
  </tbody>
</table>

<h2 id="mounting-fuse-based-file-systems-to-docker-containers">Mounting FUSE based file systems to Docker containers:</h2>
<ul>
  <li>What are the <strong><em>FUSE</em></strong> based filesystems?
    <ul>
      <li><strong><em><u>FUSE (Filesystem in Userspace)</u></em></strong> is a software interface that allows non-privileged users to create their own file systems without requiring any kernel-level programming. FUSE-based file systems are file systems that are implemented using the <a href="https://github.com/libfuse/libfuse">FUSE interface</a>.</li>
      <li>FUSE-based file systems <em>operate in userspace</em>, which means that they run as ordinary user-level programs and do not require any special privileges or access to kernel resources. This makes it easy for developers to create new file systems and experiment with new ideas, without having to worry about the complexities of kernel-level programming.</li>
      <li>FUSE-based file systems can provide a wide range of functionality, including virtual file systems, network file systems, encrypted file systems, and many others. They are used in a variety of applications, including cloud storage, backup and recovery, and distributed file systems.</li>
      <li>There are many FUSE-based file systems available, here are a few examples:
        <ul>
          <li><u>NTFS-3G</u>: A popular FUSE-based file system that provides read and write access to NTFS partitions on Linux.</li>
          <li><u>sshfs</u>: A FUSE-based file system that allows you to mount a remote file system over SSH.</li>
          <li><u>encfs</u>: A FUSE-based file system that provides an encrypted virtual file system.</li>
          <li><u>curlftpfs</u>: A FUSE-based file system that allows you to mount an FTP server as a local file system.<br />
 </li>
        </ul>
      </li>
    </ul>
  </li>
  <li>To mount a <strong><em>FUSE</em></strong> based filesystem, you need to combine both <code class="language-plaintext highlighter-rouge">--cap-add</code> and <code class="language-plaintext highlighter-rouge">--device</code>.</li>
</ul>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="nt">--cap-add</span> SYS_ADMIN sshfs sshfs sven@10.10.10.20:/home/sven /mnt
<span class="nt">--</span><span class="o">&gt;</span> fuse: failed to open /dev/fuse: Operation not permitted

<span class="nv">$ </span>docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="nt">--device</span> /dev/fuse sshfs sshfs sven@10.10.10.20:/home/sven /mnt
<span class="nt">--</span><span class="o">&gt;</span> fusermount: mount failed: Operation not permitted

<span class="nv">$ </span>docker run <span class="nt">--rm</span> <span class="nt">-it</span> <span class="nt">--cap-add</span> SYS_ADMIN <span class="nt">--device</span> /dev/fuse sshfs

<span class="c"># sshfs sven@10.10.10.20:/home/sven /mnt</span>
The authenticity of host <span class="s1">'10.10.10.20 (10.10.10.20)'</span> can<span class="s1">'t be established.
ECDSA key fingerprint is 25:34:85:75:25:b0:17:46:05:19:04:93:b5:dd:5f:c6.
Are you sure you want to continue connecting (yes/no)? yes
sven@10.10.10.20'</span>s password:

<span class="c"># root@30aa0cfaf1b5:/# ls -la /mnt/src/docker</span>
total 1516
drwxrwxr-x 1 1000 1000   4096 Dec  4 06:08 <span class="nb">.</span>
drwxrwxr-x 1 1000 1000   4096 Dec  4 11:46 ..
<span class="nt">-rw-rw-r--</span> 1 1000 1000     16 Oct  8 00:09 .dockerignore
<span class="nt">-rwxrwxr-x</span> 1 1000 1000    464 Oct  8 00:09 .drone.yml
drwxrwxr-x 1 1000 1000   4096 Dec  4 06:11 .git
<span class="nt">-rw-rw-r--</span> 1 1000 1000    461 Dec  4 06:08 .gitignore
....
</code></pre></div></div>

<hr />

<p>So that’s it for this topic, in this blog, we explored the use of Linux capabilities for managing runtime privileges in Docker containers. We discussed some common capabilities and how we can grant these privileged capabilities to containers, as well as the potential security risks of granting too many privileges.<br />
Managing runtime privileges and Linux capabilities is an essential part of container security in Docker. By default, Docker containers run as unprivileged, which limits their device access and prevents certain processes from running inside them. However, by understanding Linux capabilities and how to use them, it is possible to grant additional privileges to containers and enhance their functionality.<br />
Remember, managing runtime privileges and Linux capabilities is just one aspect of container security. It’s important to take a comprehensive approach to container security, including using <em><u>secure images</u></em>, implementing <em><u>network security</u></em>, and following other best practices.</p>

<hr />]]></content><author><name>Akhilesh Moghe</name></author><category term="Containers" /><category term="Docker" /><category term="Linux" /><category term="DevOps" /><category term="Containers" /><category term="Docker" /><category term="Linux" /><category term="DevOps" /><summary type="html"><![CDATA[Docker containers are a popular way to package and deploy applications, but they can also pose security risks if not properly configured. One important aspect of container security is managing runtime privileges - that is, controlling the level of access and permissions that a container has when it is running. In Linux, one way to manage runtime privileges is through the use of Linux Capabilities. Capabilities are a granular way of assigning privileges to processes, allowing them to perform certain privileged operations without needing to run as the root user. This helps to reduce the attack surface of a system and improve security. In this blog, we’ll explore the concept of runtime privileges and Linux capabilities in the context of Docker containers. We’ll look at some common capabilities and how they can be used to enhance container security. We’ll provide guidance on how to use Linux capabilities to grant additional privileges to Docker containers in a secure and controlled manner. Whether you’re new to Docker security or an experienced user, this blog will provide valuable insights into managing runtime privileges and permissions in containerized environments. Options to run containers with priviliged access By default, Docker containers run as “unprivileged”, which means they lack device access, preventing certain processes like Docker daemon from running within them. Easiest but most unsecured way to enable access to all devices for a container is to run the container with --privileged flag. The --privileged flag gives all capabilities to the container and enables access to all devices on the host as well as set some configuration in AppArmor or SELinux. This allows the container nearly all the same access to the host as processes running outside containers on the host. Other options which enable user to provide better granular access to running containers are explained in detail further in this blog with few examples: Option Description --cap-add :small_blue_diamond: Add Linux capabilities --cap-drop :small_blue_diamond: Drop Linux capabilities --privileged :small_blue_diamond: Give extended privileges to this container --device=[] :small_blue_diamond: Allows you to run devices inside the container without the --privileged flag. Provide Host devices access to Containers In a Linux system, devices refer to physical or virtual components that can be accessed through the operating system. Types of devices: Character devices: These devices provide a stream of data in a sequential manner. Examples of character devices include Keyboards, Mouse, Serial Ports, and Audio devices. Block devices: These devices provide access to fixed-size blocks of data, and are often used for storage devices such as hard disks, SSDs, and USB drives. Network devices: which allow for communication with other devices on a network, like Network Interface Cards (NICs), Modems, Routers, Switches, Bridges. Virtual devices: which are created by software for specific purposes like Virtual COM Port. By default, containers do not have access to any of the host devices. If you want to limit access to a specific device or few devices you can use the --device flag. It allows you to specify one or more devices that will be accessible within the container. $ docker run --device=/dev/snd:/dev/snd ... By default, the container will be able to read, write, and mknod these devices. But, this can be overridden using a third :rwm set of options to each --device flag: $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc $ docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk /dev/xvdc --&gt; You will not be able to write the partition table. $ docker run --device=/dev/sda:/dev/xvdc:w --rm -it ubuntu fdisk /dev/xvdc --&gt; crash.... $ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk /dev/xvdc --&gt; fdisk: unable to open /dev/xvdc: Operation not permitted Linux Capabilities: Linux capabilities are a powerful feature that provides fine-grained access control over system resources to processes without granting them full root privileges. Capabilities can be used to restrict or enhance the access rights of a process to a specific set of resources, such as the ability to bind to privileged ports, modify system time, or read and write to system files. Each capability is a bit that can be set or cleared to indicate whether the corresponding privilege is allowed or not for a process. By default, a process has a set of basic capabilities, but additional capabilities can be added or removed using the setcap and getcap utilities. Capabilities are widely used in modern Linux systems to improve security, reduce the attack surface, and enforce the principle of least privilege. For a full list of Linux Capabilities and their details refer to below Linux man page: capabilities(7) — Linux manual page Default Linux Capabilities included with Docker Containers Instead of providing priviliged access to containers, with --privileged flag, the users can have fine grain control over the capabilities using --cap-add and --cap-drop flags. Docker keeps following Linux capability options allowed by default and but these can be dropped, if required: Capability Key Capability Description AUDIT_WRITE Write records to kernel auditing log. CHOWN Make arbitrary changes to file UIDs and GIDs (see chown(2)). DAC_OVERRIDE Bypass file read, write, and execute permission checks. FOWNER Bypass permission checks on operations that normally require the file system UID of the process to match the UID of the file. FSETID Don’t clear set-user-ID and set-group-ID permission bits when a file is modified. KILL Bypass permission checks for sending signals. MKNOD Create special files using mknod(2). NET_BIND_SERVICE Bind a socket to internet domain privileged ports (port numbers less than 1024). NET_RAW Use RAW and PACKET sockets. SETFCAP Set file capabilities. SETGID Make arbitrary manipulations of process GIDs and supplementary GID list. SETPCAP Modify process capabilities. SETUID Make arbitrary manipulations of process UIDs. SYS_CHROOT Use chroot(2), change root directory. Providing additional capabilities to containers As an eample, for interacting with the network stack, instead of using --privileged one should use --cap-add=NET_ADMIN to modify the network interfaces. $ docker run -it --rm ubuntu:22.04 ifconfig --&gt; Allowed $ docker run -it --rm ubuntu:22.04 ifconfig lan2 down --&gt; SIOCSIFFLAGS: Operation not permitted $ docker run -it --rm --cap-add=NET_ADMIN ubuntu:22.04 ifconfig lan2 down --&gt; Allowed Both --cap-add &amp; --cap-drop flags support the value ALL, so to allow a container to use all capabilities except for MKNOD: docker run --cap-add=ALL --cap-drop=MKNOD ... The --cap-add and --cap-drop flags accept capabilities to be specified with a CAP_ prefix. The following examples are therefore equivalent: docker run --cap-add=SYS_ADMIN ... docker run --cap-add=CAP_SYS_ADMIN ... Following are the capabilities which are not granted by default and may be added with --cap-add and can be dropped with --cap-drop options. Capability Key Capability Description AUDIT_CONTROL Enable and disable kernel auditing; change auditing filter rules; retrieve auditing status and filtering rules. AUDIT_READ Allow reading the audit log via multicast netlink socket. BLOCK_SUSPEND Allow preventing system suspends. BPF Allow creating BPF maps, loading BPF Type Format (BTF) data, retrieve JITed code of BPF programs, and more. CHECKPOINT_RESTORE Allow checkpoint/restore related operations. Introduced in kernel 5.9. DAC_READ_SEARCH Bypass file read permission checks and directory read and execute permission checks. IPC_LOCK Lock memory (mlock(2), mlockall(2), mmap(2), shmctl(2)). IPC_OWNER Bypass permission checks for operations on System V IPC objects. LEASE Establish leases on arbitrary files (see fcntl(2)). LINUX_IMMUTABLE Set the FS_APPEND_FL and FS_IMMUTABLE_FL i-node flags. MAC_ADMIN Allow MAC configuration or state changes. Implemented for the Smack LSM. MAC_OVERRIDE Override Mandatory Access Control (MAC). Implemented for the Smack Linux Security Module (LSM). NET_ADMIN Perform various network-related operations. NET_BROADCAST Make socket broadcasts, and listen to multicasts. PERFMON Allow system performance and observability privileged operations using perf_events, i915_perf and other kernel subsystems SYS_ADMIN Perform a range of system administration operations. SYS_BOOT Use reboot(2) and kexec_load(2), reboot and load a new kernel for later execution. SYS_MODULE Load and unload kernel modules. SYS_NICE Raise process nice value (nice(2), setpriority(2)) and change the nice value for arbitrary processes. SYS_PACCT Use acct(2), switch process accounting on or off. SYS_PTRACE Trace arbitrary processes using ptrace(2). SYS_RAWIO Perform I/O port operations (iopl(2) and ioperm(2)). SYS_RESOURCE Override resource Limits. SYS_TIME Set system clock (settimeofday(2), stime(2), adjtimex(2)); set real-time (hardware) clock. SYS_TTY_CONFIG Use vhangup(2); employ various privileged ioctl(2) operations on virtual terminals. SYSLOG Perform privileged syslog(2) operations. WAKE_ALARM Trigger something that will wake up the system. Mounting FUSE based file systems to Docker containers: What are the FUSE based filesystems? FUSE (Filesystem in Userspace) is a software interface that allows non-privileged users to create their own file systems without requiring any kernel-level programming. FUSE-based file systems are file systems that are implemented using the FUSE interface. FUSE-based file systems operate in userspace, which means that they run as ordinary user-level programs and do not require any special privileges or access to kernel resources. This makes it easy for developers to create new file systems and experiment with new ideas, without having to worry about the complexities of kernel-level programming. FUSE-based file systems can provide a wide range of functionality, including virtual file systems, network file systems, encrypted file systems, and many others. They are used in a variety of applications, including cloud storage, backup and recovery, and distributed file systems. There are many FUSE-based file systems available, here are a few examples: NTFS-3G: A popular FUSE-based file system that provides read and write access to NTFS partitions on Linux. sshfs: A FUSE-based file system that allows you to mount a remote file system over SSH. encfs: A FUSE-based file system that provides an encrypted virtual file system. curlftpfs: A FUSE-based file system that allows you to mount an FTP server as a local file system.   To mount a FUSE based filesystem, you need to combine both --cap-add and --device. $ docker run --rm -it --cap-add SYS_ADMIN sshfs sshfs sven@10.10.10.20:/home/sven /mnt --&gt; fuse: failed to open /dev/fuse: Operation not permitted $ docker run --rm -it --device /dev/fuse sshfs sshfs sven@10.10.10.20:/home/sven /mnt --&gt; fusermount: mount failed: Operation not permitted $ docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse sshfs # sshfs sven@10.10.10.20:/home/sven /mnt The authenticity of host '10.10.10.20 (10.10.10.20)' can't be established. ECDSA key fingerprint is 25:34:85:75:25:b0:17:46:05:19:04:93:b5:dd:5f:c6. Are you sure you want to continue connecting (yes/no)? yes sven@10.10.10.20's password: # root@30aa0cfaf1b5:/# ls -la /mnt/src/docker total 1516 drwxrwxr-x 1 1000 1000 4096 Dec 4 06:08 . drwxrwxr-x 1 1000 1000 4096 Dec 4 11:46 .. -rw-rw-r-- 1 1000 1000 16 Oct 8 00:09 .dockerignore -rwxrwxr-x 1 1000 1000 464 Oct 8 00:09 .drone.yml drwxrwxr-x 1 1000 1000 4096 Dec 4 06:11 .git -rw-rw-r-- 1 1000 1000 461 Dec 4 06:08 .gitignore .... So that’s it for this topic, in this blog, we explored the use of Linux capabilities for managing runtime privileges in Docker containers. We discussed some common capabilities and how we can grant these privileged capabilities to containers, as well as the potential security risks of granting too many privileges. Managing runtime privileges and Linux capabilities is an essential part of container security in Docker. By default, Docker containers run as unprivileged, which limits their device access and prevents certain processes from running inside them. However, by understanding Linux capabilities and how to use them, it is possible to grant additional privileges to containers and enhance their functionality. Remember, managing runtime privileges and Linux capabilities is just one aspect of container security. It’s important to take a comprehensive approach to container security, including using secure images, implementing network security, and following other best practices.]]></summary></entry><entry><title type="html">Ways of managing data in Docker Containers</title><link href="https://akhileshmoghe.github.io/_post/devops/containers/docker-container-storage-volumes" rel="alternate" type="text/html" title="Ways of managing data in Docker Containers" /><published>2022-10-22T01:33:22+05:30</published><updated>2022-10-22T01:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_post/devops/containers/Docker-Container-Storage-Volumes-Mounts</id><content type="html" xml:base="https://akhileshmoghe.github.io/_post/devops/containers/docker-container-storage-volumes"><![CDATA[<p>In Microservices and container orchestrators world, all Containers are essentially <em><u>ephemeral</u></em> in nature, that means the are not suppose to last long and even if they lasted long, they are not suppose to retain or hold the data in their life cycles. Container orchestrators like <em><u>Kubernetes</u></em> replaces the crashed or exited container service with just another instance of it. Even if that’s how the containers are used, applications themselves needs to maintain it’s own state &amp; preserve some kind of application data across the life cycles of the containers either in some databases or on the host file systems. That’s where managing the data in and out-side container comes into picture.</p>

<ul>
  <li>Docker provides two options for containers to store files on the host machine, so that the data or files are persisted even after the container stops/exits: <strong><em><u>Volumes</u></em></strong>, and <strong><em><u>Bind mounts</u></em></strong>.</li>
  <li>Docker also supports containers storing <strong><em><u>files in-memory</u></em></strong> on the host machine.
    <ul>
      <li>Such files are not persisted.</li>
      <li>If you’re running <em><u>Docker on Linux</u></em>, <strong><em><u>tmpfs mount</u></em></strong> is used to store files in the host’s system memory.</li>
      <li>If you’re running <em><u>Docker on Windows</u></em>, <strong><em><u>named pipe</u></em></strong> is used to store files in the host’s system memory.</li>
    </ul>
  </li>
</ul>

<h3 id="difference-between-volumes-bind-mounts--tmpfs-mounts"><em><u>Difference between Volumes, Bind mounts &amp; tmpfs mounts</u></em>:</h3>

<p><img src="/assets/images/devops/container/docker-types-of-mounts.png" alt="docker-types-of-mounts" class="shadow" /></p>

<h4 id="volumes"><em><u>Volumes</u></em>:</h4>
<ul>
  <li><em><u>Stored in a part of the host filesystem which is managed by Docker</u></em> (/var/lib/docker/volumes/ on Linux).</li>
  <li>A given volume <em><u>can be mounted into multiple containers simultaneously</u></em>.</li>
  <li>When no running container is using a volume, the volume is still available to Docker and is <u>not removed automatically</u>.</li>
  <li>:x: Non-Docker processes should not modify this part of the filesystem.</li>
  <li>:heavy_check_mark: <strong><em><u>Volumes are the best way to persist data in Docker</u></em></strong>.</li>
  <li>Volumes also support the use of <strong><em><u>volume drivers</u></em></strong>, which allow you to <em><u>store your data on remote hosts</u></em> or <em>cloud providers</em>, among other possibilities.</li>
  <li>Volumes work on both Linux and Windows containers.</li>
  <li><u>Use-cases</u>:
    <ul>
      <li>:heavy_check_mark: Sharing data among multiple running containers. Multiple containers can mount the same volume simultaneously, either read-write or read-only.</li>
      <li>:heavy_check_mark: When you want to store your container’s data on a remote host or a cloud provider, rather than locally.</li>
      <li>:heavy_check_mark: When you need to <em><u>back up, restore, or migrate data from one Docker host to another</u></em>. You can stop containers using the volume, then back up the volume’s directory (such as /var/lib/docker/volumes/<volume-name>).</volume-name></li>
      <li>:heavy_check_mark: When your application requires fully native file system behavior on Docker Desktop. For example, a database engine requires precise control over disk flushing to guarantee transaction durability.</li>
    </ul>
  </li>
</ul>

<h4 id="bind-mounts"><em><u>Bind mounts</u></em>:</h4>
<ul>
  <li>May be <em><u>stored anywhere on the host system</u></em>.</li>
  <li>:warning: They may even be important system files or directories.</li>
  <li>:warning: Non-Docker processes on the Docker host or a Docker container can modify them at any time.</li>
  <li>:warning: <u>cautions</u>:
    <ul>
      <li>One side effect of using bind mounts, for better or for worse, is that you <em><u>can change the host filesystem via processes running in a container</u></em>, including creating, modifying, or deleting important system files or directories. This is a powerful ability which <em><u>can have security implications</u></em>, including impacting non-Docker processes on the host system.</li>
    </ul>
  </li>
  <li><em><u>Use-cases</u></em>:
    <ul>
      <li>:heavy_check_mark: Sharing configuration files from the host machine to containers. Docker provides DNS resolution to containers by default, by mounting /etc/resolv.conf from the host machine into each container.</li>
      <li>:heavy_check_mark: Sharing source code or build artifacts between a development environment on the Docker host and a container.</li>
    </ul>
  </li>
</ul>

<h4 id="tmpfs-mounts"><em><u>tmpfs mounts</u></em>:</h4>
<ul>
  <li><em><u>Stored in the host system’s memory only</u></em>, and are never written to the host system’s filesystem.</li>
  <li>It can be <em><u>used by</u></em> a container <em><u>during the lifetime of the container</u></em>, to <u>store non-persistent state or sensitive information</u>.
    <ul>
      <li>When the container stops, the tmpfs mount is removed, and files written there won’t be persisted.</li>
    </ul>
  </li>
  <li>For instance, internally, swarm services use tmpfs mounts to mount secrets into a service’s containers.</li>
  <li><strong><em><u>Limitations of tmpfs mounts</u></em></strong>:
    <ul>
      <li>Unlike volumes and bind mounts, you <em><u>can’t share tmpfs mounts between containers</u></em>.</li>
      <li>This functionality is <em><u>only available</u></em> if you’re running <em><u>Docker on Linux</u></em>.</li>
    </ul>
  </li>
  <li><em><u>Use-cases</u></em>:
    <ul>
      <li>:heavy_check_mark: When you do not want the data to persist either on the host machine or within the container. This may be for security reasons or to protect the performance of the container when your application needs to write a large volume of non-persistent state data.</li>
      <li>:heavy_check_mark: This is useful to temporarily store sensitive files that you don’t want to persist in either the host or the container writable layer.</li>
    </ul>
  </li>
  <li><em><u>Use a tmpfs mount in a container</u></em>:
    <ul>
      <li>To use a <strong><em><u>tmpfs mount</u></em></strong> in a container, use the <code class="language-plaintext highlighter-rouge">--tmpfs</code> flag, or use the <code class="language-plaintext highlighter-rouge">--mount</code> flag with <code class="language-plaintext highlighter-rouge">type=tmpfs</code> and <code class="language-plaintext highlighter-rouge">destination</code> options.</li>
      <li>with <code class="language-plaintext highlighter-rouge">--mount</code>:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  docker run -d -it --name &lt;container-name&gt; --mount type=tmpfs,destination=/&lt;path-in-container&gt; &lt;image&gt;:latest
</code></pre></div>        </div>
        <ul>
          <li><u>Optional Flags</u>:
            <ul>
              <li>Can only be used with <code class="language-plaintext highlighter-rouge">--mount</code>.</li>
              <li><code class="language-plaintext highlighter-rouge">tmpfs-size</code>:	Size of the tmpfs mount in bytes. Unlimited by default.</li>
              <li><code class="language-plaintext highlighter-rouge">tmpfs-mode</code>: File mode of the tmpfs in octal. For instance, <code class="language-plaintext highlighter-rouge">700</code> or <code class="language-plaintext highlighter-rouge">0770</code>. Defaults to <code class="language-plaintext highlighter-rouge">1777</code> or world-writable.<br />
 </li>
            </ul>
          </li>
        </ul>
      </li>
      <li>with <code class="language-plaintext highlighter-rouge">--tmpfs</code>:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  docker run -d -it --name &lt;container-name&gt; --tmpfs /&lt;path-in-container&gt; &lt;image&gt;:latest
</code></pre></div>        </div>
      </li>
    </ul>
  </li>
</ul>

<hr />

<h3 id="create--manage-volumes"><em><u>Create &amp; Manage Volumes</u></em>:</h3>
<ul>
  <li><u>Create a volume</u>:<br />
<code class="language-plaintext highlighter-rouge">docker volume create &lt;name-of-volume&gt;</code></li>
  <li><u>List volumes</u>:<br />
<code class="language-plaintext highlighter-rouge">docker volume ls</code></li>
  <li><u>Inspect a volume</u>:<br />
<code class="language-plaintext highlighter-rouge">docker volume inspect &lt;name-of-volume&gt;</code></li>
  <li><u>Remove a volume</u>:<br />
<code class="language-plaintext highlighter-rouge">docker volume rm &lt;name-of-volume&gt;</code></li>
</ul>

<hr />

<h3 id="--volume----mount-docker-flags-difference"><code class="language-plaintext highlighter-rouge">--volume</code> &amp; <code class="language-plaintext highlighter-rouge">--mount</code> <em><u>Docker flags difference</u></em>:</h3>
<ul>
  <li><code class="language-plaintext highlighter-rouge">--mount</code> is more explicit and verbose. <code class="language-plaintext highlighter-rouge">-v</code> syntax combines all the options together in one field, while the <code class="language-plaintext highlighter-rouge">--mount</code> syntax separates them.</li>
  <li>:pencil: <em><u>If you need to specify</u></em> <strong><em><u>volume driver</u></em></strong> <em><u>options, you must use</u></em> <code class="language-plaintext highlighter-rouge">--mount</code>.</li>
  <li>:pencil: When using <strong><em><u>volumes with services</u></em></strong>, only <code class="language-plaintext highlighter-rouge">--mount</code> is supported.</li>
  <li><code class="language-plaintext highlighter-rouge">--mount</code> consists of multiple key-value pairs, separated by commas and each consisting of a <code class="language-plaintext highlighter-rouge">&lt;key&gt;=&lt;value&gt;</code> tuple.
    <ul>
      <li><code class="language-plaintext highlighter-rouge">type</code>: Can be <code class="language-plaintext highlighter-rouge">bind</code>, <code class="language-plaintext highlighter-rouge">volume</code>, or <code class="language-plaintext highlighter-rouge">tmpfs</code>.</li>
      <li><code class="language-plaintext highlighter-rouge">source</code> or <code class="language-plaintext highlighter-rouge">src</code>: For named volumes, this is the name of the volume. For anonymous volumes, this field is omitted.</li>
      <li><code class="language-plaintext highlighter-rouge">destination</code> or <code class="language-plaintext highlighter-rouge">dst</code> or <code class="language-plaintext highlighter-rouge">target</code>: Takes as its value the path where the file or directory is mounted in the container.</li>
      <li><code class="language-plaintext highlighter-rouge">readonly</code> or <code class="language-plaintext highlighter-rouge">ro</code>: If present, causes the bind mount to be mounted into the container as read-only.
        <ul>
          <li>At other times, the container only needs read access to the data. Remember that multiple containers can mount the same volume, and it can be mounted read-write for some of them and read-only for others, at the same time.</li>
          <li>by default, <code class="language-plaintext highlighter-rouge">rw</code>.</li>
        </ul>
      </li>
      <li><code class="language-plaintext highlighter-rouge">volume-opt</code>: Can be specified more than once, takes a key-value pair consisting of the option name and its value.</li>
    </ul>
  </li>
  <li><em><u>Examples</u></em>: <em><u>Create volume while Starting the container</u></em>
    <ul>
      <li>with <code class="language-plaintext highlighter-rouge">--mount</code>:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  $ docker run -d --name &lt;container-name&gt; --mount source=&lt;volume-name&gt;,target=/&lt;destination-path-in-container&gt; &lt;image&gt;:latest
</code></pre></div>        </div>
      </li>
      <li>with <code class="language-plaintext highlighter-rouge">--volume</code>:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  $ docker run -d --name &lt;container-name&gt; -v &lt;volume-name&gt;:/&lt;destination-path-in-container&gt; &lt;image&gt;:latest
</code></pre></div>        </div>
      </li>
      <li>Clean up the containers and volumes:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  $ docker container stop devtest
  $ docker container rm devtest
  $ docker volume rm myvol2
</code></pre></div>        </div>
      </li>
    </ul>
  </li>
</ul>

<hr />

<h3 id="using-volume-with-docker-compose"><em><u>Using volume with Docker Compose</u></em>:</h3>
<ul>
  <li>Using Docker Compose service with a volume:</li>
  <li>On the first invocation of docker-compose up the volume will be created. The same volume will be reused on following invocations.
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>services:
frontend:
  image: node:lts
  volumes:
    - myapp:/home/node/app
volumes:
myapp:
</code></pre></div>    </div>
  </li>
  <li>Referencing the already created volume inside docker-compose.yml as follows:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>services:
frontend:
  image: node:lts
  volumes:
    - myapp:/home/node/app
volumes:
myapp:
  external: true
</code></pre></div>    </div>
  </li>
  <li>Use a <code class="language-plaintext highlighter-rouge">bind mount</code> with Docker Compose:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>version: "3.9"
services:
frontend:
  image: node:lts
  volumes:
    - type: bind
      source: ./static
      target: /opt/app/static
volumes:
myapp:
</code></pre></div>    </div>
  </li>
</ul>

<hr />

<h3 id="volume-drivers-to-share-data-among-machines-or-cloud-providers"><em><u>Volume drivers to share data among machines or cloud providers</u></em>:</h3>
<ul>
  <li>When building fault-tolerant applications, you might need to configure multiple replicas of the same service to have access to the same files.</li>
  <li>There are several ways to achieve this when developing your applications. One is to add logic to your application to store files on a cloud object storage system like Amazon S3. Another is to create volumes with a driver that supports writing files to an external storage system like NFS or Amazon S3.</li>
  <li>Volume drivers allow you to abstract the underlying storage system from the application logic. For example, if your services use a volume with an NFS driver, you can update the services to use a different driver, as an example to store data in the cloud, without changing the application logic.</li>
  <li><u>Further Reading</u>:
    <ul>
      <li><a href="https://docs.docker.com/storage/volumes/#use-a-volume-driver">Use a volume driver</a></li>
    </ul>
  </li>
</ul>

<hr />

<h6 id="references">References:</h6>
<ul>
  <li><a href="https://stackoverflow.com/questions/63177219/docker-how-to-access-files-from-another-container-from-a-given-container">Docker: How to access files from another container from a given container?</a></li>
  <li><a href="https://docs.docker.com/storage/volumes/">Docker Volumes</a></li>
</ul>

<hr />]]></content><author><name>Akhilesh Moghe</name></author><category term="Containers" /><category term="Docker" /><category term="Containers" /><category term="Docker" /><summary type="html"><![CDATA[In Microservices and container orchestrators world, all Containers are essentially ephemeral in nature, that means the are not suppose to last long and even if they lasted long, they are not suppose to retain or hold the data in their life cycles. Container orchestrators like Kubernetes replaces the crashed or exited container service with just another instance of it. Even if that’s how the containers are used, applications themselves needs to maintain it’s own state &amp; preserve some kind of application data across the life cycles of the containers either in some databases or on the host file systems. That’s where managing the data in and out-side container comes into picture. Docker provides two options for containers to store files on the host machine, so that the data or files are persisted even after the container stops/exits: Volumes, and Bind mounts. Docker also supports containers storing files in-memory on the host machine. Such files are not persisted. If you’re running Docker on Linux, tmpfs mount is used to store files in the host’s system memory. If you’re running Docker on Windows, named pipe is used to store files in the host’s system memory. Difference between Volumes, Bind mounts &amp; tmpfs mounts: Volumes: Stored in a part of the host filesystem which is managed by Docker (/var/lib/docker/volumes/ on Linux). A given volume can be mounted into multiple containers simultaneously. When no running container is using a volume, the volume is still available to Docker and is not removed automatically. :x: Non-Docker processes should not modify this part of the filesystem. :heavy_check_mark: Volumes are the best way to persist data in Docker. Volumes also support the use of volume drivers, which allow you to store your data on remote hosts or cloud providers, among other possibilities. Volumes work on both Linux and Windows containers. Use-cases: :heavy_check_mark: Sharing data among multiple running containers. Multiple containers can mount the same volume simultaneously, either read-write or read-only. :heavy_check_mark: When you want to store your container’s data on a remote host or a cloud provider, rather than locally. :heavy_check_mark: When you need to back up, restore, or migrate data from one Docker host to another. You can stop containers using the volume, then back up the volume’s directory (such as /var/lib/docker/volumes/). :heavy_check_mark: When your application requires fully native file system behavior on Docker Desktop. For example, a database engine requires precise control over disk flushing to guarantee transaction durability. Bind mounts: May be stored anywhere on the host system. :warning: They may even be important system files or directories. :warning: Non-Docker processes on the Docker host or a Docker container can modify them at any time. :warning: cautions: One side effect of using bind mounts, for better or for worse, is that you can change the host filesystem via processes running in a container, including creating, modifying, or deleting important system files or directories. This is a powerful ability which can have security implications, including impacting non-Docker processes on the host system. Use-cases: :heavy_check_mark: Sharing configuration files from the host machine to containers. Docker provides DNS resolution to containers by default, by mounting /etc/resolv.conf from the host machine into each container. :heavy_check_mark: Sharing source code or build artifacts between a development environment on the Docker host and a container. tmpfs mounts: Stored in the host system’s memory only, and are never written to the host system’s filesystem. It can be used by a container during the lifetime of the container, to store non-persistent state or sensitive information. When the container stops, the tmpfs mount is removed, and files written there won’t be persisted. For instance, internally, swarm services use tmpfs mounts to mount secrets into a service’s containers. Limitations of tmpfs mounts: Unlike volumes and bind mounts, you can’t share tmpfs mounts between containers. This functionality is only available if you’re running Docker on Linux. Use-cases: :heavy_check_mark: When you do not want the data to persist either on the host machine or within the container. This may be for security reasons or to protect the performance of the container when your application needs to write a large volume of non-persistent state data. :heavy_check_mark: This is useful to temporarily store sensitive files that you don’t want to persist in either the host or the container writable layer. Use a tmpfs mount in a container: To use a tmpfs mount in a container, use the --tmpfs flag, or use the --mount flag with type=tmpfs and destination options. with --mount: docker run -d -it --name &lt;container-name&gt; --mount type=tmpfs,destination=/&lt;path-in-container&gt; &lt;image&gt;:latest Optional Flags: Can only be used with --mount. tmpfs-size: Size of the tmpfs mount in bytes. Unlimited by default. tmpfs-mode: File mode of the tmpfs in octal. For instance, 700 or 0770. Defaults to 1777 or world-writable.   with --tmpfs: docker run -d -it --name &lt;container-name&gt; --tmpfs /&lt;path-in-container&gt; &lt;image&gt;:latest Create &amp; Manage Volumes: Create a volume: docker volume create &lt;name-of-volume&gt; List volumes: docker volume ls Inspect a volume: docker volume inspect &lt;name-of-volume&gt; Remove a volume: docker volume rm &lt;name-of-volume&gt; --volume &amp; --mount Docker flags difference: --mount is more explicit and verbose. -v syntax combines all the options together in one field, while the --mount syntax separates them. :pencil: If you need to specify volume driver options, you must use --mount. :pencil: When using volumes with services, only --mount is supported. --mount consists of multiple key-value pairs, separated by commas and each consisting of a &lt;key&gt;=&lt;value&gt; tuple. type: Can be bind, volume, or tmpfs. source or src: For named volumes, this is the name of the volume. For anonymous volumes, this field is omitted. destination or dst or target: Takes as its value the path where the file or directory is mounted in the container. readonly or ro: If present, causes the bind mount to be mounted into the container as read-only. At other times, the container only needs read access to the data. Remember that multiple containers can mount the same volume, and it can be mounted read-write for some of them and read-only for others, at the same time. by default, rw. volume-opt: Can be specified more than once, takes a key-value pair consisting of the option name and its value. Examples: Create volume while Starting the container with --mount: $ docker run -d --name &lt;container-name&gt; --mount source=&lt;volume-name&gt;,target=/&lt;destination-path-in-container&gt; &lt;image&gt;:latest with --volume: $ docker run -d --name &lt;container-name&gt; -v &lt;volume-name&gt;:/&lt;destination-path-in-container&gt; &lt;image&gt;:latest Clean up the containers and volumes: $ docker container stop devtest $ docker container rm devtest $ docker volume rm myvol2 Using volume with Docker Compose: Using Docker Compose service with a volume: On the first invocation of docker-compose up the volume will be created. The same volume will be reused on following invocations. services: frontend: image: node:lts volumes: - myapp:/home/node/app volumes: myapp: Referencing the already created volume inside docker-compose.yml as follows: services: frontend: image: node:lts volumes: - myapp:/home/node/app volumes: myapp: external: true Use a bind mount with Docker Compose: version: "3.9" services: frontend: image: node:lts volumes: - type: bind source: ./static target: /opt/app/static volumes: myapp: Volume drivers to share data among machines or cloud providers: When building fault-tolerant applications, you might need to configure multiple replicas of the same service to have access to the same files. There are several ways to achieve this when developing your applications. One is to add logic to your application to store files on a cloud object storage system like Amazon S3. Another is to create volumes with a driver that supports writing files to an external storage system like NFS or Amazon S3. Volume drivers allow you to abstract the underlying storage system from the application logic. For example, if your services use a volume with an NFS driver, you can update the services to use a different driver, as an example to store data in the cloud, without changing the application logic. Further Reading: Use a volume driver References: Docker: How to access files from another container from a given container? Docker Volumes]]></summary></entry><entry><title type="html">Brief Introduction to U-Boot - the Universal Bootloader</title><link href="https://akhileshmoghe.github.io/_post/embedded/linux/bootloader/u-boot" rel="alternate" type="text/html" title="Brief Introduction to U-Boot - the Universal Bootloader" /><published>2022-07-26T01:33:22+05:30</published><updated>2022-07-26T01:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_post/embedded/linux/bootloader/u-boot-Bootloader</id><content type="html" xml:base="https://akhileshmoghe.github.io/_post/embedded/linux/bootloader/u-boot"><![CDATA[<p>In this article, we will explore U-Boot Bootloader, a commonly used bootloader in Embedded systems. Number of different Embedded boards, development kits like Raspberry Pi, NVIDIA Jetson supports &amp; actively build their boot-up, board bring up process using U-Boot.
U-Boot is Open Source under <strong><em>GPL-2.0-or-later</em></strong> License.</p>

<p>Usually, there are 6 distinct stages of boot process, each explained in brief in <a href="/_post/linux/boot_process">Linux Boot Process</a> article.
Embedded Linux boot process similar to standard Linux to much extent, but due to the variations in hardware and the board specifics like multi-stage bootloaders, it becomes somewhat different in bootloader section and pre-dominant use of <strong><em>u-Boot</em></strong> bootloader in embedded systems also needs to be addressed. To find out overview of <a href="/_post/embedded/linux/boot_process">Embedded Linux Boot Process</a> see this article.</p>

<h2 id="u-boot-reference-material">U-Boot Reference Material:</h2>
<ul>
  <li><a href="https://source.denx.de/u-boot/u-boot">U-Boot Repository</a></li>
  <li><a href="https://u-boot.readthedocs.io/en/latest/">U-Boot Documentation</a></li>
</ul>

<hr />

<h2 id="building-u-boot-for-raspberry-pi">Building U-Boot for Raspberry Pi:</h2>
<ul>
  <li>U-Boot is not an official or default bootloader for Raspberry Pi. RPi uses multi-stage booting process, we can add another stage of U-Boot to this boot process to customize the boot process as per our requirements.</li>
  <li>I have used U-Boot stage with default RPi standard boot process to support <strong><em>OTA (Over-the-Air) Update</em></strong> mechanism on RPi 4 board.</li>
  <li>U-Boot main repository itself supports multiple Raspberry Pi boards, look at the <a href="https://source.denx.de/u-boot/u-boot/-/tree/master/configs">/u-boot/configs/</a> folder.</li>
</ul>

<h3 id="checkout-u-boot-source-code"><em><u>Checkout U-Boot source code</u></em>:</h3>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git clone git://git.denx.de/u-boot.git
</code></pre></div></div>
<ul>
  <li>You can even download the particular release version from <a href="https://source.denx.de/u-boot/u-boot/-/tags">U-Boot repository Tags</a>.</li>
</ul>

<h3 id="install-the-arm-compiler-for-cross-compilation"><em><u>Install the ARM Compiler for Cross-compilation</u></em>:</h3>
<ul>
  <li>There are various ARM cross-compiler toolchains like <strong>GCC</strong>, <strong>Linaro</strong>, even Raspberry Pi itself provides a compiler in their repository: <a href="https://github.com/raspberrypi/tools">raspberrypi/tools</a>.</li>
  <li>We will use GCC toolchain available as a standard Ubuntu package as follows:</li>
  <li>for <strong>32-bit</strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo apt update
$ sudo apt install gcc-arm-linux-gnueabi
$ export CROSS_COMPILE=arm-linux-gnueabi-
</code></pre></div>    </div>
  </li>
  <li>for <strong>64-bit</strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo apt update
$ sudo apt install gcc-aarch64-linux-gnu
$ export CROSS_COMPILE=aarch64-linux-gnu-
</code></pre></div>    </div>
  </li>
  <li>Note: Every time you start a new terminal to compile U-Boot, run the export command first.</li>
</ul>

<h3 id="compile-the-u-boot-source"><em><u>Compile the U-Boot source</u></em>:</h3>

<ul>
  <li><strong><em><u>Configs and DTBs for particular to boards</u></em></strong>:</li>
  <li><strong><em><u>Important</u></em></strong>:
    <ul>
      <li><strong><em>Raspberry Pi Kernel</em></strong> depends on Device Tree Binary(DTB) to understand and work with different peripherals during the boot process.</li>
      <li>Every Raspberry Pi board and the Compute Modules comes with different DTBs and DTB Overlays.</li>
      <li>One <code class="language-plaintext highlighter-rouge">config</code> file from <code class="language-plaintext highlighter-rouge">/u-boot/configs/</code> folder corresponds to a particular DTB, as mentioned in config parameter: <code class="language-plaintext highlighter-rouge">CONFIG_DEFAULT_DEVICE_TREE</code>.</li>
      <li>By default, config files supports for Raspberry Pi development boards DTBs.</li>
      <li>:warning: While compiling, U-Boot for any Raspberry Pi Compute Modules, like CM3 or CM4, we need to modify the default DTB mentioned in the config file corresponding to particular version of Raspberry Pi to the Compute Module compatible DTB.</li>
    </ul>
  </li>
  <li>Look for different <code class="language-plaintext highlighter-rouge">config</code> files for various supported boards under <code class="language-plaintext highlighter-rouge">/u-boot/configs/</code> directory in checked-out repository.</li>
  <li>There are different <code class="language-plaintext highlighter-rouge">config</code> files for different Raspberry Pi versions and for either 32/64-bit builds. Select appropriate config file.</li>
  <li>for <strong><em>RPi 4, 32-Bit</em></strong> build:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ make rpi_4_32b_defconfig
</code></pre></div>    </div>
  </li>
  <li>for <strong><em>RPi 3, 64-Bit</em></strong> build:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ make rpi_3_defconfig
</code></pre></div>    </div>
  </li>
  <li>for <strong><em>RPI CM3, 32-Bit</em></strong> build:</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ vim /u-boot/configs/rpi_3_32b_defconfig
--&gt; Update following config parameter:
    CONFIG_DEFAULT_DEVICE_TREE=bcm2837-rpi-cm3-io3.dts

$ make rpi_3_32b_defconfig
</code></pre></div></div>
<ul>
  <li>This creates a hidden <code class="language-plaintext highlighter-rouge">.config</code> file in the <code class="language-plaintext highlighter-rouge">/u-boot/</code> folder. You can view it to observe it’s contents and modify, if necessary.</li>
  <li>:warning: But be careful, the modifications in <code class="language-plaintext highlighter-rouge">.config</code> file, will be overwritten by above commands.</li>
  <li><strong><em><u>Compile the source code</u></em></strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd /u-boot/
$ make
</code></pre></div>    </div>
    <ul>
      <li>This will create <code class="language-plaintext highlighter-rouge">u-boot</code> and <code class="language-plaintext highlighter-rouge">u-boot.bin</code> binaries in the <code class="language-plaintext highlighter-rouge">/u-boot/</code> folder.</li>
    </ul>
  </li>
</ul>

<h3 id="verify-u-boot-binaries"><em><u>Verify U-Boot Binaries</u></em>:</h3>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ file u-boot
u-boot: ELF 32-bit LSB shared object, ARM, EABI5 version 1 (SYSV), dynamically linked, with debug_info, not stripped

$ file u-boot.bin 
u-boot.bin: COM executable for DOS

</code></pre></div></div>

<h2 id="testing-u-boot-on-raspberry-pi"><em><u>Testing U-Boot on Raspberry Pi</u></em>:</h2>
<ul>
  <li>Copy the compiled <code class="language-plaintext highlighter-rouge">u-boot.bin</code> binary to the Boot Partition of the Raspberry Pi SD card.</li>
  <li>Modify Raspberry Pi boot flow to add <code class="language-plaintext highlighter-rouge">u-boot</code> bootloader stage as the last stage of normal RPi Boot process, before starting the kernel.
    <ul>
      <li>:heavy_check_mark: Add <code class="language-plaintext highlighter-rouge">kernel=u-boot.bin</code> in the <code class="language-plaintext highlighter-rouge">config.txt</code> file and save this file.</li>
      <li>With this, the <code class="language-plaintext highlighter-rouge">start.elf</code> file loads the <code class="language-plaintext highlighter-rouge">u-boot.bin</code> instead of the kernel.</li>
      <li>Now, it’s <code class="language-plaintext highlighter-rouge">u-boot</code> bootloaders responsibility to properly load the Linux Kernel + DTBs in memory and start the kernel.</li>
      <li>:warning: Back-up the original <code class="language-plaintext highlighter-rouge">config.txt</code> file, before any edits.
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mount /dev/sdb1 /mnt/tmp
$ cp u-boot.bin /mnt/tmp/
$ echo 'kernel=u-boot.bin' &gt; /mnt/tmp/config.txt
$ umount /mnt/tmp
</code></pre></div>        </div>
      </li>
    </ul>
  </li>
</ul>

<h3 id="u-boot-command-prompt"><em><u>U-Boot Command Prompt</u></em>:</h3>
<ul>
  <li>After above changes, boot the Raspberry Pi board and press any keyboard keys to halt the <code class="language-plaintext highlighter-rouge">u-boot</code> Autoboot.</li>
  <li>Before Autobooting the kernel, <code class="language-plaintext highlighter-rouge">u-boot</code> is by default configured to wait for few seconds for user interruption.</li>
  <li>If user presses any keyboard keys, during this wait period, <code class="language-plaintext highlighter-rouge">u-boot</code> presents the command prompts for user to enter the u-boot commands.</li>
</ul>

<h3 id="check-u-boot-version"><em><u>Check U-Boot version</u></em>:</h3>
<ul>
  <li>Use <code class="language-plaintext highlighter-rouge">version</code> command on the <code class="language-plaintext highlighter-rouge">u-boot</code> command prompt to get the version of the <code class="language-plaintext highlighter-rouge">u-boot</code> binary.</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;U-Boot&gt; version

</code></pre></div></div>

<h2 id="booting-the-kernel"><em><u>Booting the Kernel</u></em>:</h2>
<ul>
  <li>For kernels that need Device Tree Binaries:</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;U-Boot&gt; setenv fdtfile bcm2710-rpi-cm3.dtb
&lt;U-Boot&gt; mmc dev 0
&lt;U-Boot&gt; fatload mmc 0:1 ${kernel_addr_r} zImage
&lt;U-Boot&gt; fatload mmc 0:1 ${fdt_addr_r} ${fdtfile}
&lt;U-Boot&gt; setenv bootargs earlyprintk console=tty0 console=ttyAMA0 root=/dev/mmcblk0p2 rootfstype=ext4 rootwait noinitrd
&lt;U-Boot&gt; bootz ${kernel_addr_r} - ${fdt_addr_r}
</code></pre></div></div>
<ul>
  <li>Here, we are setting the Device Tree Binary to be used as <code class="language-plaintext highlighter-rouge">fdtfile</code> variable.</li>
  <li>We are using <strong><em>FAT</em></strong> boot partition to load the kernel <code class="language-plaintext highlighter-rouge">zImage</code> and DTB file to memory.</li>
  <li><code class="language-plaintext highlighter-rouge">kernel_addr_r</code> &amp; <code class="language-plaintext highlighter-rouge">fdt_addr_r</code> are the RAM addreses for kernel &amp; DTB file respectively.</li>
  <li>We are then setting the boot arguments with <code class="language-plaintext highlighter-rouge">bootargs</code> variable, enabling the kernel prints, output consoles, and defining the <code class="language-plaintext highlighter-rouge">root</code> device partition and it’s type.</li>
  <li>Then with <code class="language-plaintext highlighter-rouge">bootz</code> command we are starting the kernel.</li>
  <li><code class="language-plaintext highlighter-rouge">bootz</code> command needs the kernel to be in <code class="language-plaintext highlighter-rouge">zImage</code> format only.</li>
</ul>

<hr />

<h6 id="references">References:</h6>
<ul>
  <li><a href="http://www.linfo.org/bios.html">BIOS</a></li>
  <li><a href="https://en.wikipedia.org/wiki/Runlevel">Runlevels</a></li>
  <li><a href="https://www.geeksforgeeks.org/run-levels-linux/">Runlevels</a></li>
  <li><a href="https://www.freecodecamp.org/news/the-linux-booting-process-6-steps-described-in-detail/">The Linux Booting Process - 6 Steps Described in Detail</a></li>
</ul>]]></content><author><name>Akhilesh Moghe</name></author><category term="Linux" /><category term="Embedded Systems" /><category term="Bootloader" /><category term="Linux" /><category term="Embedded Systems" /><category term="Bootloader" /><summary type="html"><![CDATA[In this article, we will explore U-Boot Bootloader, a commonly used bootloader in Embedded systems. Number of different Embedded boards, development kits like Raspberry Pi, NVIDIA Jetson supports &amp; actively build their boot-up, board bring up process using U-Boot. U-Boot is Open Source under GPL-2.0-or-later License. Usually, there are 6 distinct stages of boot process, each explained in brief in Linux Boot Process article. Embedded Linux boot process similar to standard Linux to much extent, but due to the variations in hardware and the board specifics like multi-stage bootloaders, it becomes somewhat different in bootloader section and pre-dominant use of u-Boot bootloader in embedded systems also needs to be addressed. To find out overview of Embedded Linux Boot Process see this article. U-Boot Reference Material: U-Boot Repository U-Boot Documentation Building U-Boot for Raspberry Pi: U-Boot is not an official or default bootloader for Raspberry Pi. RPi uses multi-stage booting process, we can add another stage of U-Boot to this boot process to customize the boot process as per our requirements. I have used U-Boot stage with default RPi standard boot process to support OTA (Over-the-Air) Update mechanism on RPi 4 board. U-Boot main repository itself supports multiple Raspberry Pi boards, look at the /u-boot/configs/ folder. Checkout U-Boot source code: $ git clone git://git.denx.de/u-boot.git You can even download the particular release version from U-Boot repository Tags. Install the ARM Compiler for Cross-compilation: There are various ARM cross-compiler toolchains like GCC, Linaro, even Raspberry Pi itself provides a compiler in their repository: raspberrypi/tools. We will use GCC toolchain available as a standard Ubuntu package as follows: for 32-bit: $ sudo apt update $ sudo apt install gcc-arm-linux-gnueabi $ export CROSS_COMPILE=arm-linux-gnueabi- for 64-bit: $ sudo apt update $ sudo apt install gcc-aarch64-linux-gnu $ export CROSS_COMPILE=aarch64-linux-gnu- Note: Every time you start a new terminal to compile U-Boot, run the export command first. Compile the U-Boot source: Configs and DTBs for particular to boards: Important: Raspberry Pi Kernel depends on Device Tree Binary(DTB) to understand and work with different peripherals during the boot process. Every Raspberry Pi board and the Compute Modules comes with different DTBs and DTB Overlays. One config file from /u-boot/configs/ folder corresponds to a particular DTB, as mentioned in config parameter: CONFIG_DEFAULT_DEVICE_TREE. By default, config files supports for Raspberry Pi development boards DTBs. :warning: While compiling, U-Boot for any Raspberry Pi Compute Modules, like CM3 or CM4, we need to modify the default DTB mentioned in the config file corresponding to particular version of Raspberry Pi to the Compute Module compatible DTB. Look for different config files for various supported boards under /u-boot/configs/ directory in checked-out repository. There are different config files for different Raspberry Pi versions and for either 32/64-bit builds. Select appropriate config file. for RPi 4, 32-Bit build: $ make rpi_4_32b_defconfig for RPi 3, 64-Bit build: $ make rpi_3_defconfig for RPI CM3, 32-Bit build: $ vim /u-boot/configs/rpi_3_32b_defconfig --&gt; Update following config parameter: CONFIG_DEFAULT_DEVICE_TREE=bcm2837-rpi-cm3-io3.dts $ make rpi_3_32b_defconfig This creates a hidden .config file in the /u-boot/ folder. You can view it to observe it’s contents and modify, if necessary. :warning: But be careful, the modifications in .config file, will be overwritten by above commands. Compile the source code: $ cd /u-boot/ $ make This will create u-boot and u-boot.bin binaries in the /u-boot/ folder. Verify U-Boot Binaries: $ file u-boot u-boot: ELF 32-bit LSB shared object, ARM, EABI5 version 1 (SYSV), dynamically linked, with debug_info, not stripped $ file u-boot.bin u-boot.bin: COM executable for DOS Testing U-Boot on Raspberry Pi: Copy the compiled u-boot.bin binary to the Boot Partition of the Raspberry Pi SD card. Modify Raspberry Pi boot flow to add u-boot bootloader stage as the last stage of normal RPi Boot process, before starting the kernel. :heavy_check_mark: Add kernel=u-boot.bin in the config.txt file and save this file. With this, the start.elf file loads the u-boot.bin instead of the kernel. Now, it’s u-boot bootloaders responsibility to properly load the Linux Kernel + DTBs in memory and start the kernel. :warning: Back-up the original config.txt file, before any edits. $ mount /dev/sdb1 /mnt/tmp $ cp u-boot.bin /mnt/tmp/ $ echo 'kernel=u-boot.bin' &gt; /mnt/tmp/config.txt $ umount /mnt/tmp U-Boot Command Prompt: After above changes, boot the Raspberry Pi board and press any keyboard keys to halt the u-boot Autoboot. Before Autobooting the kernel, u-boot is by default configured to wait for few seconds for user interruption. If user presses any keyboard keys, during this wait period, u-boot presents the command prompts for user to enter the u-boot commands. Check U-Boot version: Use version command on the u-boot command prompt to get the version of the u-boot binary. &lt;U-Boot&gt; version Booting the Kernel: For kernels that need Device Tree Binaries: &lt;U-Boot&gt; setenv fdtfile bcm2710-rpi-cm3.dtb &lt;U-Boot&gt; mmc dev 0 &lt;U-Boot&gt; fatload mmc 0:1 ${kernel_addr_r} zImage &lt;U-Boot&gt; fatload mmc 0:1 ${fdt_addr_r} ${fdtfile} &lt;U-Boot&gt; setenv bootargs earlyprintk console=tty0 console=ttyAMA0 root=/dev/mmcblk0p2 rootfstype=ext4 rootwait noinitrd &lt;U-Boot&gt; bootz ${kernel_addr_r} - ${fdt_addr_r} Here, we are setting the Device Tree Binary to be used as fdtfile variable. We are using FAT boot partition to load the kernel zImage and DTB file to memory. kernel_addr_r &amp; fdt_addr_r are the RAM addreses for kernel &amp; DTB file respectively. We are then setting the boot arguments with bootargs variable, enabling the kernel prints, output consoles, and defining the root device partition and it’s type. Then with bootz command we are starting the kernel. bootz command needs the kernel to be in zImage format only. References: BIOS Runlevels Runlevels The Linux Booting Process - 6 Steps Described in Detail]]></summary></entry><entry><title type="html">Securing MQTT Communication using Mosquitto MQTT Broker</title><link href="https://akhileshmoghe.github.io/_posts/iot/protocols/secure-mqtt" rel="alternate" type="text/html" title="Securing MQTT Communication using Mosquitto MQTT Broker" /><published>2022-06-30T12:33:22+05:30</published><updated>2022-06-30T12:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_posts/iot/protocols/Secure-MQTT-Communication</id><content type="html" xml:base="https://akhileshmoghe.github.io/_posts/iot/protocols/secure-mqtt"><![CDATA[<p>In this article, we will configure the <code class="language-plaintext highlighter-rouge">mosquitto</code> MQTT broker to use Username-Password and TLS/SSL security mechanisms. We will be using <code class="language-plaintext highlighter-rouge">openssl</code> to create our own Self-Signed Certificate authority (CA), Server keys and certificates. You can refer <a href="/_posts/security/tls">SSL TLS Explained</a> article to learn more about SSL, Handshake mechanism, Various certificates, etc.</p>

<h2 id="unsecured-unauthenticated-mqtt-communication"><em><u>Unsecured-Unauthenticated MQTT Communication</u></em></h2>
<ul>
  <li><strong><em><u>Mosquitto Broker Configurations</u></em></strong>:
    <ul>
      <li>Settings:
        <ul>
          <li><code class="language-plaintext highlighter-rouge">listener 8883</code></li>
          <li><code class="language-plaintext highlighter-rouge">listener 1883</code></li>
          <li><code class="language-plaintext highlighter-rouge">allow_anonymous true</code></li>
        </ul>
      </li>
      <li><strong><em><u>listener</u></em></strong>:
        <ul>
          <li>Mosquitto Broker listens on a port/ip address combination with above keyword.</li>
          <li>By using this variable multiple times, mosquitto can listen on more than one port.</li>
          <li>The <strong><em><u>port</u></em></strong><em><u> number to listen on must be given</u></em>. Optionally, an <strong><em>ip address</em></strong> or <strong><em>host</em></strong> name may be supplied as a second, optional argument.
            <ul>
              <li>Port number is mandatory, but not IP.</li>
            </ul>
          </li>
          <li><code class="language-plaintext highlighter-rouge">listener</code> by default listen on all network interfaces, but can also have IP address, or Hostname, or Unix Socket path, which can be used to restrict the broker access to specific interface and network.</li>
          <li>Only one listener should be sufficient.</li>
          <li>But, I faced issues to operate <code class="language-plaintext highlighter-rouge">mosquitto_sub</code> client on port 8883, it resulted in <code class="language-plaintext highlighter-rouge">error: Client &lt;unknown&gt; disconnected due to malformed packet</code>, but it worked fine on port 1883, for some unknown reason, so added both listeners.</li>
        </ul>
      </li>
      <li><strong><em><u>allow_anonymous</u></em></strong>:
        <ul>
          <li>Boolean value that determines whether clients that connect without providing a username are allowed to connect.</li>
          <li>Defaults to false.</li>
          <li>Setting this parameter to <code class="language-plaintext highlighter-rouge">true</code> enables the remote MQTT clients, running on other machines like CloudRail.Box to connect to Mosquitto Broker running on laptop.</li>
          <li>Without this option enabled, Mosquitto Broker can only connect to local MQTT clients, i.e. clients running on same laptop.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Run Mosquitto MQTT Broker</strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mosquitto -c mosquitto.conf -v
</code></pre></div>    </div>
  </li>
  <li><strong>Run Mosquitto Clients Receiver/Publisher</strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mosquitto_sub -t # -v
$ mosquitto_pub -m &lt;message&gt; -t /&lt;topic&gt;
</code></pre></div>    </div>

    <hr />
  </li>
</ul>

<h2 id="username-and-password-authentication-for-mosquitto-mqtt"><em><u>Username and Password Authentication for Mosquitto MQTT</u></em></h2>
<ul>
  <li>Mosquitto MQTT broker can be configured to require client authentication using a valid username and password for successful connection.</li>
  <li>The username and password combination is transmitted from the mosquitto clients to the broker in clear text format, and it is not secure in any form of encryption.(~SSL)</li>
  <li><strong><em><u>Password File</u></em></strong>:
    <ul>
      <li>Create Username and Password file:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mosquitto_passwd -c &lt;passwordfilename&gt; &lt;username&gt;
</code></pre></div>        </div>
      </li>
      <li>This command will ask you to set the password.</li>
      <li>It will not echo the characters, so be careful and remember the password.</li>
      <li>This creates a <code class="language-plaintext highlighter-rouge">passwordfile</code> which has username and encrypted password in <code class="language-plaintext highlighter-rouge">&lt;username&gt;:&lt;encrypted-password&gt;</code>.</li>
      <li>This file needs to be provided to Mosquitto Broker in its config file with parameter <code class="language-plaintext highlighter-rouge">password_file</code>.</li>
    </ul>
  </li>
  <li><strong><em><u>Mosquitto Broker Configurations</u></em></strong>:
    <ul>
      <li>Parameter Settings:
        <ul>
          <li><code class="language-plaintext highlighter-rouge">allow_anonymous false</code>
            <ul>
              <li>Set this to false, as we are implementing the basic security, access control mechanism.</li>
            </ul>
          </li>
          <li><code class="language-plaintext highlighter-rouge">password_file &lt;password_file_path&gt;</code>
            <ul>
              <li>Provide the <code class="language-plaintext highlighter-rouge">passwordfile</code> created with <code class="language-plaintext highlighter-rouge">mosquitto_passwd</code> utility with this parameter, along with its absolute/relative path.</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong>Run Mosquitto MQTT Broker</strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mosquitto -c mosquitto.conf -v
</code></pre></div>    </div>
  </li>
  <li><strong>Run Mosquitto Clients Receiver/Publisher</strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mosquitto_sub -t # -u &lt;username&gt; -P &lt;password&gt;
$ mosquitto_pub -m &lt;message&gt; -t /&lt;topic&gt;
</code></pre></div>    </div>

    <hr />
  </li>
</ul>

<h2 id="secure-mqtt-communication-with-tlsssl-certificates"><em><u>Secure MQTT Communication with TLS/SSL Certificates</u></em></h2>
<ul>
  <li>Authentication with TLS/SSL certificates is another way of authenticating &amp; securely connecting the clients to the broker.</li>
  <li>A client certificate identifies the client just like the server certificate identifies the server.</li>
  <li>Normally certificates are created and distributed to each client that connects to the server/broker that requires them.</li>
  <li>We can use certificates in combination with username and password authentication.</li>
  <li><strong><em><u>Mosquitto Broker Configurations</u></em></strong>:
    <ul>
      <li>Parameter Settings:
        <ul>
          <li><code class="language-plaintext highlighter-rouge">listener 8883</code>
            <ul>
              <li>Recommended port for MQTT over TLS is 8883, but this must be set manually.</li>
            </ul>
          </li>
          <li><code class="language-plaintext highlighter-rouge">allow_anonymous false</code></li>
          <li><code class="language-plaintext highlighter-rouge">cafile &lt;ca-certificate-file-path&gt;</code>
            <ul>
              <li>Certificate Authority certificates that will be considered trusted when checking incoming client certificates.</li>
            </ul>
          </li>
          <li><code class="language-plaintext highlighter-rouge">certfile &lt;broker-certificate-file-path&gt;</code>
            <ul>
              <li>Path to the PEM encoded server/broker certificate.</li>
            </ul>
          </li>
          <li><code class="language-plaintext highlighter-rouge">keyfile &lt;broker-private-key-file-path&gt;</code>
            <ul>
              <li>Path to the PEM encoded keyfile.</li>
            </ul>
          </li>
          <li><code class="language-plaintext highlighter-rouge">require_certificate true</code></li>
          <li><code class="language-plaintext highlighter-rouge">use_identity_as_username true</code><br />
 </li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong><em><u>OpenSSL Configuration</u></em></strong>
    <ul>
      <li>Required to create for <strong><em><u>SAN</u></em></strong> Certificates required to use <strong><em><u>Private/Public IP Addresses</u></em></strong> instead of a Domain name/URLs.</li>
      <li>Backup <code class="language-plaintext highlighter-rouge">openssl</code> configs:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cp /etc/openssl&lt;version&gt;/openssl.cnf /tmp/openssl.cnf
</code></pre></div>        </div>
      </li>
      <li>Add Private/Public IP Addresses entries to SAN extensions:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ SAN='\n[SAN]\nsubjectAltName=IP:&lt;IP-Address&gt;,IP:&lt;IP-Address&gt;'
$ 
$ echo -e "$SAN" &gt;&gt; /tmp/openssl.cnf
</code></pre></div>        </div>
      </li>
    </ul>
  </li>
</ul>

<h3 id="self-signed-ca-certificates"><em><u>Self-Signed CA Certificates</u></em>:</h3>
<ul>
  <li>Create <strong><em><u>Certificate Authority</u></em></strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl req -new -x509 -days 365 -extensions v3_ca -keyout ca.key -out ca.crt
</code></pre></div>    </div>

    <ul>
      <li><u>Sample output</u> of above command, Fill all details:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>---
Enter PEM pass phrase: &lt;password-for-ca-key&gt;
Verifying - Enter PEM pass phrase: &lt;password-for-ca-key&gt;
---
Country Name (2 letter code) [AU]:IN
State or Province Name (full name) [Some-State]:&lt;State&gt;
Locality Name (eg, city) []:&lt;City&gt;
Organization Name (eg, company) [Internet Widgits Pty Ltd]:&lt;Company-Name&gt;
Organizational Unit Name (eg, section) []:&lt;Org-Unit&gt;
Common Name (e.g. server FQDN or YOUR name) []:&lt;Website-URL&gt;
Email Address []:&lt;support-email-address&gt;
---
</code></pre></div>        </div>
      </li>
      <li>:red_circle: <strong>Important Note</strong>: <em>The</em> <strong><em>Common Name</em></strong> <em>for the CA cannot be the same as the Common Name for the client and server certificates</em>.
        <ul>
          <li><em>Probable Error</em>:
<code class="language-plaintext highlighter-rouge">OpenSSL Error[0]: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca</code></li>
        </ul>
      </li>
      <li>:pencil: Note down the <strong>PEM pass phrase</strong>, you will need this at a next stage while creating the broker &amp; client certificates.</li>
    </ul>
  </li>
  <li>Check generated CA Certificate, specifically <strong>Subject</strong> field, which reflect all information provided in above step:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl x509 -in ca.crt -text -noout
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="mqtt-brokerserver-certificate"><em><u>MQTT Broker/Server Certificate</u></em>:</h3>
<ul>
  <li>Create <strong><em>Private Key</em></strong> for Broker:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl genrsa -out broker.key 2048
</code></pre></div>    </div>
  </li>
  <li>Create a <strong><em><u>Certificate Signing Request(CSR)</u></em></strong> file from Broker key:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl req -out broker.csr -key broker.key -new -config /tmp/openssl.cnf
</code></pre></div>    </div>
  </li>
  <li><u>Sample output</u> of above command, Fill all details:</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>---
You are about to be asked to enter information that will be incorporated into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
---
Country Name (2 letter code) [AU]:IN
State or Province Name (full name) [Some-State]:&lt;State&gt;
Locality Name (eg, city) []:&lt;City&gt;
Organization Name (eg, company) [Internet Widgits Pty Ltd]:&lt;Company-Name&gt;
Organizational Unit Name (eg, section) []:&lt;Org-Unit&gt;
Common Name (e.g. server FQDN or YOUR name) []:&lt;IP Address of the MQTT Broker&gt; or localhost
Email Address []:&lt;support-email-address&gt;

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:              
An optional company name []:
---
</code></pre></div></div>
<ul>
  <li>:red_circle: <strong>Important Note</strong>: <em>The</em> <strong><em>Common Name</em></strong> <em>for the CA cannot be the same as the Common Name for the client and server certificates</em>.</li>
  <li>
    <p>:o: Optional fields: A challenge password []: &amp; An optional company name []:<br />
 </p>
  </li>
  <li>Check generated MQTT Broker Certificate Signing Request:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl req -in broker.csr -text -noout
</code></pre></div>    </div>
  </li>
  <li>Create a MQTT Broker <strong><em><u>Certificate(.crt)</u></em></strong> from above CSR Request:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl x509 -req -in broker.csr -CA ../ca/ca.crt -CAkey ../ca/ca.key -CAcreateserial -out broker.crt -days 365 -extensions SAN -extfile ../openssl.cnf
</code></pre></div>    </div>
    <ul>
      <li>:red_circle: <strong>Important Note</strong>: You need to provide <strong><em>PEM pass phrase</em></strong> used in CA certificate creation hereby.<br />
 </li>
    </ul>
  </li>
  <li><u>Sample output</u>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Certificate request self-signature ok
subject=C = IN, ST = Maharashtra, L = Pune, O = CloudRail, OU = IoT, CN = 10.149.0.30, emailAddress = contact@cloudrail.com
Enter pass phrase for ../ca/ca.key:
</code></pre></div>    </div>
  </li>
  <li>Check generated MQTT Broker Certificate, specifically <strong>Subject</strong> &amp; <strong>SAN</strong> fields, which reflect all information provided in above step:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl x509 -in broker.crt -text -noout
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="mqtt-client-certificate"><em><u>MQTT Client Certificate</u></em>:</h3>
<ul>
  <li>Create <strong><em>Private Key</em></strong> for Client:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl genrsa -out client.key 2048
</code></pre></div>    </div>
  </li>
  <li>Create a <strong><em><u>Certificate Signing Request(CSR)</u></em></strong> file from Client key:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl req -out client.csr -key client.key -new -config /tmp/openssl.cnf
</code></pre></div>    </div>
  </li>
  <li><u>Sample output</u> of above command, Fill all details:</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>---
You are about to be asked to enter information that will be incorporated into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
---
Country Name (2 letter code) [AU]:IN
State or Province Name (full name) [Some-State]:&lt;State&gt;
Locality Name (eg, city) []:&lt;City&gt;
Organization Name (eg, company) [Internet Widgits Pty Ltd]:&lt;Company-Name&gt;
Organizational Unit Name (eg, section) []:&lt;Org-Unit&gt;
Common Name (e.g. server FQDN or YOUR name) []:&lt;IP Address of the MQTT Broker&gt; or localhost
Email Address []:&lt;support-email-address&gt;

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:              
An optional company name []:
---
</code></pre></div></div>
<ul>
  <li>:red_circle: <strong>Important Note</strong>: <em>The</em> <strong><em>Common Name</em></strong> <em>for the CA cannot be the same as the Common Name for the client and server certificates</em>.</li>
  <li>
    <p>:o: Optional fields: A challenge password []: &amp; An optional company name []:<br />
 </p>
  </li>
  <li>Check generated Client Certificate Signing Request:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl req -in client.csr -text -noout
</code></pre></div>    </div>
  </li>
  <li>Create a Client <strong><em><u>Certificate(.crt)</u></em></strong> from above CSR Request:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl x509 -req -in broker.csr -CA ../ca/ca.crt -CAkey ../ca/ca.key -CAcreateserial -out client.crt -days 365 -extensions SAN -extfile ../openssl.cnf
</code></pre></div>    </div>
    <ul>
      <li>:red_circle: <strong>Important Note</strong>: You need to provide <strong><em>PEM pass phrase</em></strong> used in CA certificate creation hereby.<br />
 </li>
    </ul>
  </li>
  <li><u>Sample output</u>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Certificate request self-signature ok
subject=C = IN, ST = Maharashtra, L = Pune, O = CloudRail, OU = IoT, CN = 10.149.0.30, emailAddress = contact@cloudrail.com
Enter pass phrase for ../ca/ca.key:
</code></pre></div>    </div>
  </li>
  <li>Check generated Client Certificate, specifically <strong>Subject</strong> &amp; <strong>SAN</strong> fields, which reflect all information provided in above step:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl x509 -in client.crt -text -noout
</code></pre></div>    </div>
  </li>
</ul>

<h3 id="mqtts-communication-testing"><em><u>MQTTS Communication Testing</u></em>:</h3>
<ul>
  <li><strong>Run Mosquitto MQTT Broker</strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mosquitto -c mosquitto.conf -v
</code></pre></div>    </div>
  </li>
  <li><strong>Run Mosquitto Client Receiver</strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mosquitto_sub -p &lt;1883/8883&gt; --cafile /&lt;path-to-ca-certificate&gt;/ca.crt --cert /&lt;path-to-client-certificate&gt;/client.crt --key /&lt;path-to-client-key&gt;/client.key -h &lt;IPAddress-or-localhost-or-BrokerDomainURL&gt; -t &lt;topic&gt;
</code></pre></div>    </div>
  </li>
  <li><strong>Run Mosquitto Client Publisher</strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mosquitto_pub -p &lt;1883/8883&gt; --cafile /&lt;path-to-ca-certificate&gt;/ca.crt --cert /&lt;path-to-client-certificate&gt;/client.crt --key /&lt;path-to-client-key&gt;/client.key -h &lt;IPAddress-or-localhost-or-BrokerDomainURL&gt; -m &lt;message&gt; -t &lt;topic&gt;
</code></pre></div>    </div>
  </li>
</ul>

<hr />

<h2 id="what-is-san-certificate"><em><u>What is SAN Certificate?</u></em></h2>
<ul>
  <li>A <strong><em>Subject Alternate Name</em></strong> (or SAN) certificate is a digital security certificate which allows multiple hostnames to be protected by a single certificate.</li>
  <li>A SAN certificate may also be called a <strong><em><u>Unified Communication Certificate</u></em></strong> (or UCC), a <strong><em><u>multi-domain certificate</u></em></strong>, or an <strong><em><u>Exchange certificate</u></em></strong>.</li>
  <li>SAN certificates can be used on unlimited multiple servers concurrently and can be used on unlimited IP addresses with multiple, concurrent private keys (which is great for hosting and virtual hosts).</li>
  <li>The entries in any SSL.com SAN certificate: can be a <strong><em><u>Fully Qualified Domain Name (FQDN)</u></em></strong> and can be a <strong><em><u>wildcard domain name</u></em></strong> (i.e. <em>.domain.com or </em>.store.domain.com) but NOT a multiple-level wildcard (like <em>.</em>.domain.com).</li>
  <li>:x: <em><u>CA Certificate can not be a “Subject Alternative Name (SAN)” certificate</u></em>, it results in an Error:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">OpenSSL Error[0]: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca</code>.<br />
 </li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">Error: {"message":"Device muruMsT0IhwpFZeNNPlaYxFjx11Uxikv failed to connect with err Error: Hostname/IP doesn't match certificate's altnames: \"IP: 10.149.0.30 is not in the cert's list: \"\n","timestamp":"2022-06-29T09:45:18.080Z","type":"out","process_id":9,"app_name":"main"}</code>
    <ul>
      <li><u>Reason</u>:
        <ul>
          <li>This Error appeared for me while using Self-Signed CA, Server, Client certificates with NodeJS Application, but Mosquitto MQTT clients/broker had no issues using the same self-signed certificates. Also these certificates were created for a Private IP address, and not for any domain URL, as is the usual case. I was testing the local MQTTS communication over local LAN so private IP addresses makes sense.</li>
          <li>The problem is as indicated that, a Node ‘mqtt’ module seems to need a SAN certificate for Private IP Addresses.
            <ul>
              <li>According to the CA Browser forum, there may be compatibility issues with certificates for IP addresses unless the IP address is in both the commonName and subjectAltName fields. This is due to legacy SSL implementations which are not aligned with RFC 5280, notably, Windows OS prior to Windows 10.</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<hr />

<h2 id="encountered-errors--reasons-for-them"><em>Encountered Errors &amp; Reasons for them</em>:</h2>
<ul>
  <li><code class="language-plaintext highlighter-rouge">Error: mosquitto mqtt tls certificate error Client auto-5F29B532-D3F5-7C93-EF6A-0289F5C3DAEA disconnected, not authorised.</code>
    <ul>
      <li><u>Reason</u>: Client certificates were not created and broker certificates were tried to use, so this error.<br />
 </li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">Error: OpenSSL Error: error:14094438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error</code>
    <ul>
      <li><u>Reason</u>:
        <ul>
          <li>TLS expects the connection to be directed to the same CN (Common Name) as the one used in the generation step of the client.csr request file.</li>
          <li>The CN (Common Name) should be the same as the server/broker hostname if no SAN extension is used (See What is SAN Certificate).</li>
        </ul>
      </li>
      <li>References:
        <ul>
          <li><a href="https://stackoverflow.com/a/65957636/2003556">Client using libmosquitto gets “tlsv1 alert internal error” using TLS, works fine without TLS</a></li>
          <li><a href="https://openest.io/en/services/mqtts-how-to-use-mqtt-with-tls/">MQTTS : How to use MQTT with TLS?</a><br />
 </li>
        </ul>
      </li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">Error: {“message":"Device XdtNrVk5zzZ5Fvmf8adL9R0dJeG6inkG failed to connect with err Error: write EPROTO 1996375408:error:1409441B:SSL routines:ssl3_read_bytes:tlsv1 alert decrypt error:../deps/openssl/openssl/ssl/s3_pkt.c:1498:SSL alert number 51\n1996375408:error:1409E0E5:SSL routines:ssl3_write_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:659:\n\n","timestamp":"2022-06-29T09:34:12.858Z","type":"out","process_id":9,"app_name":"main"}</code>
    <ul>
      <li><u>Reason</u>: Certificate mismatch, older certificate used.<br />
 </li>
    </ul>
  </li>
  <li><code class="language-plaintext highlighter-rouge">New connection from 10.149.0.1:59884 on port 8883.</code><br />
  <code class="language-plaintext highlighter-rouge">OpenSSL Error[0]: error:0407008A:rsa routines:RSA_padding_check_PKCS1_type_1:invalid padding</code><br />
  <code class="language-plaintext highlighter-rouge">OpenSSL Error[1]: error:04067072:rsa routines:rsa_ossl_public_decrypt:padding check failed</code><br />
  <code class="language-plaintext highlighter-rouge">OpenSSL Error[2]: error:0D0C5006:asn1 encoding routines:ASN1_item_verify:EVP lib</code><br />
  <code class="language-plaintext highlighter-rouge">OpenSSL Error[3]: error:1417C086:SSL routines:tls_process_client_certificate:certificate verify failed Client &lt;unknown&gt; disconnected: Protocol error.</code>
    <ul>
      <li><u>Reason</u>: Certificate mismatch, older certificate used.</li>
    </ul>
  </li>
</ul>

<hr />

<h6 id="references">References:</h6>
<ul>
  <li><u>SAN References</u>:
    <ul>
      <li><a href="https://stackoverflow.com/a/64186819/2003556">Is it possible to have SSL certificate for IP address, not domain name? [closed]</a></li>
      <li><a href="https://stackoverflow.com/a/37063612/2003556">Is it possible to have SSL certificate for IP address, not domain name? [closed]</a></li>
      <li><a href="https://stackoverflow.com/questions/33494750/self-signed-certificate-for-public-and-private-ip-tomcat-7">Self-Signed Certificate for Public and Private IP (Tomcat 7)</a></li>
      <li><a href="https://stackoverflow.com/a/58210221/2003556">Invalid self signed SSL cert - “Subject Alternative Name Missing”</a></li>
      <li><a href="https://github.com/mqttjs/MQTT.js/issues/663">Unable to connet a mosquitto using a private IP address and WSS #663</a></li>
    </ul>
  </li>
  <li><a href="http://www.steves-internet-guide.com/creating-and-using-client-certificates-with-mqtt-and-mosquitto/">Creating and Using Client Certificates with MQTT and Mosquitto</a></li>
  <li><a href="http://www.steves-internet-guide.com/mosquitto-tls/">Mosquitto SSL Configuration -MQTT TLS Security</a></li>
  <li><a href="http://www.steves-internet-guide.com/mossquitto-conf-file/">Quick Guide to The Mosquitto.conf File With Examples</a></li>
  <li><a href="http://www.steves-internet-guide.com/mosquitto_pub-sub-clients/">Using The Mosquitto_pub and Mosquitto_sub MQTT Client Tools- Examples</a></li>
  <li>
    <p><a href="https://openest.io/en/services/mqtts-how-to-use-mqtt-with-tls/">MQTTS : How to use MQTT with TLS?</a></p>
  </li>
  <li><u>Mosquitto Username and Password Authentication References</u>:
    <ul>
      <li><a href="http://www.steves-internet-guide.com/mqtt-username-password-example/">Mosquitto Username and Password Authentication -Configuration and Testing</a></li>
      <li><a href="https://mosquitto.org/man/mosquitto_passwd-1.html">mosquitto_passwd man page</a></li>
      <li><a href="https://mosquitto.org/documentation/authentication-methods/">Mosquitto MQTT Authentication methods</a></li>
    </ul>
  </li>
</ul>]]></content><author><name>Akhilesh Moghe</name></author><category term="IoT" /><category term="IoT Security" /><category term="MQTT" /><category term="IoT" /><category term="IoT Security" /><category term="MQTT" /><summary type="html"><![CDATA[In this article, we will configure the mosquitto MQTT broker to use Username-Password and TLS/SSL security mechanisms. We will be using openssl to create our own Self-Signed Certificate authority (CA), Server keys and certificates. You can refer SSL TLS Explained article to learn more about SSL, Handshake mechanism, Various certificates, etc. Unsecured-Unauthenticated MQTT Communication Mosquitto Broker Configurations: Settings: listener 8883 listener 1883 allow_anonymous true listener: Mosquitto Broker listens on a port/ip address combination with above keyword. By using this variable multiple times, mosquitto can listen on more than one port. The port number to listen on must be given. Optionally, an ip address or host name may be supplied as a second, optional argument. Port number is mandatory, but not IP. listener by default listen on all network interfaces, but can also have IP address, or Hostname, or Unix Socket path, which can be used to restrict the broker access to specific interface and network. Only one listener should be sufficient. But, I faced issues to operate mosquitto_sub client on port 8883, it resulted in error: Client &lt;unknown&gt; disconnected due to malformed packet, but it worked fine on port 1883, for some unknown reason, so added both listeners. allow_anonymous: Boolean value that determines whether clients that connect without providing a username are allowed to connect. Defaults to false. Setting this parameter to true enables the remote MQTT clients, running on other machines like CloudRail.Box to connect to Mosquitto Broker running on laptop. Without this option enabled, Mosquitto Broker can only connect to local MQTT clients, i.e. clients running on same laptop. Run Mosquitto MQTT Broker: $ mosquitto -c mosquitto.conf -v Run Mosquitto Clients Receiver/Publisher: $ mosquitto_sub -t # -v $ mosquitto_pub -m &lt;message&gt; -t /&lt;topic&gt; Username and Password Authentication for Mosquitto MQTT Mosquitto MQTT broker can be configured to require client authentication using a valid username and password for successful connection. The username and password combination is transmitted from the mosquitto clients to the broker in clear text format, and it is not secure in any form of encryption.(~SSL) Password File: Create Username and Password file: $ mosquitto_passwd -c &lt;passwordfilename&gt; &lt;username&gt; This command will ask you to set the password. It will not echo the characters, so be careful and remember the password. This creates a passwordfile which has username and encrypted password in &lt;username&gt;:&lt;encrypted-password&gt;. This file needs to be provided to Mosquitto Broker in its config file with parameter password_file. Mosquitto Broker Configurations: Parameter Settings: allow_anonymous false Set this to false, as we are implementing the basic security, access control mechanism. password_file &lt;password_file_path&gt; Provide the passwordfile created with mosquitto_passwd utility with this parameter, along with its absolute/relative path. Run Mosquitto MQTT Broker: $ mosquitto -c mosquitto.conf -v Run Mosquitto Clients Receiver/Publisher: $ mosquitto_sub -t # -u &lt;username&gt; -P &lt;password&gt; $ mosquitto_pub -m &lt;message&gt; -t /&lt;topic&gt; Secure MQTT Communication with TLS/SSL Certificates Authentication with TLS/SSL certificates is another way of authenticating &amp; securely connecting the clients to the broker. A client certificate identifies the client just like the server certificate identifies the server. Normally certificates are created and distributed to each client that connects to the server/broker that requires them. We can use certificates in combination with username and password authentication. Mosquitto Broker Configurations: Parameter Settings: listener 8883 Recommended port for MQTT over TLS is 8883, but this must be set manually. allow_anonymous false cafile &lt;ca-certificate-file-path&gt; Certificate Authority certificates that will be considered trusted when checking incoming client certificates. certfile &lt;broker-certificate-file-path&gt; Path to the PEM encoded server/broker certificate. keyfile &lt;broker-private-key-file-path&gt; Path to the PEM encoded keyfile. require_certificate true use_identity_as_username true   OpenSSL Configuration Required to create for SAN Certificates required to use Private/Public IP Addresses instead of a Domain name/URLs. Backup openssl configs: $ cp /etc/openssl&lt;version&gt;/openssl.cnf /tmp/openssl.cnf Add Private/Public IP Addresses entries to SAN extensions: $ SAN='\n[SAN]\nsubjectAltName=IP:&lt;IP-Address&gt;,IP:&lt;IP-Address&gt;' $ $ echo -e "$SAN" &gt;&gt; /tmp/openssl.cnf Self-Signed CA Certificates: Create Certificate Authority: $ openssl req -new -x509 -days 365 -extensions v3_ca -keyout ca.key -out ca.crt Sample output of above command, Fill all details: --- Enter PEM pass phrase: &lt;password-for-ca-key&gt; Verifying - Enter PEM pass phrase: &lt;password-for-ca-key&gt; --- Country Name (2 letter code) [AU]:IN State or Province Name (full name) [Some-State]:&lt;State&gt; Locality Name (eg, city) []:&lt;City&gt; Organization Name (eg, company) [Internet Widgits Pty Ltd]:&lt;Company-Name&gt; Organizational Unit Name (eg, section) []:&lt;Org-Unit&gt; Common Name (e.g. server FQDN or YOUR name) []:&lt;Website-URL&gt; Email Address []:&lt;support-email-address&gt; --- :red_circle: Important Note: The Common Name for the CA cannot be the same as the Common Name for the client and server certificates. Probable Error: OpenSSL Error[0]: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca :pencil: Note down the PEM pass phrase, you will need this at a next stage while creating the broker &amp; client certificates. Check generated CA Certificate, specifically Subject field, which reflect all information provided in above step: $ openssl x509 -in ca.crt -text -noout MQTT Broker/Server Certificate: Create Private Key for Broker: $ openssl genrsa -out broker.key 2048 Create a Certificate Signing Request(CSR) file from Broker key: $ openssl req -out broker.csr -key broker.key -new -config /tmp/openssl.cnf Sample output of above command, Fill all details: --- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. --- Country Name (2 letter code) [AU]:IN State or Province Name (full name) [Some-State]:&lt;State&gt; Locality Name (eg, city) []:&lt;City&gt; Organization Name (eg, company) [Internet Widgits Pty Ltd]:&lt;Company-Name&gt; Organizational Unit Name (eg, section) []:&lt;Org-Unit&gt; Common Name (e.g. server FQDN or YOUR name) []:&lt;IP Address of the MQTT Broker&gt; or localhost Email Address []:&lt;support-email-address&gt; Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: --- :red_circle: Important Note: The Common Name for the CA cannot be the same as the Common Name for the client and server certificates. :o: Optional fields: A challenge password []: &amp; An optional company name []:   Check generated MQTT Broker Certificate Signing Request: $ openssl req -in broker.csr -text -noout Create a MQTT Broker Certificate(.crt) from above CSR Request: $ openssl x509 -req -in broker.csr -CA ../ca/ca.crt -CAkey ../ca/ca.key -CAcreateserial -out broker.crt -days 365 -extensions SAN -extfile ../openssl.cnf :red_circle: Important Note: You need to provide PEM pass phrase used in CA certificate creation hereby.   Sample output: Certificate request self-signature ok subject=C = IN, ST = Maharashtra, L = Pune, O = CloudRail, OU = IoT, CN = 10.149.0.30, emailAddress = contact@cloudrail.com Enter pass phrase for ../ca/ca.key: Check generated MQTT Broker Certificate, specifically Subject &amp; SAN fields, which reflect all information provided in above step: $ openssl x509 -in broker.crt -text -noout MQTT Client Certificate: Create Private Key for Client: $ openssl genrsa -out client.key 2048 Create a Certificate Signing Request(CSR) file from Client key: $ openssl req -out client.csr -key client.key -new -config /tmp/openssl.cnf Sample output of above command, Fill all details: --- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. --- Country Name (2 letter code) [AU]:IN State or Province Name (full name) [Some-State]:&lt;State&gt; Locality Name (eg, city) []:&lt;City&gt; Organization Name (eg, company) [Internet Widgits Pty Ltd]:&lt;Company-Name&gt; Organizational Unit Name (eg, section) []:&lt;Org-Unit&gt; Common Name (e.g. server FQDN or YOUR name) []:&lt;IP Address of the MQTT Broker&gt; or localhost Email Address []:&lt;support-email-address&gt; Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: --- :red_circle: Important Note: The Common Name for the CA cannot be the same as the Common Name for the client and server certificates. :o: Optional fields: A challenge password []: &amp; An optional company name []:   Check generated Client Certificate Signing Request: $ openssl req -in client.csr -text -noout Create a Client Certificate(.crt) from above CSR Request: $ openssl x509 -req -in broker.csr -CA ../ca/ca.crt -CAkey ../ca/ca.key -CAcreateserial -out client.crt -days 365 -extensions SAN -extfile ../openssl.cnf :red_circle: Important Note: You need to provide PEM pass phrase used in CA certificate creation hereby.   Sample output: Certificate request self-signature ok subject=C = IN, ST = Maharashtra, L = Pune, O = CloudRail, OU = IoT, CN = 10.149.0.30, emailAddress = contact@cloudrail.com Enter pass phrase for ../ca/ca.key: Check generated Client Certificate, specifically Subject &amp; SAN fields, which reflect all information provided in above step: $ openssl x509 -in client.crt -text -noout MQTTS Communication Testing: Run Mosquitto MQTT Broker: $ mosquitto -c mosquitto.conf -v Run Mosquitto Client Receiver: $ mosquitto_sub -p &lt;1883/8883&gt; --cafile /&lt;path-to-ca-certificate&gt;/ca.crt --cert /&lt;path-to-client-certificate&gt;/client.crt --key /&lt;path-to-client-key&gt;/client.key -h &lt;IPAddress-or-localhost-or-BrokerDomainURL&gt; -t &lt;topic&gt; Run Mosquitto Client Publisher: $ mosquitto_pub -p &lt;1883/8883&gt; --cafile /&lt;path-to-ca-certificate&gt;/ca.crt --cert /&lt;path-to-client-certificate&gt;/client.crt --key /&lt;path-to-client-key&gt;/client.key -h &lt;IPAddress-or-localhost-or-BrokerDomainURL&gt; -m &lt;message&gt; -t &lt;topic&gt; What is SAN Certificate? A Subject Alternate Name (or SAN) certificate is a digital security certificate which allows multiple hostnames to be protected by a single certificate. A SAN certificate may also be called a Unified Communication Certificate (or UCC), a multi-domain certificate, or an Exchange certificate. SAN certificates can be used on unlimited multiple servers concurrently and can be used on unlimited IP addresses with multiple, concurrent private keys (which is great for hosting and virtual hosts). The entries in any SSL.com SAN certificate: can be a Fully Qualified Domain Name (FQDN) and can be a wildcard domain name (i.e. .domain.com or .store.domain.com) but NOT a multiple-level wildcard (like ..domain.com). :x: CA Certificate can not be a “Subject Alternative Name (SAN)” certificate, it results in an Error: OpenSSL Error[0]: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca.   Error: {"message":"Device muruMsT0IhwpFZeNNPlaYxFjx11Uxikv failed to connect with err Error: Hostname/IP doesn't match certificate's altnames: \"IP: 10.149.0.30 is not in the cert's list: \"\n","timestamp":"2022-06-29T09:45:18.080Z","type":"out","process_id":9,"app_name":"main"} Reason: This Error appeared for me while using Self-Signed CA, Server, Client certificates with NodeJS Application, but Mosquitto MQTT clients/broker had no issues using the same self-signed certificates. Also these certificates were created for a Private IP address, and not for any domain URL, as is the usual case. I was testing the local MQTTS communication over local LAN so private IP addresses makes sense. The problem is as indicated that, a Node ‘mqtt’ module seems to need a SAN certificate for Private IP Addresses. According to the CA Browser forum, there may be compatibility issues with certificates for IP addresses unless the IP address is in both the commonName and subjectAltName fields. This is due to legacy SSL implementations which are not aligned with RFC 5280, notably, Windows OS prior to Windows 10. Encountered Errors &amp; Reasons for them: Error: mosquitto mqtt tls certificate error Client auto-5F29B532-D3F5-7C93-EF6A-0289F5C3DAEA disconnected, not authorised. Reason: Client certificates were not created and broker certificates were tried to use, so this error.   Error: OpenSSL Error: error:14094438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error Reason: TLS expects the connection to be directed to the same CN (Common Name) as the one used in the generation step of the client.csr request file. The CN (Common Name) should be the same as the server/broker hostname if no SAN extension is used (See What is SAN Certificate). References: Client using libmosquitto gets “tlsv1 alert internal error” using TLS, works fine without TLS MQTTS : How to use MQTT with TLS?   Error: {“message":"Device XdtNrVk5zzZ5Fvmf8adL9R0dJeG6inkG failed to connect with err Error: write EPROTO 1996375408:error:1409441B:SSL routines:ssl3_read_bytes:tlsv1 alert decrypt error:../deps/openssl/openssl/ssl/s3_pkt.c:1498:SSL alert number 51\n1996375408:error:1409E0E5:SSL routines:ssl3_write_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:659:\n\n","timestamp":"2022-06-29T09:34:12.858Z","type":"out","process_id":9,"app_name":"main"} Reason: Certificate mismatch, older certificate used.   New connection from 10.149.0.1:59884 on port 8883. OpenSSL Error[0]: error:0407008A:rsa routines:RSA_padding_check_PKCS1_type_1:invalid padding OpenSSL Error[1]: error:04067072:rsa routines:rsa_ossl_public_decrypt:padding check failed OpenSSL Error[2]: error:0D0C5006:asn1 encoding routines:ASN1_item_verify:EVP lib OpenSSL Error[3]: error:1417C086:SSL routines:tls_process_client_certificate:certificate verify failed Client &lt;unknown&gt; disconnected: Protocol error. Reason: Certificate mismatch, older certificate used. References: SAN References: Is it possible to have SSL certificate for IP address, not domain name? [closed] Is it possible to have SSL certificate for IP address, not domain name? [closed] Self-Signed Certificate for Public and Private IP (Tomcat 7) Invalid self signed SSL cert - “Subject Alternative Name Missing” Unable to connet a mosquitto using a private IP address and WSS #663 Creating and Using Client Certificates with MQTT and Mosquitto Mosquitto SSL Configuration -MQTT TLS Security Quick Guide to The Mosquitto.conf File With Examples Using The Mosquitto_pub and Mosquitto_sub MQTT Client Tools- Examples MQTTS : How to use MQTT with TLS? Mosquitto Username and Password Authentication References: Mosquitto Username and Password Authentication -Configuration and Testing mosquitto_passwd man page Mosquitto MQTT Authentication methods]]></summary></entry><entry><title type="html">Complete tutorial to create a Debian Minimal RootFS</title><link href="https://akhileshmoghe.github.io/_post/linux/debian_minimal_rootfs" rel="alternate" type="text/html" title="Complete tutorial to create a Debian Minimal RootFS" /><published>2022-06-14T01:33:22+05:30</published><updated>2022-06-14T01:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_post/linux/Debian-Minimal-RootFS</id><content type="html" xml:base="https://akhileshmoghe.github.io/_post/linux/debian_minimal_rootfs"><![CDATA[<p>This article is about creation of minimal <strong><em><u>rootfs</u></em></strong> which will be the base file system to be mounted on <code class="language-plaintext highlighter-rouge">/</code> rootfs partition any Embedded board like Raspberry Pi, NVIDIA Jetson Nano/TX2 once the kernel is loaded in memory by the boot loader. We will also install few linux packages like <code class="language-plaintext highlighter-rouge">ssh</code>, <code class="language-plaintext highlighter-rouge">nodeJS</code>, which forms part of pre-installed packages on our customize <code class="language-plaintext highlighter-rouge">rootfs</code>.<br />
All steps below should work on any Debian/Ubuntu host and I have verified them with Ubuntu 18.04 LTS.</p>

<h2 id="install-support-packages-on-host">Install support packages on host:</h2>
<ul>
  <li>Get apt sources updated:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo apt update
</code></pre></div>    </div>

    <h3 id="qemu-user-static"><em><u>qemu-user-static</u></em></h3>
    <ul>
      <li>QEMU user mode emulation binaries (static version)</li>
      <li>QEMU is a fast processor emulator: By using dynamic translation it achieves reasonable speed while being easy to port on new host CPUs.</li>
      <li>currently the package supports <code class="language-plaintext highlighter-rouge">ARM</code>, <code class="language-plaintext highlighter-rouge">CRIS</code>, <code class="language-plaintext highlighter-rouge">i386</code>, <code class="language-plaintext highlighter-rouge">M68k</code> (ColdFire), <code class="language-plaintext highlighter-rouge">MicroBlaze</code>, <code class="language-plaintext highlighter-rouge">MIPS</code>, <code class="language-plaintext highlighter-rouge">PowerPC</code>, <code class="language-plaintext highlighter-rouge">SH4</code>, <code class="language-plaintext highlighter-rouge">SPARC</code> and <code class="language-plaintext highlighter-rouge">x86-64</code> emulation.</li>
      <li>This <code class="language-plaintext highlighter-rouge">qemu-user-static</code> package provides the <em><u>user mode emulation binaries</u></em>, built statically.</li>
      <li>In this mode QEMU can <em><u>launch Linux processes compiled for one CPU on another CPU</u></em>.</li>
      <li><code class="language-plaintext highlighter-rouge">qemu-user-static</code> package will <em><u>register binary formats</u></em> which the provided emulators can handle, so that it will be possible to <em><u>run foreign binaries directly</u></em>.</li>
      <li><em>Other few QEMU packages (mentioned here just for info, not required for the task at hand)</em>:
        <ul>
          <li><strong><em><u>qemu</u></em></strong>: Once upon a time there was only one package named <code class="language-plaintext highlighter-rouge">qemu</code>, with all functionality included. These days, qemu become large and has been split into numerous packages. Different packages provides entirely different services, and it is very unlikely one will need all of them together. So current <code class="language-plaintext highlighter-rouge">qemu</code> package makes no sense anymore, and is becoming a dummy package.</li>
          <li><strong><em><u>qemu-user</u></em></strong>: If you want user-mode emulation, install <code class="language-plaintext highlighter-rouge">qemu-user</code> or <code class="language-plaintext highlighter-rouge">qemu-user-static</code> package.</li>
          <li><strong><em><u>qemu-utils</u></em></strong>: If you need utilities, use <code class="language-plaintext highlighter-rouge">qemu-utils</code> package.
            <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo apt install qemu-user-static
</code></pre></div>            </div>
          </li>
        </ul>
      </li>
    </ul>

    <h3 id="binfmt-support">binfmt-support</h3>
    <ul>
      <li><strong><em><u>Support for extra binary formats</u></em></strong></li>
      <li>The <code class="language-plaintext highlighter-rouge">binfmt_misc</code> kernel module allows system administrators to <em><u>register interpreters for various binary formats</u></em> based on a <em>magic number</em> or their <em>file extension</em>, and cause the <em><u>appropriate interpreter to be invoked whenever a matching file is executed</u></em>.
        <ul>
          <li>Think of it as a more flexible version of the <code class="language-plaintext highlighter-rouge">#!</code> (shebang line) executable interpreter mechanism.</li>
        </ul>
      </li>
      <li>This <code class="language-plaintext highlighter-rouge">binfmt-support</code> package provides an <code class="language-plaintext highlighter-rouge">update-binfmts</code> script with which <em><u>package maintainers can register interpreters to be used with this module</u></em> without having to worry about writing their own <code class="language-plaintext highlighter-rouge">init.d</code> scripts, and which sysadmins can use for a slightly higher-level interface to this module.
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo apt install binfmt-support
</code></pre></div>        </div>
      </li>
    </ul>

    <h3 id="debootstrap">debootstrap</h3>
    <ul>
      <li><code class="language-plaintext highlighter-rouge">debootstrap</code> is a tool which will <em><u>install a Debian base system into a subdirectory of another, already installed system</u></em>.</li>
      <li>It doesn’t require an installation CD, just access to a Debian repository (~internet).</li>
      <li>It can also be installed and run from another operating system, so, for instance, you can use <code class="language-plaintext highlighter-rouge">debootstrap</code> to <em><u>install Debian onto an unused partition from a running</u></em> <a href="https://www.gentoo.org/">Gentoo Linux</a>.</li>
      <li>It can also be used to <strong><em><u>create a rootfs</u></em></strong><em><u> for a machine of a different architecture</u></em>, which is known as <code class="language-plaintext highlighter-rouge">cross-debootstrapping</code>.</li>
      <li>:x: <code class="language-plaintext highlighter-rouge">Debootstrap</code> can <strong><em>only use one repository for its packages</em></strong>. If you need to merge packages from different repositories (the way apt does) to make a rootfs, or you need to automatically customise the rootfs, then use <a href="https://wiki.debian.org/Multistrap">Multistrap</a>.
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo apt install debootstrap
</code></pre></div>        </div>
      </li>
    </ul>

    <hr />
  </li>
</ul>

<h2 id="build-1st-stage-of-debian-rootfs">Build 1st stage of Debian RootFS</h2>
<ul>
  <li><strong><em>ARM Architecture</em></strong>:
    <ul>
      <li>I am using Raspberry Pi 4 Model B board while drafting this article, RPi4 uses <strong><em>Broadcom BCM2711</em></strong> chip which has <strong><em>ARM Cortex-A72</em></strong> CPU, which implements <strong><em>ARMv8-A</em></strong> 64-bit instruction set.</li>
      <li>I am also going to try this created RootFS on <a href="https://revolutionpi.com/revpi-connect/">Revolution Pi, RevPi Connect</a> box which uses <strong><em>Raspberry Pi Compute Module 3</em></strong> chip which has <strong><em>ARM Cortex-A53</em></strong> CPU, which also implements <strong><em>ARMv8-A</em></strong> 64-bit instruction set.</li>
      <li>So, in my opinion, the same RootFS should work on both the boards, though they have different processors, but the same instruction set and the ARM Architecture.</li>
      <li>ARMv8-A has 64-bit ARM Architecture known as <strong><em>AArch64</em></strong> or <strong><em>ARM64</em></strong>. <strong><em>Is there a difference?</em></strong>
        <ul>
          <li>AArch64 is the 64-bit state introduced in the Armv8-A architecture, The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is <strong><em>aarch64</em></strong>.</li>
          <li>The Linux kernel community chose to call their port of the kernel to this architecture <strong><em>arm64</em></strong> rather than aarch64, so that’s where some of the arm64 usage comes from.</li>
          <li><em><u>So, AArch64 is the ARM64, no difference</u></em>.</li>
        </ul>
      </li>
      <li>References:
        <ul>
          <li><a href="https://en.wikipedia.org/wiki/AArch64">Wikipedia: AArch46</a></li>
          <li><a href="https://stackoverflow.com/q/31851611/2003556">Stackoverflow: Differences between arm64 and aarch64</a></li>
          <li><a href="https://en.wikipedia.org/wiki/Raspberry_Pi#Specifications">Wikipedia: Raspberry_Pi Specifications</a></li>
          <li><a href="https://en.wikipedia.org/wiki/ARM_Cortex-A53">Wikipedia: ARM Cortex-A53</a></li>
          <li><a href="https://en.wikipedia.org/wiki/ARM_Cortex-A72">Wikipedia: ARM Cortex-A72</a></li>
          <li><a href="https://en.wikipedia.org/wiki/Comparison_of_ARMv8-A_processors">Wikipedia: Comparison of ARMv8-A processors</a></li>
          <li><a href="https://en.wikipedia.org/wiki/ARM_architecture_family#64/32-bit_architecture">Wikipedia ARM 64/32-bit Architecture</a></li>
          <li><a href="https://revolutionpi.com/revpi-connect/">Revolution Pi, RevPi Connect</a></li>
          <li><a href="https://www.raspberrypi.com/software/operating-systems/">Raspberry Pi OS (64-bit): compatible with CM3 &amp; Pi4</a></li>
          <li><a href="https://www.raspberrypi.com/documentation/computers/processors.html#bcm2711">Raspberry Pi 4 Model B: BCM2711</a></li>
          <li><a href="https://www.raspberrypi.com/documentation/computers/processors.html#bcm2837">Raspberry Pi Compute Module 3: BCM2837</a>
            <ul>
              <li>The underlying architecture of the BCM2837 is identical to the BCM2836.</li>
              <li>The only significant difference is the replacement of the ARMv7 quad core cluster with a quad-core ARM Cortex A53 (ARMv8) cluster.</li>
            </ul>
          </li>
          <li><a href="https://www.raspberrypi.com/documentation/computers/processors.html#bcm2837b0">Raspberry Pi Compute Module 3+: BCM2837B0</a>
            <ul>
              <li>The underlying architecture of the BCM2837B0 is identical to the BCM2837 chip used in other versions of the Raspberry Pi.</li>
              <li>The ARM core hardware is the same, only the frequency is rated higher.</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong><em>buster</em></strong>: One of th distributions of debian.</li>
  <li><strong><em>debianMinimalRootFS</em></strong>: Target directory for the new RootFS.</li>
  <li><strong><em>–foreign option</em></strong>: <code class="language-plaintext highlighter-rouge">debootstrap</code> is also capable of installing a system for any supported architecture, not only the host system’s architecture; with its <code class="language-plaintext highlighter-rouge">--foreign</code> option. If necessary it can use Qemu to emulate the target architecture.</li>
  <li>:heavy_check_mark: The output will be a basic rootfs file structure in target directory. Above command installs many debian packages in this directory, have a look at the logs and the created folder structures in target directory.
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mkdir debianMinimalRootFS
</code></pre></div>    </div>
  </li>
  <li>For <strong>64-Bit</strong> OS:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo debootstrap --arch=arm64 --foreign buster debianMinimalRootFS
</code></pre></div>    </div>
  </li>
  <li>For <strong>32-Bit</strong> OS:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo debootstrap --arch=armhf --foreign buster debianMinimalRootFS
</code></pre></div>    </div>

    <hr />
  </li>
</ul>

<h2 id="copy-qemu-aarch64-static-to-newly-created-rootfs">Copy <code class="language-plaintext highlighter-rouge">qemu-aarch64-static</code> to newly created rootfs</h2>
<ul>
  <li>Copy <code class="language-plaintext highlighter-rouge">qemu-aarch64-static</code> binary into <code class="language-plaintext highlighter-rouge">/$target_dir/usr/bin/</code> for binfmt packages to find it.</li>
  <li>For <strong>64-Bit</strong> OS:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo cp /usr/bin/qemu-aarch64-static /debianMinimalRootFS/usr/bin/
</code></pre></div>    </div>
  </li>
  <li>For <strong>32-Bit</strong> OS:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo cp /usr/bin/qemu-arm-static /debianMinimalRootFS/usr/bin/
</code></pre></div>    </div>

    <hr />
  </li>
</ul>

<h2 id="copy-resolvconf-to-newly-created-rootfs-for-internet-access">Copy <code class="language-plaintext highlighter-rouge">resolv.conf</code> to newly created rootfs for internet access</h2>
<ul>
  <li>The <code class="language-plaintext highlighter-rouge">/etc/resolv.conf</code> file defines how the system uses <strong><em><u>DNS</u></em></strong> <em><u> to resolve host names and IP addresses</u></em>.</li>
  <li>This file usually contains <em><u>a line specifying the </u></em><strong><em><u>search domains</u></em></strong> and up to <em><u>three lines that specify the </u></em><strong><em><u>IP addresses of DNS server</u></em></strong>.
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo cp /etc/resolv.conf /debianMinimalRootFS/etc/resolv.conf
</code></pre></div>    </div>

    <hr />
  </li>
</ul>

<h2 id="setup-newly-created-rootfs">Setup newly created RootFS</h2>
<ul>
  <li><strong><em><u>chroot, chroot jail</u></em></strong>:
    <ul>
      <li>A <code class="language-plaintext highlighter-rouge">chroot</code> on Unix operating systems is <em><u>an operation that changes the apparent root directory for the current running process and its children</u></em>.</li>
      <li><em><u>A program that is run in such a modified environment cannot name (and therefore normally cannot access) files outside the designated directory tree</u></em>.</li>
      <li>A chroot environment can be used to create and host a separate virtualized copy of the software system.</li>
    </ul>
  </li>
  <li>In our case, we will <code class="language-plaintext highlighter-rouge">chroot</code> to further setup the RootFS.
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo chroot /debianMinimalRootFS
</code></pre></div>    </div>
  </li>
  <li>Setup environment:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># export LANG=C
</code></pre></div>    </div>

    <hr />
  </li>
</ul>

<h2 id="2nd-stage-of-debootstrap">2nd stage of <code class="language-plaintext highlighter-rouge">debootstrap</code></h2>
<ul>
  <li>We need to run the 2nd stage of <code class="language-plaintext highlighter-rouge">debootstrap</code> to install the packages downloaded earlier, as:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># /debootstrap/debootstrap --second-stage
</code></pre></div>    </div>
  </li>
  <li>Let the installation complete, it may take few minutes. After completion, you should get following message on terminal:</li>
  <li>
    <p>:heavy_check_mark: <code class="language-plaintext highlighter-rouge">I: Base system installed successfully.</code></p>

    <hr />
  </li>
</ul>

<h2 id="add-debian-repository-and-apt-configuration">Add debian repository and apt configuration</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># cat &lt;&lt;EOT &gt; /etc/apt/sources.list
&gt; deb http://deb.debian.org/debian buster main contrib non-free
&gt; deb-src http://deb.debian.org/debian buster main contrib non-free
&gt; deb http://security.debian.org/ buster/updates main contrib non-free
&gt; deb-src http://security.debian.org/ buster/updates main contrib non-free
&gt; deb http://deb.debian.org/debian buster-updates main contrib non-free
&gt; deb-src http://deb.debian.org/debian buster-updates main contrib non-free
&lt; EOT
</code></pre></div></div>

<ul>
  <li>Check the apt sources list:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># cat /etc/apt/sources.list
</code></pre></div>    </div>
  </li>
  <li>Update debian database:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># apt update
</code></pre></div>    </div>

    <hr />
  </li>
</ul>

<h2 id="install-and-configure-few-packages">Install and configure few packages</h2>
<ul>
  <li>Install <code class="language-plaintext highlighter-rouge">locales</code> and <code class="language-plaintext highlighter-rouge">dialog</code> packages, otherwise, set up locales dpkg scripts tend to complain.
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># apt install locales dialog
</code></pre></div>    </div>
  </li>
  <li>Configure <code class="language-plaintext highlighter-rouge">locales</code>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># dpkg-reconfigure locales
</code></pre></div>    </div>
    <ul>
      <li>Select <code class="language-plaintext highlighter-rouge">en_US.UTF-8 UTF-8</code> only, click <code class="language-plaintext highlighter-rouge">ok</code> on the dialog box.</li>
      <li>On next dialog box, again select <code class="language-plaintext highlighter-rouge">en_US.UTF-8</code>, click <code class="language-plaintext highlighter-rouge">ok</code>.</li>
    </ul>

    <hr />
  </li>
</ul>

<h2 id="install-some-useful-packages-inside-the-chroot">Install some useful packages inside the chroot</h2>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># apt install vim openssh-server ntpdate sudo ifupdown net-tools udev iputils-ping wget dosfstools unzip binutils libatomic1
</code></pre></div></div>

<ul>
  <li><code class="language-plaintext highlighter-rouge">ntpdate</code> - sets the local date and time by polling the Network Time Protocol (NTP) server(s) given as the server arguments to determine the correct time.</li>
  <li><code class="language-plaintext highlighter-rouge">ifupdown</code> - configure (or, respectively, deconfigure) network interfaces based on interface definitions in the file /etc/network/interfaces.</li>
  <li><code class="language-plaintext highlighter-rouge">net-tools</code> - This package includes arp(8), hostname(1), ifconfig(8), ipmaddr, iptunnel, mii-tool(8), nameif(8), netstat(8), plipconfig(8), rarp(8), route(8) and slattach(8).</li>
  <li><code class="language-plaintext highlighter-rouge">udev</code> - (userspace /dev) - primarily manages device nodes in the <code class="language-plaintext highlighter-rouge">/dev</code> directory. At the same time, udev also handles all user space events raised when hardware devices are added into the system or removed from it, including firmware loading as required by certain devices.</li>
  <li><code class="language-plaintext highlighter-rouge">iputils-ping</code> - <code class="language-plaintext highlighter-rouge">ping</code> command that sends ICMP ECHO_REQUEST packets to a host in order to test if the host is reachable via the network. This package includes a <code class="language-plaintext highlighter-rouge">ping6</code> utility which supports <code class="language-plaintext highlighter-rouge">IPv6</code> network connections.</li>
  <li><code class="language-plaintext highlighter-rouge">wget</code> - downloads files served with HTTP, HTTPS, or FTP over a network.</li>
  <li><code class="language-plaintext highlighter-rouge">dosfstools</code> - The dosfstools package contains various utilities for use with the <code class="language-plaintext highlighter-rouge">FAT</code> family of file systems like <code class="language-plaintext highlighter-rouge">mkfs.fat</code> and <code class="language-plaintext highlighter-rouge">fsck.fat</code> utilities, which respectively make and check MS-DOS FAT filesystems.</li>
  <li><code class="language-plaintext highlighter-rouge">unzip</code> - Command used to unzip the zipped files.</li>
  <li><code class="language-plaintext highlighter-rouge">binutils</code> - It’s very basic GNU package and it’s utilities listed below are required by many other applications to work properly, like AWS Greengrass.
    <ul>
      <li>GNU Binutils are a collection of binary tools:</li>
      <li><code class="language-plaintext highlighter-rouge">ld</code> - the GNU linker.</li>
      <li><code class="language-plaintext highlighter-rouge">as</code> - the GNU assembler.</li>
      <li><code class="language-plaintext highlighter-rouge">addr2line</code> - Converts addresses into filenames and line numbers.</li>
      <li><code class="language-plaintext highlighter-rouge">ar</code> - A utility for creating, modifying and extracting from archives.</li>
      <li><code class="language-plaintext highlighter-rouge">c++filt</code> - Filter to demangle encoded C++ symbols.</li>
      <li><code class="language-plaintext highlighter-rouge">dlltool</code> - Creates files for building and using DLLs.</li>
      <li><code class="language-plaintext highlighter-rouge">gold</code> - A new, faster, ELF only linker, still in beta test.</li>
      <li><code class="language-plaintext highlighter-rouge">gprof</code> - Displays profiling information.</li>
      <li><code class="language-plaintext highlighter-rouge">nlmconv</code> - Converts object code into an NLM.</li>
      <li><code class="language-plaintext highlighter-rouge">nm</code> - Lists symbols from object files.</li>
      <li><code class="language-plaintext highlighter-rouge">objcopy</code> - Copies and translates object files.</li>
      <li><code class="language-plaintext highlighter-rouge">objdump</code> - Displays information from object files.</li>
      <li><code class="language-plaintext highlighter-rouge">ranlib</code> - Generates an index to the contents of an archive.</li>
      <li><code class="language-plaintext highlighter-rouge">readelf</code> - Displays information from any ELF format object file.</li>
      <li><code class="language-plaintext highlighter-rouge">size</code> - Lists the section sizes of an object or archive file.</li>
      <li><code class="language-plaintext highlighter-rouge">strings</code> - Lists printable strings from files.</li>
      <li><code class="language-plaintext highlighter-rouge">strip</code> - Discards symbols.</li>
      <li><code class="language-plaintext highlighter-rouge">windmc</code> - A Windows compatible message compiler.</li>
      <li><code class="language-plaintext highlighter-rouge">windres</code> - A compiler for Windows resource files.</li>
    </ul>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">libatomic1</code> - library providing __atomic built-in functions. When an atomic call cannot be turned into lock-free instructions, GCC will make calls into this library.
             - Required by node 12.x installation.</p>

    <hr />
  </li>
</ul>

<h2 id="install-nodejs-on-custom-debian-rootfs">Install NodeJS on custom debian rootfs</h2>
<ul>
  <li>We are creating the <code class="language-plaintext highlighter-rouge">rootfs</code> for the <code class="language-plaintext highlighter-rouge">arm</code> architecture, so we will not take the usual <code class="language-plaintext highlighter-rouge">nvm</code> installation path, rather we will download the Node Archive for particular ARM Architecture for required Node version from the <code class="language-plaintext highlighter-rouge">https://nodejs.org/dist/</code> website, which hosts all Node releases.</li>
  <li>We will be installing <strong><em>Node12</em></strong> this time.</li>
  <li>Download node installable:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># cd /tmp
# wget https://nodejs.org/dist/v12.0.0/node-v12.0.0-linux-armv7l.tar.xz
</code></pre></div>    </div>
  </li>
  <li>Extract:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># xz -d node-v12.0.0-linux-armv7l.tar.xz
# tar -xvf node-v12.0.0-linux-armv7l.tar
</code></pre></div>    </div>
  </li>
  <li>Install:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># cd /tmp/node-v12.0.0-linux-armv7l.tar.xz/
# cp -R * /usr/local/
</code></pre></div>    </div>
  </li>
  <li>Verify Installation:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># node -v
# npm -v
</code></pre></div>    </div>
  </li>
</ul>

<hr />

<h2 id="set-root-password-for-login">Set root password for login</h2>
<ul>
  <li><code class="language-plaintext highlighter-rouge">passwd</code> command is used to update the password of the Linux users.</li>
  <li>If no user is specified, default <code class="language-plaintext highlighter-rouge">root</code> user is considered for password update.
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># passwd
</code></pre></div>    </div>
  </li>
</ul>

<hr />

<h2 id="create-user-and-set-password">Create user and set password</h2>
<ul>
  <li><code class="language-plaintext highlighter-rouge">useradd</code> command creates a new user entry in <code class="language-plaintext highlighter-rouge">/etc/passwd</code>, <code class="language-plaintext highlighter-rouge">/etc/shadow</code>, <code class="language-plaintext highlighter-rouge">/etc/group</code>, <code class="language-plaintext highlighter-rouge">/etc/gshadow</code> files.</li>
  <li><code class="language-plaintext highlighter-rouge">-m</code> option with <code class="language-plaintext highlighter-rouge">useradd</code> creates Home Directory for the new user as: <code class="language-plaintext highlighter-rouge">/home/&lt;user-name&gt;</code>
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># useradd -m &lt;user-name&gt;
# passwd &lt;user-name&gt;
</code></pre></div>    </div>
  </li>
  <li><strong><em><u>Change the default `shell` to `/bin/bash`</u></em></strong> for the users, why because, Bash provides a lot of flexibility and syntax that looks a lot like those of modern programming languages. Few key features of Bash are:
    <ul>
      <li><strong>Command-line completion</strong> can be used to quickly complete a command using the <TAB> key</TAB></li>
      <li><strong>Command history</strong> through which we can quickly search for commands previously executed by using the <Up> arrow key or <CTRL-R></CTRL-R></Up></li>
      <li><strong>Arithmetic evaluation</strong> without having to use external programs</li>
      <li><strong>Associative arrays</strong>, which enables us to create an array with string indices</li>
      <li>Keyboard shortcuts for command-line editing</li>
      <li>Customizability enables us to modify the default presentation offered by Bash
        <ul>
          <li>like Colors, Current Folder or Complete Path to current folder settings can be modified with variables like: <code class="language-plaintext highlighter-rouge">$PS1</code>.
            <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># usermod --shell /bin/bash &lt;user-name&gt;
</code></pre></div>            </div>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<hr />

<h2 id="network-settings-in-rootfs">Network settings in RootFS</h2>
<ul>
  <li>Following settings will enable a Static IP address: 192.168.0.254 to the board on <code class="language-plaintext highlighter-rouge">eth0</code> network interface. We should be able to SSH to the board.</li>
  <li><code class="language-plaintext highlighter-rouge">allow-hotplug &lt;interface&gt;</code> - Start the <interface> when a "hotplug" event is detected, i.e. when the ethernet cable is inserted.</interface></li>
  <li>For <strong><em>Static IP</em></strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># cat &gt;&gt; EOT &gt; etc/network/interfaces
allow-hotplug eth0
iface eth0 inet static
  address 192.168.1.254
  netmask 255.255.255.248
  gateway 192.168.1.1	
EOT
</code></pre></div>    </div>
  </li>
  <li>For <strong><em>Dynamic IP</em></strong>:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># cat &gt;&gt; EOT &gt; etc/network/interfaces
&gt; auto eth0
&gt; iface eth0 inet dhcp
&gt; EOT
</code></pre></div>    </div>
  </li>
  <li><strong><em><u>Ping Command Alias</u></em></strong>:
    <ul>
      <li>Ping command supports both ipv4 &amp; ipv6, but for some reason unknown to me, <code class="language-plaintext highlighter-rouge">ping</code> command is acting as <code class="language-plaintext highlighter-rouge">ping -6</code> i.e. for ipv6 protocol by default.</li>
      <li>On the RootFS created, by default ipv6 is disabled, confirmed with below command, which returns ipv6 address, if it’s enabled on the OS or on RootFS:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ip -6 addr
$ ip -4 addr
$ ip a
</code></pre></div>        </div>
      </li>
      <li>So <code class="language-plaintext highlighter-rouge">ping</code> command results in error:
        <ul>
          <li>Error: <code class="language-plaintext highlighter-rouge">ping: socket: Address family not supported by protocol</code></li>
        </ul>
      </li>
      <li>Solution for this error is to create an alias of the <code class="language-plaintext highlighter-rouge">ping -4</code> command, so that we need not to remember everytime about using this flag for ipv4.
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo vim ~/.bashrc
&gt;
&gt; # Custom aliases
&gt; alias ping='ping -4'
&gt;
</code></pre></div>        </div>
      </li>
      <li>Reference:
        <ul>
          <li><a href="https://bbs.archlinux.org/viewtopic.php?id=202614">archlinux: ping error</a></li>
          <li><a href="https://www.golinuxcloud.com/linux-check-ipv6-enabled/">Check if ipv6 enabled or disabled</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<hr />

<h2 id="set-hostname-for-the-board">Set <code class="language-plaintext highlighter-rouge">hostname</code> for the board</h2>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># echo &lt;any-host-name&gt; &gt; etc/hostname
</code></pre></div></div>
<ul>
  <li>Edit <code class="language-plaintext highlighter-rouge">/etc/hosts</code> to <strong><em>add an entry</em></strong> for hostname in it.
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># vim /etc/hosts
&gt; 127.0.1.1 &lt;Tab&gt; &lt;any-host-name&gt;
</code></pre></div>    </div>
  </li>
</ul>

<hr />

<h2 id="add-fstab-entries-for-partitions">Add <code class="language-plaintext highlighter-rouge">fstab</code> entries for partitions</h2>
<ul>
  <li>Note: these are the tabs, between the columns in <code class="language-plaintext highlighter-rouge">fstab</code> file.</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># vim etc/fstab
&gt;&gt;&gt;
proc  /proc proc  defaults  0 0
PARTUUID=&lt;PARTUUID of `ROOTFS Partition of SD card or loop mounted Image`&gt;  /   ext4    defaults,noatime    0   1
PARTUUID=&lt;PARTUUID of `BOOT Partition of SD card or loop mounted Image`&gt;  /boot  vfat    defaults    0   2
PARTUUID=&lt;PARTUUID of `DATA Partition of SD card or loop mounted Image`&gt;  /data ext4  defaults  0 0
&gt;&gt;&gt;
</code></pre></div></div>

<hr />

<h2 id="configure-sudo-utility">Configure <code class="language-plaintext highlighter-rouge">sudo</code> utility</h2>
<ul>
  <li>Few Errors that we may face, if <code class="language-plaintext highlighter-rouge">sudo</code> utility is not configured properly as:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">Error: sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set</code>
        <ul>
          <li>Solution: <a href="https://askubuntu.com/a/471503/896173">Reference</a>
            <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># chown root:root /usr/bin/sudo
# chmod 4755 /usr/bin/sudo
</code></pre></div>            </div>
          </li>
        </ul>
      </li>
      <li><code class="language-plaintext highlighter-rouge">Error: &lt;username&gt; is not in the sudoers file</code>
        <ul>
          <li>Solution: <a href="https://www.tecmint.com/fix-user-is-not-in-the-sudoers-file-the-incident-will-be-reported-ubuntu/">Reference</a>
            <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># adduser &lt;username&gt; sudo
</code></pre></div>            </div>
          </li>
        </ul>
      </li>
      <li><code class="language-plaintext highlighter-rouge">Error: sudo unable to resolve host</code>
        <ul>
          <li>Solution: <a href="https://askubuntu.com/a/59517/896173">Reference</a>
            <ul>
              <li>Add <code class="language-plaintext highlighter-rouge">hostname</code> entry to <code class="language-plaintext highlighter-rouge">/etc/hosts</code> file as per section: <a href="/_post/linux/debian_minimal_rootfs#set-hostname-for-the-board">Set <code class="language-plaintext highlighter-rouge">hostname</code> for the board</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<hr />

<h2 id="exit-chroot-shell">Exit chroot shell</h2>
<ul>
  <li>Your Custom Debian Minimal RootFS is ready in debianMinimalRootFS` folder.</li>
  <li>We can now exit the from the <code class="language-plaintext highlighter-rouge">chroot</code>.
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># exit
</code></pre></div>    </div>
  </li>
</ul>

<hr />

<h2 id="remove-support-files-from-rootfs">Remove Support files from RootFS</h2>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo rm /debianMinimalRootFS/usr/bin/qemu-aarch64-static
or
$ sudo rm debianMinimalRootFS/usr/bin/qemu-arm-static
</code></pre></div></div>

<hr />

<h2 id="copy-custom-rootfs-to-sd-card-partition">Copy Custom RootFS to SD card Partition</h2>
<ul>
  <li>You can dirctly copy whole contents of the debianMinimalRootFS` folder on to a ROOTFS partition of the bootable/disk image.</li>
  <li>But if we directly copy the contents of the <code class="language-plaintext highlighter-rouge">debianMinimalRootFS</code> i.e. Custom RootFS folder, we had just exited from to any partition of the SD card using <code class="language-plaintext highlighter-rouge">cp</code> command, there are definite chances of intereferences with the file/folder properties like, the folder/file permissions getting changed to the <code class="language-plaintext highlighter-rouge">root</code> user, which might probably be used to copy the contents and many more as such.</li>
  <li>This may result in folders/files only being accessible to <code class="language-plaintext highlighter-rouge">root</code> user even after successful boot.</li>
  <li>To avoid any such issues, it’s always better to bundle the custom RootFS using <code class="language-plaintext highlighter-rouge">tar</code> command, which stores information about ownership and permissions and is recursive by default.</li>
  <li>Also, while extracting the contents from the bundle, <code class="language-plaintext highlighter-rouge">tar</code> command provides the flags like <code class="language-plaintext highlighter-rouge">--same-owner</code> and <code class="language-plaintext highlighter-rouge">--same-permissions</code>, which preserves the ownership &amp; permissions of the files while being extracted.</li>
  <li>Create a bundle/archive of the custom rootfs:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd `debianMinimalRootFS`
$ sudo tar cvf debianMinimalRootFS.tar *
</code></pre></div>    </div>
  </li>
  <li>Check the bundle created:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ls -ltha
</code></pre></div>    </div>
  </li>
  <li>Extract the custom rootfs bundle to SD card partition mounted e.g. at <code class="language-plaintext highlighter-rouge">/media/SD-Card</code>
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo tar --same-owner --same-permissions -xvf debianMinimalRootFS.tar -C /media/SD-Card/ROOTFS/
</code></pre></div>    </div>
  </li>
  <li>Check the Extracted custom rootfs from SD-Card partition:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ls -ltha /media/SD-Card/ROOTFS/
</code></pre></div>    </div>
  </li>
</ul>

<hr />

<ul>
  <li>With this, your SD-Card is ready to use with board.</li>
  <li>You may be required to modify the boot command like in <code class="language-plaintext highlighter-rouge">cmdline.txt</code> in <code class="language-plaintext highlighter-rouge">/boot</code> partiton for RaspberryPi as per the boot settings.</li>
  <li>Also, there might be changes required in <code class="language-plaintext highlighter-rouge">/etc/fstab</code> file to mount the various partitions at the boot time.</li>
  <li>Hopefully, your board should boot without any errors… fingers crossed…</li>
  <li>Note:
    <ul>
      <li>This is a very minimal rootfs, many packages would be required to be installed in order to carryout the work properly.</li>
      <li>But this image is configured to connect to the ethernet port and internet should be accessible for you to install packages, so No Worries…</li>
    </ul>
  </li>
</ul>

<hr />

<h6 id="references">References:</h6>
<ul>
  <li><a href="https://packages.debian.org/sid/qemu-user-static">qemu-user-static</a></li>
  <li><a href="https://packages.debian.org/sid/binfmt-support">binfmt-support</a></li>
  <li><a href="https://wiki.debian.org/Debootstrap">Debootstrap</a></li>
  <li><a href="https://en.wikipedia.org/wiki/Chroot">Wikipedia: chroot</a></li>
  <li><a href="https://linuxize.com/post/how-to-create-users-in-linux-using-the-useradd-command/">useradd</a></li>
  <li><a href="https://unix.stackexchange.com/q/128439/98539">Details of /etc/network/interfaces</a></li>
  <li><a href="https://superuser.com/a/1461631/568169">How to preserve file structure/ownership/permission/… when downloading a folder from remote server?</a></li>
  <li></li>
</ul>]]></content><author><name>Akhilesh Moghe</name></author><category term="Linux" /><category term="Embedded Linux" /><category term="Systems Engineering" /><category term="Linux" /><category term="Embedded Linux" /><category term="Systems Engineering" /><summary type="html"><![CDATA[This article is about creation of minimal rootfs which will be the base file system to be mounted on / rootfs partition any Embedded board like Raspberry Pi, NVIDIA Jetson Nano/TX2 once the kernel is loaded in memory by the boot loader. We will also install few linux packages like ssh, nodeJS, which forms part of pre-installed packages on our customize rootfs. All steps below should work on any Debian/Ubuntu host and I have verified them with Ubuntu 18.04 LTS. Install support packages on host: Get apt sources updated: $ sudo apt update qemu-user-static QEMU user mode emulation binaries (static version) QEMU is a fast processor emulator: By using dynamic translation it achieves reasonable speed while being easy to port on new host CPUs. currently the package supports ARM, CRIS, i386, M68k (ColdFire), MicroBlaze, MIPS, PowerPC, SH4, SPARC and x86-64 emulation. This qemu-user-static package provides the user mode emulation binaries, built statically. In this mode QEMU can launch Linux processes compiled for one CPU on another CPU. qemu-user-static package will register binary formats which the provided emulators can handle, so that it will be possible to run foreign binaries directly. Other few QEMU packages (mentioned here just for info, not required for the task at hand): qemu: Once upon a time there was only one package named qemu, with all functionality included. These days, qemu become large and has been split into numerous packages. Different packages provides entirely different services, and it is very unlikely one will need all of them together. So current qemu package makes no sense anymore, and is becoming a dummy package. qemu-user: If you want user-mode emulation, install qemu-user or qemu-user-static package. qemu-utils: If you need utilities, use qemu-utils package. $ sudo apt install qemu-user-static binfmt-support Support for extra binary formats The binfmt_misc kernel module allows system administrators to register interpreters for various binary formats based on a magic number or their file extension, and cause the appropriate interpreter to be invoked whenever a matching file is executed. Think of it as a more flexible version of the #! (shebang line) executable interpreter mechanism. This binfmt-support package provides an update-binfmts script with which package maintainers can register interpreters to be used with this module without having to worry about writing their own init.d scripts, and which sysadmins can use for a slightly higher-level interface to this module. $ sudo apt install binfmt-support debootstrap debootstrap is a tool which will install a Debian base system into a subdirectory of another, already installed system. It doesn’t require an installation CD, just access to a Debian repository (~internet). It can also be installed and run from another operating system, so, for instance, you can use debootstrap to install Debian onto an unused partition from a running Gentoo Linux. It can also be used to create a rootfs for a machine of a different architecture, which is known as cross-debootstrapping. :x: Debootstrap can only use one repository for its packages. If you need to merge packages from different repositories (the way apt does) to make a rootfs, or you need to automatically customise the rootfs, then use Multistrap. $ sudo apt install debootstrap Build 1st stage of Debian RootFS ARM Architecture: I am using Raspberry Pi 4 Model B board while drafting this article, RPi4 uses Broadcom BCM2711 chip which has ARM Cortex-A72 CPU, which implements ARMv8-A 64-bit instruction set. I am also going to try this created RootFS on Revolution Pi, RevPi Connect box which uses Raspberry Pi Compute Module 3 chip which has ARM Cortex-A53 CPU, which also implements ARMv8-A 64-bit instruction set. So, in my opinion, the same RootFS should work on both the boards, though they have different processors, but the same instruction set and the ARM Architecture. ARMv8-A has 64-bit ARM Architecture known as AArch64 or ARM64. Is there a difference? AArch64 is the 64-bit state introduced in the Armv8-A architecture, The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that’s where some of the arm64 usage comes from. So, AArch64 is the ARM64, no difference. References: Wikipedia: AArch46 Stackoverflow: Differences between arm64 and aarch64 Wikipedia: Raspberry_Pi Specifications Wikipedia: ARM Cortex-A53 Wikipedia: ARM Cortex-A72 Wikipedia: Comparison of ARMv8-A processors Wikipedia ARM 64/32-bit Architecture Revolution Pi, RevPi Connect Raspberry Pi OS (64-bit): compatible with CM3 &amp; Pi4 Raspberry Pi 4 Model B: BCM2711 Raspberry Pi Compute Module 3: BCM2837 The underlying architecture of the BCM2837 is identical to the BCM2836. The only significant difference is the replacement of the ARMv7 quad core cluster with a quad-core ARM Cortex A53 (ARMv8) cluster. Raspberry Pi Compute Module 3+: BCM2837B0 The underlying architecture of the BCM2837B0 is identical to the BCM2837 chip used in other versions of the Raspberry Pi. The ARM core hardware is the same, only the frequency is rated higher. buster: One of th distributions of debian. debianMinimalRootFS: Target directory for the new RootFS. –foreign option: debootstrap is also capable of installing a system for any supported architecture, not only the host system’s architecture; with its --foreign option. If necessary it can use Qemu to emulate the target architecture. :heavy_check_mark: The output will be a basic rootfs file structure in target directory. Above command installs many debian packages in this directory, have a look at the logs and the created folder structures in target directory. $ mkdir debianMinimalRootFS For 64-Bit OS: $ sudo debootstrap --arch=arm64 --foreign buster debianMinimalRootFS For 32-Bit OS: $ sudo debootstrap --arch=armhf --foreign buster debianMinimalRootFS Copy qemu-aarch64-static to newly created rootfs Copy qemu-aarch64-static binary into /$target_dir/usr/bin/ for binfmt packages to find it. For 64-Bit OS: $ sudo cp /usr/bin/qemu-aarch64-static /debianMinimalRootFS/usr/bin/ For 32-Bit OS: $ sudo cp /usr/bin/qemu-arm-static /debianMinimalRootFS/usr/bin/ Copy resolv.conf to newly created rootfs for internet access The /etc/resolv.conf file defines how the system uses DNS to resolve host names and IP addresses. This file usually contains a line specifying the search domains and up to three lines that specify the IP addresses of DNS server. $ sudo cp /etc/resolv.conf /debianMinimalRootFS/etc/resolv.conf Setup newly created RootFS chroot, chroot jail: A chroot on Unix operating systems is an operation that changes the apparent root directory for the current running process and its children. A program that is run in such a modified environment cannot name (and therefore normally cannot access) files outside the designated directory tree. A chroot environment can be used to create and host a separate virtualized copy of the software system. In our case, we will chroot to further setup the RootFS. $ sudo chroot /debianMinimalRootFS Setup environment: # export LANG=C 2nd stage of debootstrap We need to run the 2nd stage of debootstrap to install the packages downloaded earlier, as: # /debootstrap/debootstrap --second-stage Let the installation complete, it may take few minutes. After completion, you should get following message on terminal: :heavy_check_mark: I: Base system installed successfully. Add debian repository and apt configuration # cat &lt;&lt;EOT &gt; /etc/apt/sources.list &gt; deb http://deb.debian.org/debian buster main contrib non-free &gt; deb-src http://deb.debian.org/debian buster main contrib non-free &gt; deb http://security.debian.org/ buster/updates main contrib non-free &gt; deb-src http://security.debian.org/ buster/updates main contrib non-free &gt; deb http://deb.debian.org/debian buster-updates main contrib non-free &gt; deb-src http://deb.debian.org/debian buster-updates main contrib non-free &lt; EOT Check the apt sources list: # cat /etc/apt/sources.list Update debian database: # apt update Install and configure few packages Install locales and dialog packages, otherwise, set up locales dpkg scripts tend to complain. # apt install locales dialog Configure locales: # dpkg-reconfigure locales Select en_US.UTF-8 UTF-8 only, click ok on the dialog box. On next dialog box, again select en_US.UTF-8, click ok. Install some useful packages inside the chroot # apt install vim openssh-server ntpdate sudo ifupdown net-tools udev iputils-ping wget dosfstools unzip binutils libatomic1 ntpdate - sets the local date and time by polling the Network Time Protocol (NTP) server(s) given as the server arguments to determine the correct time. ifupdown - configure (or, respectively, deconfigure) network interfaces based on interface definitions in the file /etc/network/interfaces. net-tools - This package includes arp(8), hostname(1), ifconfig(8), ipmaddr, iptunnel, mii-tool(8), nameif(8), netstat(8), plipconfig(8), rarp(8), route(8) and slattach(8). udev - (userspace /dev) - primarily manages device nodes in the /dev directory. At the same time, udev also handles all user space events raised when hardware devices are added into the system or removed from it, including firmware loading as required by certain devices. iputils-ping - ping command that sends ICMP ECHO_REQUEST packets to a host in order to test if the host is reachable via the network. This package includes a ping6 utility which supports IPv6 network connections. wget - downloads files served with HTTP, HTTPS, or FTP over a network. dosfstools - The dosfstools package contains various utilities for use with the FAT family of file systems like mkfs.fat and fsck.fat utilities, which respectively make and check MS-DOS FAT filesystems. unzip - Command used to unzip the zipped files. binutils - It’s very basic GNU package and it’s utilities listed below are required by many other applications to work properly, like AWS Greengrass. GNU Binutils are a collection of binary tools: ld - the GNU linker. as - the GNU assembler. addr2line - Converts addresses into filenames and line numbers. ar - A utility for creating, modifying and extracting from archives. c++filt - Filter to demangle encoded C++ symbols. dlltool - Creates files for building and using DLLs. gold - A new, faster, ELF only linker, still in beta test. gprof - Displays profiling information. nlmconv - Converts object code into an NLM. nm - Lists symbols from object files. objcopy - Copies and translates object files. objdump - Displays information from object files. ranlib - Generates an index to the contents of an archive. readelf - Displays information from any ELF format object file. size - Lists the section sizes of an object or archive file. strings - Lists printable strings from files. strip - Discards symbols. windmc - A Windows compatible message compiler. windres - A compiler for Windows resource files. libatomic1 - library providing __atomic built-in functions. When an atomic call cannot be turned into lock-free instructions, GCC will make calls into this library. - Required by node 12.x installation. Install NodeJS on custom debian rootfs We are creating the rootfs for the arm architecture, so we will not take the usual nvm installation path, rather we will download the Node Archive for particular ARM Architecture for required Node version from the https://nodejs.org/dist/ website, which hosts all Node releases. We will be installing Node12 this time. Download node installable: # cd /tmp # wget https://nodejs.org/dist/v12.0.0/node-v12.0.0-linux-armv7l.tar.xz Extract: # xz -d node-v12.0.0-linux-armv7l.tar.xz # tar -xvf node-v12.0.0-linux-armv7l.tar Install: # cd /tmp/node-v12.0.0-linux-armv7l.tar.xz/ # cp -R * /usr/local/ Verify Installation: # node -v # npm -v Set root password for login passwd command is used to update the password of the Linux users. If no user is specified, default root user is considered for password update. # passwd Create user and set password useradd command creates a new user entry in /etc/passwd, /etc/shadow, /etc/group, /etc/gshadow files. -m option with useradd creates Home Directory for the new user as: /home/&lt;user-name&gt; # useradd -m &lt;user-name&gt; # passwd &lt;user-name&gt; Change the default `shell` to `/bin/bash` for the users, why because, Bash provides a lot of flexibility and syntax that looks a lot like those of modern programming languages. Few key features of Bash are: Command-line completion can be used to quickly complete a command using the key Command history through which we can quickly search for commands previously executed by using the arrow key or Arithmetic evaluation without having to use external programs Associative arrays, which enables us to create an array with string indices Keyboard shortcuts for command-line editing Customizability enables us to modify the default presentation offered by Bash like Colors, Current Folder or Complete Path to current folder settings can be modified with variables like: $PS1. # usermod --shell /bin/bash &lt;user-name&gt; Network settings in RootFS Following settings will enable a Static IP address: 192.168.0.254 to the board on eth0 network interface. We should be able to SSH to the board. allow-hotplug &lt;interface&gt; - Start the when a "hotplug" event is detected, i.e. when the ethernet cable is inserted. For Static IP: # cat &gt;&gt; EOT &gt; etc/network/interfaces allow-hotplug eth0 iface eth0 inet static address 192.168.1.254 netmask 255.255.255.248 gateway 192.168.1.1 EOT For Dynamic IP: # cat &gt;&gt; EOT &gt; etc/network/interfaces &gt; auto eth0 &gt; iface eth0 inet dhcp &gt; EOT Ping Command Alias: Ping command supports both ipv4 &amp; ipv6, but for some reason unknown to me, ping command is acting as ping -6 i.e. for ipv6 protocol by default. On the RootFS created, by default ipv6 is disabled, confirmed with below command, which returns ipv6 address, if it’s enabled on the OS or on RootFS: $ ip -6 addr $ ip -4 addr $ ip a So ping command results in error: Error: ping: socket: Address family not supported by protocol Solution for this error is to create an alias of the ping -4 command, so that we need not to remember everytime about using this flag for ipv4. $ sudo vim ~/.bashrc &gt; &gt; # Custom aliases &gt; alias ping='ping -4' &gt; Reference: archlinux: ping error Check if ipv6 enabled or disabled Set hostname for the board # echo &lt;any-host-name&gt; &gt; etc/hostname Edit /etc/hosts to add an entry for hostname in it. # vim /etc/hosts &gt; 127.0.1.1 &lt;Tab&gt; &lt;any-host-name&gt; Add fstab entries for partitions Note: these are the tabs, between the columns in fstab file. # vim etc/fstab &gt;&gt;&gt; proc /proc proc defaults 0 0 PARTUUID=&lt;PARTUUID of `ROOTFS Partition of SD card or loop mounted Image`&gt; / ext4 defaults,noatime 0 1 PARTUUID=&lt;PARTUUID of `BOOT Partition of SD card or loop mounted Image`&gt; /boot vfat defaults 0 2 PARTUUID=&lt;PARTUUID of `DATA Partition of SD card or loop mounted Image`&gt; /data ext4 defaults 0 0 &gt;&gt;&gt; Configure sudo utility Few Errors that we may face, if sudo utility is not configured properly as: Error: sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set Solution: Reference # chown root:root /usr/bin/sudo # chmod 4755 /usr/bin/sudo Error: &lt;username&gt; is not in the sudoers file Solution: Reference # adduser &lt;username&gt; sudo Error: sudo unable to resolve host Solution: Reference Add hostname entry to /etc/hosts file as per section: Set hostname for the board Exit chroot shell Your Custom Debian Minimal RootFS is ready in debianMinimalRootFS` folder. We can now exit the from the chroot. # exit Remove Support files from RootFS $ sudo rm /debianMinimalRootFS/usr/bin/qemu-aarch64-static or $ sudo rm debianMinimalRootFS/usr/bin/qemu-arm-static Copy Custom RootFS to SD card Partition You can dirctly copy whole contents of the debianMinimalRootFS` folder on to a ROOTFS partition of the bootable/disk image. But if we directly copy the contents of the debianMinimalRootFS i.e. Custom RootFS folder, we had just exited from to any partition of the SD card using cp command, there are definite chances of intereferences with the file/folder properties like, the folder/file permissions getting changed to the root user, which might probably be used to copy the contents and many more as such. This may result in folders/files only being accessible to root user even after successful boot. To avoid any such issues, it’s always better to bundle the custom RootFS using tar command, which stores information about ownership and permissions and is recursive by default. Also, while extracting the contents from the bundle, tar command provides the flags like --same-owner and --same-permissions, which preserves the ownership &amp; permissions of the files while being extracted. Create a bundle/archive of the custom rootfs: $ cd `debianMinimalRootFS` $ sudo tar cvf debianMinimalRootFS.tar * Check the bundle created: $ ls -ltha Extract the custom rootfs bundle to SD card partition mounted e.g. at /media/SD-Card $ sudo tar --same-owner --same-permissions -xvf debianMinimalRootFS.tar -C /media/SD-Card/ROOTFS/ Check the Extracted custom rootfs from SD-Card partition: $ ls -ltha /media/SD-Card/ROOTFS/ With this, your SD-Card is ready to use with board. You may be required to modify the boot command like in cmdline.txt in /boot partiton for RaspberryPi as per the boot settings. Also, there might be changes required in /etc/fstab file to mount the various partitions at the boot time. Hopefully, your board should boot without any errors… fingers crossed… Note: This is a very minimal rootfs, many packages would be required to be installed in order to carryout the work properly. But this image is configured to connect to the ethernet port and internet should be accessible for you to install packages, so No Worries… References: qemu-user-static binfmt-support Debootstrap Wikipedia: chroot useradd Details of /etc/network/interfaces How to preserve file structure/ownership/permission/… when downloading a folder from remote server?]]></summary></entry><entry><title type="html">Frequently used commands while creating a Linux Disk Image</title><link href="https://akhileshmoghe.github.io/_post/linux/disk_img_creation_process" rel="alternate" type="text/html" title="Frequently used commands while creating a Linux Disk Image" /><published>2022-06-03T01:33:22+05:30</published><updated>2022-06-03T01:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_post/linux/Disk-image</id><content type="html" xml:base="https://akhileshmoghe.github.io/_post/linux/disk_img_creation_process"><![CDATA[<p>In this article, we will learn the Linux Disk image creation, partioning the disk image, formatting the partitions, mounting it in order to view it’s contents.
Also, we will try to understand the various commands used in this process like <code class="language-plaintext highlighter-rouge">dd</code>, <code class="language-plaintext highlighter-rouge">fdisk</code>, <code class="language-plaintext highlighter-rouge">mkfs</code>, etc…</p>

<h2 id="dd">dd:</h2>
<ul>
  <li><code class="language-plaintext highlighter-rouge">dd</code> is basically a command-line utility to copy a file, also convert and format as per the options specified.</li>
  <li>Now, Linux/Unix has everything as a file, weather it’s a Hardware drive like <code class="language-plaintext highlighter-rouge">/dev/sda</code>, USB drives like <code class="language-plaintext highlighter-rouge">/dev/sdb</code> or special devices like <code class="language-plaintext highlighter-rouge">/dev/null</code> or <code class="language-plaintext highlighter-rouge">/dev/zero</code> or <code class="language-plaintext highlighter-rouge">/dev/random</code>, all are files only, so <code class="language-plaintext highlighter-rouge">dd</code> command can be used for all above devices, to read from, write to i.e. copy to/from and also format them.</li>
  <li><code class="language-plaintext highlighter-rouge">dd</code> can be used for tasks such as <em><u>backing up the </u></em><strong><em><u>boot sector</u></em></strong> of a hard drive, and <em><u>obtaining a fixed amount of random data</u></em>.</li>
  <li><code class="language-plaintext highlighter-rouge">dd</code> can also perform <em><u>conversions on the data</u></em> as it is copied, including <em><u>byte order swapping</u></em> and <em><u>conversion to and from the ASCII and EBCDIC text encodings</u></em> (option: conv=ascii/ebcdic).</li>
  <li>By default, <code class="language-plaintext highlighter-rouge">dd</code> reads from <code class="language-plaintext highlighter-rouge">stdin</code> and writes to <code class="language-plaintext highlighter-rouge">stdout</code>, but these can be changed by using the <code class="language-plaintext highlighter-rouge">if</code> (input file) and <code class="language-plaintext highlighter-rouge">of</code> (output file) options.</li>
  <li>On completion, <code class="language-plaintext highlighter-rouge">dd</code> prints to the <code class="language-plaintext highlighter-rouge">stderr</code> stream about statistics of the data transfer. Each of the <em><u>Records in</u></em> and <em><u>Records out</u></em> lines shows the number of <em><u>complete blocks transferred + the number of partial blocks</u></em>, e.g. because the physical medium ended before a complete block was read, or a physical error prevented reading the complete block.</li>
  <li><strong><em><u>Block Size (bs)</u></em></strong>:
    <ul>
      <li>A <em><u>block</u></em> is a unit measuring the number of bytes that are read, written, or converted at one time.</li>
      <li>Command-line options can specify a different block size for <em><u>input/reading</u></em> (<strong><em><u>ibs</u></em></strong>) compared to <em><u>output/writing</u></em> (<strong><em><u>obs</u></em></strong>), though the <em><u>block size</u></em> (<strong><em><u>bs</u></em></strong>) option will override both ibs and obs.</li>
      <li>The <strong>default</strong> value for both input and output block sizes is <strong>512 bytes</strong> (the traditional block size of disks, and POSIX-mandated size of “a block”).</li>
      <li>Block size has an effect on the performance of copying <code class="language-plaintext highlighter-rouge">dd</code> commands.
        <ul>
          <li>Doing many small reads or writes is often slower than doing fewer large ones.</li>
          <li>Using large blocks requires more RAM and can complicate error recovery, also larger block sizes usually don’t really speed it up much more.</li>
          <li>Basically you should use <em><u>4M</u></em> or a multiple of that as block size. Because, the organisation of SD card is such that , it erases 4M blocks in group, so partitions should be aligned on Erase Block Group, i.e. 4M boundary for efficiency.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong><em><u>Count</u></em></strong>:
    <ul>
      <li>The count option for copying is measured in blocks, as are both the <strong><em><u>skip count</u></em></strong> for reading and <strong><em><u>seek count</u></em></strong> for writing.</li>
    </ul>
  </li>
  <li><strong><em><u>Status</u></em></strong>:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">dd</code> support the <code class="language-plaintext highlighter-rouge">status=progress</code> option, which enables periodic printing of transfer statistics to stderr.</li>
    </ul>
  </li>
  <li>Examples:</li>
</ul>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
</pre></td><td class="code"><pre><span class="nv">$ blocks</span><span class="o">=</span><span class="si">$(</span>isosize <span class="nt">-d</span> 2048 /dev/sr0<span class="si">)</span>
<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/sr0 <span class="nv">of</span><span class="o">=</span>isoimage.iso <span class="nv">bs</span><span class="o">=</span>2048 <span class="nv">count</span><span class="o">=</span><span class="nv">$blocks</span> <span class="nv">status</span><span class="o">=</span>progress
<span class="nt">--</span><span class="o">&gt;</span> Creates an ISO disk image from a CD-ROM, DVD or Blu-ray disc.

<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>system.img <span class="nv">of</span><span class="o">=</span>/dev/sdc <span class="nv">bs</span><span class="o">=</span>64M <span class="nv">conv</span><span class="o">=</span>noerror
<span class="nt">--</span><span class="o">&gt;</span> Restores a hard disk drive <span class="o">(</span>or an SD card, <span class="k">for </span>example<span class="o">)</span> from a previously created image.

<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/sdb2 <span class="nv">of</span><span class="o">=</span>partition.image <span class="nv">bs</span><span class="o">=</span>64M <span class="nv">conv</span><span class="o">=</span>noerror
<span class="nt">--</span><span class="o">&gt;</span> Create an image of the partition sdb2, using a 64 MiB block size.

<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/sda2 <span class="nv">of</span><span class="o">=</span>/dev/sdb2 <span class="nv">bs</span><span class="o">=</span>64M <span class="nv">conv</span><span class="o">=</span>noerror
<span class="nt">--</span><span class="o">&gt;</span> Clones one partition to another.

<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/sd0 <span class="nv">of</span><span class="o">=</span>/dev/sd1 <span class="nv">bs</span><span class="o">=</span>64M <span class="nv">conv</span><span class="o">=</span>noerror
<span class="nt">--</span><span class="o">&gt;</span> Clones a hard disk drive <span class="s2">"sd0"</span> to <span class="s2">"sd1"</span><span class="nb">.</span>

<span class="nt">----------------------------X----------------------------</span>

<span class="c">### In-place modification</span>
<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/zero <span class="nv">of</span><span class="o">=</span>path/to/file <span class="nv">bs</span><span class="o">=</span>512 <span class="nv">count</span><span class="o">=</span>1 <span class="nv">conv</span><span class="o">=</span>notrunc
<span class="nt">--</span><span class="o">&gt;</span> <span class="nb">dd </span>can modify data <span class="k">in </span>place. For example, this overwrites the first 512 bytes of a file with null bytes:
<span class="nt">--</span><span class="o">&gt;</span> The notrunc conversion option means <span class="k">do </span>not <span class="nb">truncate </span>the output file,
<span class="nt">--</span><span class="o">&gt;</span> i.e. <span class="k">if </span>the output file already exists, just replace the specified bytes and leave the rest of the output file alone.
<span class="nt">--</span><span class="o">&gt;</span> Without this option, <span class="nb">dd </span>would create an output file 512 bytes long.

<span class="nt">----------------------------X----------------------------</span>

<span class="c">### Master boot record backup and restore</span>
<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/fd0 <span class="nv">of</span><span class="o">=</span>MBRboot.img <span class="nv">bs</span><span class="o">=</span>512 <span class="nv">count</span><span class="o">=</span>2
<span class="nt">--</span><span class="o">&gt;</span> The example above can also be used to back up and restore any region of a device to a file, such as a master boot record.
<span class="nt">--</span><span class="o">&gt;</span> To duplicate the first two sectors of a floppy disk.

<span class="nt">----------------------------X----------------------------</span>

<span class="c">### Disk wipe-out</span>
To write zeros to a disk, use:
<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/zero <span class="nv">of</span><span class="o">=</span>/dev/sda <span class="nv">bs</span><span class="o">=</span>16M.

To write random data to a disk, use: <span class="o">(</span>slower than above, obviously due to random numbers generation<span class="o">)</span>
<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/urandom <span class="nv">of</span><span class="o">=</span>/dev/sda <span class="nv">bs</span><span class="o">=</span>16M.

<span class="nt">----------------------------X----------------------------</span>

<span class="c">### Generating a file with random data</span>
To make a file of 100 random bytes using the kernel random driver:
<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/urandom <span class="nv">of</span><span class="o">=</span>myrandom <span class="nv">bs</span><span class="o">=</span>100 <span class="nv">count</span><span class="o">=</span>1

<span class="nt">----------------------------X----------------------------</span>

<span class="c">### Converting a file to upper case</span>
To convert a file to uppercase:
<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>filename <span class="nv">of</span><span class="o">=</span>filename1 <span class="nv">conv</span><span class="o">=</span>ucase,notrunc
</pre></td></tr></tbody></table></code></pre></figure>

<hr />

<h2 id="fdisk">fdisk:</h2>
<ul>
  <li><code class="language-plaintext highlighter-rouge">fdisk</code> also known as <em><u>format disk</u></em> is used for creating and manipulating <em><u>disk partition table</u></em>. It is used for the view, create, delete, change, resize, copy and move partitions on a hard drive.</li>
  <li>It understands <strong>GPT</strong>, <strong>MBR</strong>, <strong>Sun</strong>, <strong>SGI</strong> and <strong>BSD</strong> partition tables. Block devices can be divided into one or more logical disks called partitions. This division is recorded in the <em><u>partition table</u></em>, usually found in <em><u>sector</u></em> 0 of the disk.</li>
  <li><code class="language-plaintext highlighter-rouge">fdisk</code> allows you to create a <em><u>maximum of four </u></em><strong><em><u>primary</u></em></strong><em><u> partitions</u></em> and the <em><u>number of logical partition depends on the size of the hard disk</u></em>.</li>
  <li>It allows the user to:
    <ul>
      <li>To Create space for new partitions.</li>
      <li>Organizing space for new drives.</li>
      <li>Re-organizing old drives.</li>
      <li>Copying or Moving data to new disks(partitions).</li>
    </ul>
  </li>
  <li>Usage:
    <ul>
      <li><strong><em>View All Disk Partitions</em></strong>:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo fdisk -l
</code></pre></div>        </div>
      </li>
      <li><strong><em>View Partition on a Specific Disk</em></strong>:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo fdisk -l /dev/sda
</code></pre></div>        </div>
      </li>
      <li><strong><em>View all fdisk Commands</em></strong>:
        <ul>
          <li><code class="language-plaintext highlighter-rouge">fdisk</code> is a dialogue driven command as:
            <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo fdisk /dev/sda
</code></pre></div>            </div>
            <ul>
              <li>Create a Hard Disk Partition: <strong><em>n</em></strong></li>
              <li>Make Partition <strong>Primary</strong>: <strong><em>p</em></strong></li>
              <li>Delete a Hard Disk Partition: <strong><em>d</em></strong>
<img src="/assets/images/embedded/fdisk-options.png" alt="fdisk options" /></li>
            </ul>
          </li>
        </ul>
      </li>
      <li><strong><em>View the size of Partition</em></strong>:
        <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo fdisk -s /dev/sda
</code></pre></div>        </div>
      </li>
      <li>Further Details: <a href="https://man7.org/linux/man-pages/man8/fdisk.8.html">fdisk(8):man-page</a></li>
    </ul>
  </li>
</ul>

<hr />

<h2 id="losetup">losetup:</h2>
<ul>
  <li><code class="language-plaintext highlighter-rouge">losetup</code> is used to associate loop devices with regular files or block devices, to detach loop devices, and to query the status of a loop device.</li>
  <li><strong><em><u>Loop Devices</u></em></strong>:
    <ul>
      <li>A loop device is a pseudo-device that <em><u>makes a computer file accessible as a block device</u></em>.</li>
      <li>If the CD ISO images and floppy disk images contains an entire file system, the file may then be <em><u>mounted</u></em> as if it were a disk device.</li>
      <li>Mounting a file containing a file system via such a loop mount makes the files within that file system accessible, just like any other directories accessed with <code class="language-plaintext highlighter-rouge">ls</code>, <code class="language-plaintext highlighter-rouge">cd</code> commands. They appear in the mount point directory (/mnt).</li>
      <li>It makes it a convenient method for managing and editing file system images offline, that are later used for normal system operation.</li>
      <li>It also provides a permanent segregation of data, by means of a data partition.</li>
      <li>In Linux, these devices are called “loop” devices and device nodes are usually named <code class="language-plaintext highlighter-rouge">/dev/loop0</code>, <code class="language-plaintext highlighter-rouge">/dev/loop1</code>, etc.</li>
      <li>They can be created with <code class="language-plaintext highlighter-rouge">makedev</code> for the static device directory, dynamically by the facilities of the device file system (<code class="language-plaintext highlighter-rouge">udev</code>), or directly with <code class="language-plaintext highlighter-rouge">mknod</code>.</li>
      <li>The management user interface for the loop device is <code class="language-plaintext highlighter-rouge">losetup</code>, which is part of the package <code class="language-plaintext highlighter-rouge">util-linux</code>.</li>
      <li>
        <p>:x: A <code class="language-plaintext highlighter-rouge">loopback</code> device, term is reserved for a networking device in operating systems. The concept of the loop device is distinct.</p>
      </li>
      <li>Mounting a file containing a disk image on a directory requires two steps:
        <ul>
          <li>Association of the file with a loop device node,
            <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ losetup /dev/loop0 example.img
</code></pre></div>            </div>
          </li>
          <li>Mounting of the loop device at a mount point directory
            <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mount /dev/loop0 /home/you/dir
</code></pre></div>            </div>
          </li>
          <li>The <code class="language-plaintext highlighter-rouge">mount</code> utility is usually capable of handling the entire procedure (both above steps):
            <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mount -o loop example.img /home/you/dir
</code></pre></div>            </div>
          </li>
          <li>The device can then be unmounted with the following command:
            <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ umount /home/you/dir
$ umount /dev/loop&lt;N&gt;
</code></pre></div>            </div>
          </li>
        </ul>
      </li>
      <li><strong><em><code class="language-plaintext highlighter-rouge">/dev/null</code> vs <code class="language-plaintext highlighter-rouge">/dev/zero</code></em></strong>:
        <ul>
          <li><code class="language-plaintext highlighter-rouge">/dev/null</code> produces no output.</li>
          <li><code class="language-plaintext highlighter-rouge">/dev/zero</code> produces a continuous stream of NULL (zero value) bytes.</li>
          <li><code class="language-plaintext highlighter-rouge">/dev/zero</code> is used to create dummy files or swap.</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre><span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/null <span class="nv">of</span><span class="o">=</span>file <span class="nv">count</span><span class="o">=</span>10
0+0 records <span class="k">in
</span>0+0 records out
0 bytes <span class="o">(</span>0 B<span class="o">)</span> copied, 0.000276193 s, 0.0 kB/s

<span class="nt">----------------------------X----------------------------</span>

<span class="nv">$ </span><span class="nb">dd </span><span class="k">if</span><span class="o">=</span>/dev/zero <span class="nv">of</span><span class="o">=</span>file <span class="nv">count</span><span class="o">=</span>10
10+0 records <span class="k">in
</span>10+0 records out
5120 bytes <span class="o">(</span>5.1 kB<span class="o">)</span> copied, 0.00090775 s, 5.6 MB/s
</pre></td></tr></tbody></table></code></pre></figure>

<ul>
  <li><strong><em>Mount multiple partitions from disk image simultaneously</em></strong>:</li>
</ul>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre><span class="nv">$ </span>losetup <span class="nt">-P</span> <span class="nt">-f</span> <span class="nt">--show</span> my.img
<span class="nt">--</span><span class="o">&gt;</span> Creates one <span class="sb">`</span>/dev/loopXpY<span class="sb">`</span> per partition.

<span class="nv">$ </span><span class="nb">sudo </span>mount /dev/loop5p1 /mnt/CROS_Boot/
<span class="nv">$ </span><span class="nb">sudo </span>mount /dev/loop5p2 /mnt/CROS_imgpart2/
<span class="nv">$ </span><span class="nb">sudo </span>mount /dev/loop5p3 /mnt/CROS_imgpart3/
<span class="nv">$ </span><span class="nb">sudo </span>mount /dev/loop5p4 /mnt/CROS_imgpart4/
<span class="nt">--</span><span class="o">&gt;</span> After <span class="sb">`</span>losetup<span class="sb">`</span>, every partition needs to be mounted, before accessing it.
</pre></td></tr></tbody></table></code></pre></figure>

<hr />

<h2 id="mkfs">mkfs</h2>
<ul>
  <li><code class="language-plaintext highlighter-rouge">mkfs</code> command stands for <strong><em>make file system</em></strong> is utilized to make a file system on a formatted storage device usually, a partition on a hard disk drive (HDD) or USB drive or it can also be a loop device, etc.</li>
  <li><code class="language-plaintext highlighter-rouge">mkfs</code> is a front-end for the various specific file system creation programs that are available in Linux, such as <code class="language-plaintext highlighter-rouge">mke2fs</code>, <code class="language-plaintext highlighter-rouge">mkfs.ext4</code> and <code class="language-plaintext highlighter-rouge">mkfs.vfat</code>, etc.
<img src="/assets/images/embedded/mkfs-supported-file-types.jpeg" alt="mkfs-supported-file-types" /></li>
  <li>Use <code class="language-plaintext highlighter-rouge">fdisk</code> command to create the volume partitions and <code class="language-plaintext highlighter-rouge">losetup</code> command to mount the partition of an disk image on a loop device, if required.</li>
  <li>Formatting the new volume created as a FAT32 FS type:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo mkfs.vfat /dev/sdb1
</code></pre></div>    </div>
    <p><img src="/assets/images/embedded/mkfs-vfat-output.jpeg" alt="mkfs-vfat-output" /></p>
  </li>
  <li>Verifying the newly created filesystem:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo file -sL /dev/sdb1
</code></pre></div>    </div>
    <p><img src="/assets/images/embedded/mkfs-vfat-verification.jpeg" alt="mkfs-vfat-verification" /></p>
  </li>
</ul>

<hr />

<h2 id="mount--umount-commands">mount &amp; umount commands</h2>
<ul>
  <li>All files accessible in a Unix system are arranged in one big tree, the file hierarchy, rooted at <code class="language-plaintext highlighter-rouge">/</code>. These files can be spread out over several devices.</li>
  <li>The <code class="language-plaintext highlighter-rouge">mount</code> command serves to attach the filesystem found on some device to the big file tree.</li>
  <li>Conversely, the <code class="language-plaintext highlighter-rouge">umount(8)</code> command will detach the filesystem again.</li>
  <li>The filesystem is used to control how data is stored on the device or provided in a virtual way by network or other services.</li>
  <li>Some Important Options:
    <ul>
      <li>l : Lists all the file systems mounted yet.</li>
      <li>h : Displays options for command.</li>
      <li>V : Displays the version information.</li>
      <li>a : Mounts all devices described at /etc/fstab.</li>
      <li>t : Type of filesystem device uses.</li>
      <li>T : Describes an alternative fstab file.</li>
      <li>r : Read-only mode mounted.</li>
    </ul>
  </li>
  <li>List of <code class="language-plaintext highlighter-rouge">ext4</code> file systems mounted on a machine:
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mount -l -t ext4
/dev/sda1 on / type ext4 (rw,relatime,errors=remount-ro)
$
</code></pre></div>    </div>
  </li>
  <li>Mount file system on devices to a directory on a machine
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo mount &lt;source-device-path&gt; &lt;destination-directory-path&gt;
</code></pre></div>    </div>
  </li>
  <li>Unmount the file system
    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo umount &lt;mounted-destination-path&gt;
</code></pre></div>    </div>
  </li>
</ul>

<h6 id="references">References:</h6>
<ul>
  <li><a href="https://en.wikipedia.org/wiki/Dd_(Unix)">dd:wikipedia</a></li>
  <li><a href="https://man7.org/linux/man-pages/man1/dd.1.html">dd(1):man-page</a></li>
  <li><a href="https://man7.org/linux/man-pages/man8/fdisk.8.html">fdisk(8):man-page</a></li>
  <li><a href="https://man7.org/linux/man-pages/man8/losetup.8.html">losetup(8):man-page</a></li>
  <li><a href="https://en.wikipedia.org/wiki/Loop_device">Loop Devices: wikipedia</a></li>
  <li><a href="https://unix.stackexchange.com/q/254384/98539">Difference between <code class="language-plaintext highlighter-rouge">/dev/null</code> and <code class="language-plaintext highlighter-rouge">/dev/zero</code></a></li>
  <li><a href="https://unix.stackexchange.com/q/342463/98539">How to mount multiple partitions from disk image simultaneously?</a></li>
  <li><a href="https://www.geeksforgeeks.org/mkfs-command-in-linux-with-examples/">mkfs</a></li>
  <li><a href="https://man7.org/linux/man-pages/man8/mount.8.html">mount</a></li>
</ul>]]></content><author><name>Akhilesh Moghe</name></author><category term="Linux" /><category term="Embedded Linux" /><category term="Systems Engineering" /><category term="Linux" /><category term="Embedded Linux" /><category term="Systems Engineering" /><summary type="html"><![CDATA[In this article, we will learn the Linux Disk image creation, partioning the disk image, formatting the partitions, mounting it in order to view it’s contents. Also, we will try to understand the various commands used in this process like dd, fdisk, mkfs, etc… dd: dd is basically a command-line utility to copy a file, also convert and format as per the options specified. Now, Linux/Unix has everything as a file, weather it’s a Hardware drive like /dev/sda, USB drives like /dev/sdb or special devices like /dev/null or /dev/zero or /dev/random, all are files only, so dd command can be used for all above devices, to read from, write to i.e. copy to/from and also format them. dd can be used for tasks such as backing up the boot sector of a hard drive, and obtaining a fixed amount of random data. dd can also perform conversions on the data as it is copied, including byte order swapping and conversion to and from the ASCII and EBCDIC text encodings (option: conv=ascii/ebcdic). By default, dd reads from stdin and writes to stdout, but these can be changed by using the if (input file) and of (output file) options. On completion, dd prints to the stderr stream about statistics of the data transfer. Each of the Records in and Records out lines shows the number of complete blocks transferred + the number of partial blocks, e.g. because the physical medium ended before a complete block was read, or a physical error prevented reading the complete block. Block Size (bs): A block is a unit measuring the number of bytes that are read, written, or converted at one time. Command-line options can specify a different block size for input/reading (ibs) compared to output/writing (obs), though the block size (bs) option will override both ibs and obs. The default value for both input and output block sizes is 512 bytes (the traditional block size of disks, and POSIX-mandated size of “a block”). Block size has an effect on the performance of copying dd commands. Doing many small reads or writes is often slower than doing fewer large ones. Using large blocks requires more RAM and can complicate error recovery, also larger block sizes usually don’t really speed it up much more. Basically you should use 4M or a multiple of that as block size. Because, the organisation of SD card is such that , it erases 4M blocks in group, so partitions should be aligned on Erase Block Group, i.e. 4M boundary for efficiency. Count: The count option for copying is measured in blocks, as are both the skip count for reading and seek count for writing. Status: dd support the status=progress option, which enables periodic printing of transfer statistics to stderr. Examples: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 $ blocks=$(isosize -d 2048 /dev/sr0) $ dd if=/dev/sr0 of=isoimage.iso bs=2048 count=$blocks status=progress --&gt; Creates an ISO disk image from a CD-ROM, DVD or Blu-ray disc. $ dd if=system.img of=/dev/sdc bs=64M conv=noerror --&gt; Restores a hard disk drive (or an SD card, for example) from a previously created image. $ dd if=/dev/sdb2 of=partition.image bs=64M conv=noerror --&gt; Create an image of the partition sdb2, using a 64 MiB block size. $ dd if=/dev/sda2 of=/dev/sdb2 bs=64M conv=noerror --&gt; Clones one partition to another. $ dd if=/dev/sd0 of=/dev/sd1 bs=64M conv=noerror --&gt; Clones a hard disk drive "sd0" to "sd1". ----------------------------X---------------------------- ### In-place modification $ dd if=/dev/zero of=path/to/file bs=512 count=1 conv=notrunc --&gt; dd can modify data in place. For example, this overwrites the first 512 bytes of a file with null bytes: --&gt; The notrunc conversion option means do not truncate the output file, --&gt; i.e. if the output file already exists, just replace the specified bytes and leave the rest of the output file alone. --&gt; Without this option, dd would create an output file 512 bytes long. ----------------------------X---------------------------- ### Master boot record backup and restore $ dd if=/dev/fd0 of=MBRboot.img bs=512 count=2 --&gt; The example above can also be used to back up and restore any region of a device to a file, such as a master boot record. --&gt; To duplicate the first two sectors of a floppy disk. ----------------------------X---------------------------- ### Disk wipe-out To write zeros to a disk, use: $ dd if=/dev/zero of=/dev/sda bs=16M. To write random data to a disk, use: (slower than above, obviously due to random numbers generation) $ dd if=/dev/urandom of=/dev/sda bs=16M. ----------------------------X---------------------------- ### Generating a file with random data To make a file of 100 random bytes using the kernel random driver: $ dd if=/dev/urandom of=myrandom bs=100 count=1 ----------------------------X---------------------------- ### Converting a file to upper case To convert a file to uppercase: $ dd if=filename of=filename1 conv=ucase,notrunc fdisk: fdisk also known as format disk is used for creating and manipulating disk partition table. It is used for the view, create, delete, change, resize, copy and move partitions on a hard drive. It understands GPT, MBR, Sun, SGI and BSD partition tables. Block devices can be divided into one or more logical disks called partitions. This division is recorded in the partition table, usually found in sector 0 of the disk. fdisk allows you to create a maximum of four primary partitions and the number of logical partition depends on the size of the hard disk. It allows the user to: To Create space for new partitions. Organizing space for new drives. Re-organizing old drives. Copying or Moving data to new disks(partitions). Usage: View All Disk Partitions: $ sudo fdisk -l View Partition on a Specific Disk: $ sudo fdisk -l /dev/sda View all fdisk Commands: fdisk is a dialogue driven command as: $ sudo fdisk /dev/sda Create a Hard Disk Partition: n Make Partition Primary: p Delete a Hard Disk Partition: d View the size of Partition: $ sudo fdisk -s /dev/sda Further Details: fdisk(8):man-page losetup: losetup is used to associate loop devices with regular files or block devices, to detach loop devices, and to query the status of a loop device. Loop Devices: A loop device is a pseudo-device that makes a computer file accessible as a block device. If the CD ISO images and floppy disk images contains an entire file system, the file may then be mounted as if it were a disk device. Mounting a file containing a file system via such a loop mount makes the files within that file system accessible, just like any other directories accessed with ls, cd commands. They appear in the mount point directory (/mnt). It makes it a convenient method for managing and editing file system images offline, that are later used for normal system operation. It also provides a permanent segregation of data, by means of a data partition. In Linux, these devices are called “loop” devices and device nodes are usually named /dev/loop0, /dev/loop1, etc. They can be created with makedev for the static device directory, dynamically by the facilities of the device file system (udev), or directly with mknod. The management user interface for the loop device is losetup, which is part of the package util-linux. :x: A loopback device, term is reserved for a networking device in operating systems. The concept of the loop device is distinct. Mounting a file containing a disk image on a directory requires two steps: Association of the file with a loop device node, $ losetup /dev/loop0 example.img Mounting of the loop device at a mount point directory $ mount /dev/loop0 /home/you/dir The mount utility is usually capable of handling the entire procedure (both above steps): $ mount -o loop example.img /home/you/dir The device can then be unmounted with the following command: $ umount /home/you/dir $ umount /dev/loop&lt;N&gt; /dev/null vs /dev/zero: /dev/null produces no output. /dev/zero produces a continuous stream of NULL (zero value) bytes. /dev/zero is used to create dummy files or swap. 1 2 3 4 5 6 7 8 9 10 11 $ dd if=/dev/null of=file count=10 0+0 records in 0+0 records out 0 bytes (0 B) copied, 0.000276193 s, 0.0 kB/s ----------------------------X---------------------------- $ dd if=/dev/zero of=file count=10 10+0 records in 10+0 records out 5120 bytes (5.1 kB) copied, 0.00090775 s, 5.6 MB/s Mount multiple partitions from disk image simultaneously: 1 2 3 4 5 6 7 8 $ losetup -P -f --show my.img --&gt; Creates one `/dev/loopXpY` per partition. $ sudo mount /dev/loop5p1 /mnt/CROS_Boot/ $ sudo mount /dev/loop5p2 /mnt/CROS_imgpart2/ $ sudo mount /dev/loop5p3 /mnt/CROS_imgpart3/ $ sudo mount /dev/loop5p4 /mnt/CROS_imgpart4/ --&gt; After `losetup`, every partition needs to be mounted, before accessing it. mkfs mkfs command stands for make file system is utilized to make a file system on a formatted storage device usually, a partition on a hard disk drive (HDD) or USB drive or it can also be a loop device, etc. mkfs is a front-end for the various specific file system creation programs that are available in Linux, such as mke2fs, mkfs.ext4 and mkfs.vfat, etc. Use fdisk command to create the volume partitions and losetup command to mount the partition of an disk image on a loop device, if required. Formatting the new volume created as a FAT32 FS type: $ sudo mkfs.vfat /dev/sdb1 Verifying the newly created filesystem: $ sudo file -sL /dev/sdb1 mount &amp; umount commands All files accessible in a Unix system are arranged in one big tree, the file hierarchy, rooted at /. These files can be spread out over several devices. The mount command serves to attach the filesystem found on some device to the big file tree. Conversely, the umount(8) command will detach the filesystem again. The filesystem is used to control how data is stored on the device or provided in a virtual way by network or other services. Some Important Options: l : Lists all the file systems mounted yet. h : Displays options for command. V : Displays the version information. a : Mounts all devices described at /etc/fstab. t : Type of filesystem device uses. T : Describes an alternative fstab file. r : Read-only mode mounted. List of ext4 file systems mounted on a machine: $ mount -l -t ext4 /dev/sda1 on / type ext4 (rw,relatime,errors=remount-ro) $ Mount file system on devices to a directory on a machine $ sudo mount &lt;source-device-path&gt; &lt;destination-directory-path&gt; Unmount the file system $ sudo umount &lt;mounted-destination-path&gt; References: dd:wikipedia dd(1):man-page fdisk(8):man-page losetup(8):man-page Loop Devices: wikipedia Difference between /dev/null and /dev/zero How to mount multiple partitions from disk image simultaneously? mkfs mount]]></summary></entry><entry><title type="html">Azure Functions Overview</title><link href="https://akhileshmoghe.github.io/_posts/azure/azure-functions-overview" rel="alternate" type="text/html" title="Azure Functions Overview" /><published>2022-04-12T12:33:22+05:30</published><updated>2022-04-12T12:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_posts/azure/Azure-Functions-Overview</id><content type="html" xml:base="https://akhileshmoghe.github.io/_posts/azure/azure-functions-overview"><![CDATA[<ul>
  <li><strong><em><u>Azure Functions</u></em></strong> for IoT enable developers to create scalable IoT applications that can be rapidly deployed without provisioning a fixed infrastructure capacity in advance.</li>
  <li>IoT solutions especially benefit from the ability to scale infrastructure using Azure Functions.</li>
  <li>Azure Functions is a part of the Azure serverless solution. Azure Serverless solution comprises of three elements:
    <ul>
      <li>Serverless Kubernetes</li>
      <li>Serverless functions</li>
      <li>Serverless application environments</li>
    </ul>
  </li>
</ul>

<h2 id="function-app">Function App</h2>
<ul>
  <li>Azure Functions are hosted in an execution context called a <strong>function app</strong>.</li>
  <li>You define function apps to <em><u>logically group and structure your functions and a compute resource</u></em> in Azure.</li>
  <li>There are a few decisions that need to be made to create the function app; you need to choose a service plan and select a compatible storage account.</li>
  <li><strong><em><u>Service plan</u></em></strong>
    <ul>
      <li>Function apps may use one of two types of service plans:</li>
      <li><strong><em>Consumption plan</em></strong>:
        <ul>
          <li>When using the Azure serverless application platform, choose the Consumption plan.</li>
          <li>This plan provides <em><u>automatic scaling*</u></em> and bills you only when your functions are running.</li>
          <li>The Consumption plan comes with a <em><u>configurable timeout period for executing a function</u></em>. By default, it’s <strong><em><u>five (5) minutes</u></em></strong>, but may be configured to have a timeout as long as <strong><em>10 minutes</em></strong>.</li>
        </ul>
      </li>
      <li><strong><em>Azure App Service plan</em></strong>:
        <ul>
          <li>The Azure App Service plan enables you to <em><u>avoid timeout periods</u></em> by having your <em><u>function run continuously on a VM that you define</u></em>.</li>
          <li>When using an App Service plan, <em><u>you are responsible for managing the app resources the function runs on</u></em>, so this is technically not a serverless plan.</li>
          <li>It may be a better choice if your functions are used continuously, or if your functions require more processing power or longer execution time than the Consumption plan can provide.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li><strong><em><u>Storage account</u></em></strong> requirements:
    <ul>
      <li>When you create <em><u>a function app, it must be linked to a storage account</u></em>.</li>
      <li>The function app uses this storage account for internal operations, such as <em><u>logging function executions</u></em> and <em><u>managing execution triggers</u></em>.</li>
      <li>On the Consumption plan, this is also where the <em><u>function code and configuration file are stored</u></em>.</li>
    </ul>
  </li>
</ul>

<h2 id="triggers-and-bindings-in-azure-functions">Triggers and Bindings in Azure Functions:</h2>
<ul>
  <li>An Azure function has two parts:
    <ul>
      <li><strong><em>Triggers</em></strong>:
        <ul>
          <li>A function has a specific <em><u>single trigger</u></em>.</li>
          <li>The trigger <em><u>invokes the function</u></em>.</li>
          <li>Triggers <em><u>provide data</u></em> needed by the function.</li>
          <li>Templates for Azure function triggers:
            <ul>
              <li><strong>HTTP Trigger</strong>: When you want the code to execute in response to <em><u>a request sent through the HTTP protocol</u></em>.</li>
              <li><strong>Timer Trigger</strong>: When you want the code to execute according to a <em><u>schedule</u></em>.</li>
              <li><strong>Blob Trigger</strong>: When you want the code to execute when <em><u>a new blob is added to an </u></em><strong><em><u>Azure Storage account</u></em></strong>.</li>
              <li><strong>CosmosDB Trigger</strong>: When you want the code to execute in response to <em><u>new or updated documents in a NoSQL database</u></em>.</li>
              <li><strong><em>Event Grid Trigger</em></strong>:	Starts a function when an event is received from Event Grid.</li>
              <li><strong><em>Queue Storage Trigger</em></strong>: Starts a function when <em><u>a new item is received on a queue</u></em>. The <em><u>queue message is provided as input</u></em> to the function.</li>
              <li><strong><em>Service Bus Trigger</em></strong>: Starts a function in response to messages from a Service Bus queue.</li>
              <li><strong><em>Microsoft Graph Events Trigger</em></strong>:	Starts a function in response to an <em><u>incoming webhook from the Microsoft Graph</u></em>. Each instance of this trigger can react to one Microsoft Graph resource type.</li>
            </ul>
          </li>
        </ul>
      </li>
      <li><strong><em>Bindings</em></strong>:
        <ul>
          <li>A trigger is a type of input binding that has the ability to initiate execution of some code.</li>
          <li>Bindings connect Azure resources to the Azure functions.</li>
          <li>Data from bindings is provided to the function as parameters.</li>
          <li>Bindings interact with various data sources, which means <em><u>you don't have to write the code in your function to connect to data sources and manage connections</u></em>. The platform takes care of that complexity for you as part of the binding code.</li>
          <li>Each binding has a direction, you could have input and output bindings for a function. Your code reads data from input bindings, and writes data to output bindings.</li>
          <li>You can mix and match different bindings to suit your needs.</li>
          <li>Bindings are optional and a function might have zero or multiple input and/or output bindings.</li>
          <li>Triggers and bindings help you to avoid hardcoding access to other services.</li>
        </ul>
      </li>
      <li>Further details:
        <ul>
          <li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings?tabs=csharp#supported-bindings">Supported Bindings for various Azure services</a></li>
          <li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings">Azure Functions triggers and bindings concepts</a></li>
          <li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings?tabs=python#bindings-code-examples">Bindings code examples</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h2 id="example-scenario-for-azure-functions-for-iot">Example Scenario for Azure Functions for IoT</h2>
<object data="/assets/docs/azure/azure-functions/Azure_Functions_IoT_Usecase.pdf" type="application/pdf" width="850px" height="1000px">
  <embed src="/assets/docs/azure/azure-functions/Azure_Functions_IoT_Usecase.pdf" />
      <p>This browser does not support PDFs. Please download the PDF to view it: <a href="/assets/docs/azure/azure-functions/Azure_Functions_IoT_Usecase.pdf">Download PDF</a>.</p>
  &lt;/embed&gt;
</object>

<h2 id="considerations-for-azure-function-in-iot-solution">Considerations for Azure Function in IoT Solution</h2>
<ul>
  <li>Using the serverless computing approach, you can <em><u>focus on the core logic</u></em> of your solutions. You <em><u>avoid the need to manage the underlying infrastructure</u></em> that runs your solution. In the serverless application model, the cloud service provider automatically provisions, scales, and manages the underlying infrastructure required to run the code.</li>
  <li>The serverless model has two aspects: <strong><em>function as a service</em></strong> and <strong><em>backend as a service</em></strong>.
    <ul>
      <li>Developers write the application as functions. Typically, these <em><u>functions are </u></em><strong><em><u>stateless</u></em></strong> and <strong><em><u>short-lived</u></em></strong>.</li>
      <li>Azure functions enable you to <strong><em><u>chain your functions</u></em></strong><em><u> to create the complete solution</u></em>. Hence, as a developer, you’re concerned only with writing functions that interact with each other to solve the business problem.</li>
      <li>Cloud service provider manages these deployed functions from the perspective of resources like processors, storage, and bandwidth (backend as a service). The resources are provided on an ‘as-needed’ basis and scaled as required.</li>
      <li>You (the developer) are <em><u>charged</u></em> for the function <em><u>only when the function is actually running</u></em> (function as service).</li>
    </ul>
  </li>
  <li>IoT applications suit many of these characteristics. In the case of IoT applications, you can create a larger application by amalgamating/chaining many functions and scaling them dynamically as needed.</li>
</ul>

<h3 id="merits-of-using-azure-functions-for-iot-solutions">Merits of using Azure Functions for IoT solutions:</h3>
<ul>
  <li>Scalable applications where you’re charged only for the resources you use.</li>
  <li>Your solution can <em><u>scale up or down dynamically and instantly</u></em> depending on the business requirements. Ddon’t have to manage the infrastructure and to allocate the resources in advance.</li>
  <li><em><u>Faster time to market</u></em></li>
  <li><em><u>Flexibility to use multiple programming languages</u></em></li>
  <li>Internet of Things solutions are typically <strong><em>event driven</em></strong> that is, you need to define a specific trigger that causes the function to run.</li>
  <li>If your IoT solution could potentially scale from a small number of devices to millions of devices – you should consider Azure Functions.</li>
  <li>Similarly, if your solution could see spikes of events to millions of events, you should consider Azure functions.</li>
</ul>

<h3 id="constraints-of-azure-functions-to-consider">Constraints of Azure Functions to consider:</h3>
<ul>
  <li><strong><em>Execution time</em></strong>:
    <ul>
      <li>By default, <em><u>functions have a timeout of </u></em><strong><em><u>five (5) minutes</u></em></strong>. This timeout is configurable to a <strong><em><u>maximum of 10 minutes</u></em></strong>.</li>
      <li>If your function requires more than 10 minutes to execute, you can host it on a VM.</li>
      <li>:x: Additionally, if your <em><u>service is initiated through an HTTP request</u></em> and you expect that value as an HTTP response, the timeout is further restricted to <strong><em>2.5 minutes</em></strong>.</li>
      <li>:heavy_check_mark: But, there’s also an option called <a href="https://docs.microsoft.com/en-us/azure/azure-functions/durable/">Durable Functions</a> that enables you to <em><u>orchestrate the executions of multiple functions without any timeout</u></em>.</li>
    </ul>
  </li>
  <li><strong><em>Execution frequency</em></strong>:
    <ul>
      <li>If you expect your <em><u>function to be executed continuously by multiple clients</u></em>, it would be prudent/sensible to estimate the usage and calculate the cost of using functions accordingly. It <em><u>might be cheaper to host your service on a VM</u></em>.</li>
      <li>:x: While scaling, <strong><em><u>only one function app instance</u></em></strong> can be created <strong><em><u>every 10 seconds</u></em></strong>, for <strong><em><u>up to 200 total instances</u></em></strong>.
        <ul>
          <li>Keep in mind, <em><u>each instance can service multiple concurrent executions</u></em>, so there’s no set limit about how much traffic a single instance can handle.</li>
        </ul>
      </li>
      <li><em><u>Different types of triggers have different scaling requirements</u></em>, so research your choice of trigger and investigate its limits.</li>
    </ul>
  </li>
</ul>

<h3 id="programming-language-support-with-azure-functions">Programming Language support with Azure Functions</h3>
<ul>
  <li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/supported-languages#languages-by-runtime-version">Languages by runtime version</a>
    <ul>
      <li>Supported: Python, JavaScript, C#, Java, PowerShell, TypeScript</li>
    </ul>
  </li>
  <li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/supported-languages#language-support-details">Azure Functions runtime constraints</a>
    <ul>
      <li>Whether Azure function runtime is supported on <strong>Linux</strong> or <strong>Windows</strong>.</li>
      <li>Whether <em><u>in-portal editing</u></em> is supported for the runtime or not.</li>
    </ul>
  </li>
  <li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/supported-languages#custom-handlers">Custom Handlers</a>
    <ul>
      <li>Custom handlers are lightweight web servers that receive events from the Azure Functions host.</li>
      <li>Any language that supports HTTP primitives can implement a custom handler.</li>
      <li>:heavy_check_mark: This means that custom handlers can be used to create functions in languages that aren’t officially supported.</li>
    </ul>
  </li>
</ul>

<h2 id="best-practice-guidelines-for-azure-functions">Best practice guidelines for Azure Functions</h2>
<ul>
  <li><strong><em>Avoid long running functions</em></strong>:
    <ul>
      <li>Large, long-running functions can cause unexpected <em><u>timeout issues</u></em>.</li>
    </ul>
  </li>
  <li><strong><em>Write functions to be stateless</em></strong>:
    <ul>
      <li>Functions should be <strong><em>stateless</em></strong> and <strong><em>idempotent</em></strong> if possible.</li>
      <li>Idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. For example, the number 1 is idempotent with respect to the multiplication operation because 1 x 1 = 1.</li>
      <li>Associate any required state information with your data.</li>
      <li>It’s possible to achieve <strong><em>cross function communication</em></strong> using <a href="https://docs.microsoft.com/en-us/azure/azure-functions/durable/">Durable Functions</a> and <a href="####">Azure Logic Apps</a> that <em><u>manage state transitions</u></em> and <em><u>communication between multiple functions</u></em>.</li>
    </ul>
  </li>
  <li><strong><em>Write defensive functions</em></strong>:
    <ul>
      <li>Design your functions with the <em><u>ability to continue from a previous fail point during the next execution</u></em>.</li>
    </ul>
  </li>
  <li><strong><em>Scalability best practices</em></strong>:
    <ul>
      <li>Share and manage connections</li>
      <li>Avoid sharing storage accounts</li>
      <li>Manage function memory usage</li>
    </ul>
  </li>
</ul>

<h2 id="durable-functions">Durable Functions:</h2>
<ul>
  <li>Durable Functions is an extension of <strong><em>Azure Functions</em></strong> that lets you write <em><u>stateful functions</u></em> in a serverless compute environment.</li>
  <li>The extension lets you define stateful workflows by writing <a href="https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-orchestrations?tabs=python">orchestrator functions</a> and stateful entities by writing <a href="https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-entities?tabs=python">entity functions</a> using the Azure Functions programming model. Behind the scenes, the extension manages state, checkpoints, and restarts for you, allowing you to focus on your business logic.</li>
</ul>

<h3 id="durable-orchestration-functions">Durable Orchestration Functions</h3>
<ul>
  <li>Durable Functions is an extension of Azure Functions. You can use an orchestrator function <em><u>to orchestrate the execution of other Durable functions</u></em> within a function app. Orchestrator functions have the following characteristics:
    <ul>
      <li>Orchestrator functions define function workflows using <em><u>procedural code</u></em>. No declarative schemas or designers are needed.</li>
      <li>Orchestrator functions can <em><u>call other durable functions </u></em><strong><em><u>synchronously and asynchronously</u></em></strong>. Output from called functions can be reliably saved to local variables.</li>
      <li>Orchestrator functions are durable and reliable. <em><u>Execution progress is automatically checkpointed when the function "awaits" or "yields"</u></em>. <em><u>Local state is never lost when the process recycles or the VM reboots</u></em>.</li>
      <li>Orchestrator functions can be <em><u>long-running</u></em>. The total lifespan of an orchestration instance can be <em><u>seconds, days, months, or never-ending</u></em>.</li>
    </ul>
  </li>
</ul>

<h3 id="entity-functions">Entity Functions</h3>
<ul>
  <li>Entity functions define operations for <em><u>reading and updating small pieces of state</u></em>, known as <strong><em>durable entities</em></strong>.</li>
  <li>Like orchestrator functions, entity functions are functions with <em><u>a special trigger type</u></em>, the <strong><em>entity trigger</em></strong>.</li>
  <li>Unlike orchestrator functions, entity functions <em><u>manage the state of an entity explicitly</u></em>, rather than implicitly representing state via control flow.</li>
  <li>Entities provide a means for scaling out applications by distributing the work across many entities, each with a modestly sized state.</li>
</ul>]]></content><author><name>Akhilesh Moghe</name></author><category term="Cloud Computing" /><category term="Azure" /><category term="Serverless" /><category term="Cloud Computing" /><category term="Azure" /><category term="Serverless" /><summary type="html"><![CDATA[Azure Functions for IoT enable developers to create scalable IoT applications that can be rapidly deployed without provisioning a fixed infrastructure capacity in advance. IoT solutions especially benefit from the ability to scale infrastructure using Azure Functions. Azure Functions is a part of the Azure serverless solution. Azure Serverless solution comprises of three elements: Serverless Kubernetes Serverless functions Serverless application environments Function App Azure Functions are hosted in an execution context called a function app. You define function apps to logically group and structure your functions and a compute resource in Azure. There are a few decisions that need to be made to create the function app; you need to choose a service plan and select a compatible storage account. Service plan Function apps may use one of two types of service plans: Consumption plan: When using the Azure serverless application platform, choose the Consumption plan. This plan provides automatic scaling* and bills you only when your functions are running. The Consumption plan comes with a configurable timeout period for executing a function. By default, it’s five (5) minutes, but may be configured to have a timeout as long as 10 minutes. Azure App Service plan: The Azure App Service plan enables you to avoid timeout periods by having your function run continuously on a VM that you define. When using an App Service plan, you are responsible for managing the app resources the function runs on, so this is technically not a serverless plan. It may be a better choice if your functions are used continuously, or if your functions require more processing power or longer execution time than the Consumption plan can provide. Storage account requirements: When you create a function app, it must be linked to a storage account. The function app uses this storage account for internal operations, such as logging function executions and managing execution triggers. On the Consumption plan, this is also where the function code and configuration file are stored. Triggers and Bindings in Azure Functions: An Azure function has two parts: Triggers: A function has a specific single trigger. The trigger invokes the function. Triggers provide data needed by the function. Templates for Azure function triggers: HTTP Trigger: When you want the code to execute in response to a request sent through the HTTP protocol. Timer Trigger: When you want the code to execute according to a schedule. Blob Trigger: When you want the code to execute when a new blob is added to an Azure Storage account. CosmosDB Trigger: When you want the code to execute in response to new or updated documents in a NoSQL database. Event Grid Trigger: Starts a function when an event is received from Event Grid. Queue Storage Trigger: Starts a function when a new item is received on a queue. The queue message is provided as input to the function. Service Bus Trigger: Starts a function in response to messages from a Service Bus queue. Microsoft Graph Events Trigger: Starts a function in response to an incoming webhook from the Microsoft Graph. Each instance of this trigger can react to one Microsoft Graph resource type. Bindings: A trigger is a type of input binding that has the ability to initiate execution of some code. Bindings connect Azure resources to the Azure functions. Data from bindings is provided to the function as parameters. Bindings interact with various data sources, which means you don't have to write the code in your function to connect to data sources and manage connections. The platform takes care of that complexity for you as part of the binding code. Each binding has a direction, you could have input and output bindings for a function. Your code reads data from input bindings, and writes data to output bindings. You can mix and match different bindings to suit your needs. Bindings are optional and a function might have zero or multiple input and/or output bindings. Triggers and bindings help you to avoid hardcoding access to other services. Further details: Supported Bindings for various Azure services Azure Functions triggers and bindings concepts Bindings code examples Example Scenario for Azure Functions for IoT This browser does not support PDFs. Please download the PDF to view it: Download PDF. &lt;/embed&gt; Considerations for Azure Function in IoT Solution Using the serverless computing approach, you can focus on the core logic of your solutions. You avoid the need to manage the underlying infrastructure that runs your solution. In the serverless application model, the cloud service provider automatically provisions, scales, and manages the underlying infrastructure required to run the code. The serverless model has two aspects: function as a service and backend as a service. Developers write the application as functions. Typically, these functions are stateless and short-lived. Azure functions enable you to chain your functions to create the complete solution. Hence, as a developer, you’re concerned only with writing functions that interact with each other to solve the business problem. Cloud service provider manages these deployed functions from the perspective of resources like processors, storage, and bandwidth (backend as a service). The resources are provided on an ‘as-needed’ basis and scaled as required. You (the developer) are charged for the function only when the function is actually running (function as service). IoT applications suit many of these characteristics. In the case of IoT applications, you can create a larger application by amalgamating/chaining many functions and scaling them dynamically as needed. Merits of using Azure Functions for IoT solutions: Scalable applications where you’re charged only for the resources you use. Your solution can scale up or down dynamically and instantly depending on the business requirements. Ddon’t have to manage the infrastructure and to allocate the resources in advance. Faster time to market Flexibility to use multiple programming languages Internet of Things solutions are typically event driven that is, you need to define a specific trigger that causes the function to run. If your IoT solution could potentially scale from a small number of devices to millions of devices – you should consider Azure Functions. Similarly, if your solution could see spikes of events to millions of events, you should consider Azure functions. Constraints of Azure Functions to consider: Execution time: By default, functions have a timeout of five (5) minutes. This timeout is configurable to a maximum of 10 minutes. If your function requires more than 10 minutes to execute, you can host it on a VM. :x: Additionally, if your service is initiated through an HTTP request and you expect that value as an HTTP response, the timeout is further restricted to 2.5 minutes. :heavy_check_mark: But, there’s also an option called Durable Functions that enables you to orchestrate the executions of multiple functions without any timeout. Execution frequency: If you expect your function to be executed continuously by multiple clients, it would be prudent/sensible to estimate the usage and calculate the cost of using functions accordingly. It might be cheaper to host your service on a VM. :x: While scaling, only one function app instance can be created every 10 seconds, for up to 200 total instances. Keep in mind, each instance can service multiple concurrent executions, so there’s no set limit about how much traffic a single instance can handle. Different types of triggers have different scaling requirements, so research your choice of trigger and investigate its limits. Programming Language support with Azure Functions Languages by runtime version Supported: Python, JavaScript, C#, Java, PowerShell, TypeScript Azure Functions runtime constraints Whether Azure function runtime is supported on Linux or Windows. Whether in-portal editing is supported for the runtime or not. Custom Handlers Custom handlers are lightweight web servers that receive events from the Azure Functions host. Any language that supports HTTP primitives can implement a custom handler. :heavy_check_mark: This means that custom handlers can be used to create functions in languages that aren’t officially supported. Best practice guidelines for Azure Functions Avoid long running functions: Large, long-running functions can cause unexpected timeout issues. Write functions to be stateless: Functions should be stateless and idempotent if possible. Idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application. For example, the number 1 is idempotent with respect to the multiplication operation because 1 x 1 = 1. Associate any required state information with your data. It’s possible to achieve cross function communication using Durable Functions and Azure Logic Apps that manage state transitions and communication between multiple functions. Write defensive functions: Design your functions with the ability to continue from a previous fail point during the next execution. Scalability best practices: Share and manage connections Avoid sharing storage accounts Manage function memory usage Durable Functions: Durable Functions is an extension of Azure Functions that lets you write stateful functions in a serverless compute environment. The extension lets you define stateful workflows by writing orchestrator functions and stateful entities by writing entity functions using the Azure Functions programming model. Behind the scenes, the extension manages state, checkpoints, and restarts for you, allowing you to focus on your business logic. Durable Orchestration Functions Durable Functions is an extension of Azure Functions. You can use an orchestrator function to orchestrate the execution of other Durable functions within a function app. Orchestrator functions have the following characteristics: Orchestrator functions define function workflows using procedural code. No declarative schemas or designers are needed. Orchestrator functions can call other durable functions synchronously and asynchronously. Output from called functions can be reliably saved to local variables. Orchestrator functions are durable and reliable. Execution progress is automatically checkpointed when the function "awaits" or "yields". Local state is never lost when the process recycles or the VM reboots. Orchestrator functions can be long-running. The total lifespan of an orchestration instance can be seconds, days, months, or never-ending. Entity Functions Entity functions define operations for reading and updating small pieces of state, known as durable entities. Like orchestrator functions, entity functions are functions with a special trigger type, the entity trigger. Unlike orchestrator functions, entity functions manage the state of an entity explicitly, rather than implicitly representing state via control flow. Entities provide a means for scaling out applications by distributing the work across many entities, each with a modestly sized state.]]></summary></entry><entry><title type="html">AI on Jetson Nano</title><link href="https://akhileshmoghe.github.io/_post/ml_ai_dl/ai_on_jetson_nano" rel="alternate" type="text/html" title="AI on Jetson Nano" /><published>2022-03-14T01:33:22+05:30</published><updated>2022-03-14T01:33:22+05:30</updated><id>https://akhileshmoghe.github.io/_post/ml_ai_dl/AI-On-Jetson-Nano</id><content type="html" xml:base="https://akhileshmoghe.github.io/_post/ml_ai_dl/ai_on_jetson_nano"><![CDATA[<h2 id="ai-and-deep-learning-evolution">AI and Deep Learning Evolution</h2>
<ul>
  <li>As humans, we generalize what we see based on our experience. In a similar way, we can use a branch of AI called <strong><em>Machine Learning</em></strong> to generalize and <em><u>classify images</u></em> based on experience in the form of lots of example data.</li>
  <li>In particular, we will use deep neural network models, or <strong><em>Deep Learning</em></strong> to recognize relevant patterns in an image dataset, and ultimately match new images to correct answers.
<img src="/assets/images/ml_ai_dl/ai-ml-dl-evolution.png" alt="ai-ml-dl-evolution" /></li>
</ul>

<h2 id="deep-learning-models">Deep Learning Models</h2>
<ul>
  <li>A Deep Learning model consists of a <em><u>neural network</u></em> with internal parameters, or <strong><em><u>weights</u></em></strong>, configured to map inputs to outputs. In <a href=""><em><u>Image Classification</u></em></a>, the inputs are the pixels from a camera image and the outputs are the possible categories, or <strong><em><u>classes</u></em></strong> that the model is trained to recognize. The choices might be 1000 different objects, or only two. Multiple labeled examples must be provided to the model over and over to <strong><em><u>train</u></em></strong> it to recognize the images. Once the model is trained, it can be run on live data and provide results in real time. This is called <strong><em><u>inference</u></em></strong>.</li>
  <li>Before training, the model cannot accurately determine the correct class from an image input, because the weights are wrong.</li>
  <li>Labeled examples of images are iteratively submitted to the network with a learning algorithm. If the network gets the “wrong” answer (the label doesn’t match), the learning algorithm adjusts the weights a little bit. Each iteration of training is supposed to improve the model’s performance, it is termed as <strong><em><u>epoch</u></em></strong>.</li>
  <li>Over many computationally intensive iterations, the accuracy improves to the point that the model can reliably determine the class for an input image.
<img src="/assets/images/ml_ai_dl/dl/ai_difference_between_deep_learning_training_inference.jpg" alt="ai_difference_between_deep_learning_training_inference" /></li>
</ul>

<h2 id="convolutional-neural-networks-cnns-overview">Convolutional Neural Networks (CNNs) Overview</h2>
<ul>
  <li>Deep learning relies on <a href="https://developer.nvidia.com/discover/convolutional-neural-network">Convolutional Neural Network (CNN)</a> models to transform images into predicted classifications. A CNN is a class of <a href="https://developer.nvidia.com/discover/artificial-neural-network">artificial neural network</a> that uses convolutional layers to filter inputs for useful information, and is the preferred network for image applications.</li>
  <li>An artificial neural network is a computational model. At each layer, the network transforms input data by applying a <em><u>nonlinear function</u></em> to a weighted sum of the inputs. The intermediate outputs of one layer, called <em><u>features</u></em>, are used as the input into the next layer. The neural network, through repeated <em><u>transformations</u></em>, learns multiple layers of <em><u>nonlinear features (like edges and shapes)</u></em>, which it then combines in a final layer to create a prediction (of more complex objects).</li>
  <li>The convolution operation specific to CNNs combines the <em><u>input data (feature map)</u></em> from one layer with a <a href="https://developer.nvidia.com/discover/convolution"><em><u>convolution</u></em></a><em><u> kernel (filter)</u></em> to form a transformed feature map for the next layer.</li>
  <li>CNNs for <em><u>image classification</u></em> are generally composed of an input layer (the image), a series of hidden layers for feature extraction (the convolutions), and a <em><u>fully connected output layer (the classification)</u></em>.
<img src="/assets/images/ml_ai_dl/dl/convolutional_neural_network.png" alt="convolutional_neural_network" /></li>
  <li>As it is trained, the CNN adjusts automatically to find the most relevant features based on its classification requirements.
    <ul>
      <li>For example, a CNN would filter information about the <em><u>shape of an object</u></em> when confronted with a general object recognition task but would <em><u>extract the color of the bird</u></em> when faced with a bird recognition task. This is based on the CNN’s recognition through training that different classes of objects have different shapes but that different types of birds are more likely to differ in color than in shape.</li>
    </ul>
  </li>
</ul>

<h2 id="transfer-learning">Transfer Learning:</h2>
<ul>
  <li>The Transfer Learning a deep learning technique <em><u>enables developers to harness a neural network used for one task and apply it to another domain</u></em>.</li>
  <li>For Example, take image recognition. Let’s say that you want to identify horses, but there aren’t any publicly available algorithms that do an adequate job. With transfer learning, you begin with an existing convolutional neural network commonly used for image recognition of other animals, and you tweak it to train with horses.
    <ul>
      <li>Developers might start with <strong><em>ResNet-50</em></strong> — a pre-trained deep learning model consisting of <em><u>50 layers</u></em> — because it has a high accuracy level for identifying cats or dogs. Within the neural network are layers that are used to identify outlines, curves, lines and other identifying features of these animals. The layers required a lot of labeled training data, so using them saves a lot of time. Those layers can be applied to the task of carrying out the same identification on some horse features. You might be able to identify eyes, ears, legs and outlines of horses with ResNet-50, but to determine it was a horse and not a dog might require some additional training data. And with additional training by feeding labeled training data for horses — more horse-specific features can be built into the model.</li>
    </ul>
  </li>
  <li><em><u>How it works</u></em>:
    <ul>
      <li>First, you delete what’s known as the “<em><u>loss output</u></em>” layer, which is the final layer used to make predictions, and replace it with a new loss output layer for horse prediction. This loss output layer is a fine-tuning node for determining how training penalizes deviations from the labeled data and the predicted output.</li>
      <li>Next, you would take your smaller dataset for horses and train it on the entire 50-layer neural network or the last few layers or just the loss layer alone. By applying these transfer learning techniques, your output on the new CNN will be horse identification.</li>
    </ul>
  </li>
  <li>Transfer learning isn’t just for image recognition. <a href="https://blogs.nvidia.com/blog/2018/09/05/whats-the-difference-between-a-cnn-and-an-rnn/">Recurrent neural networks</a>, often used in speech recognition, can take advantage of transfer learning, as well. However, you’ll need two similar speech-related datasets, such as a million hours of speech from a pre-existing model and 10 hours of speech specific to the new task.
    <ul>
      <li>Baidu’s Deep Speech neural network offers a jump start for speech-to-text models, for example, allowing an opportunity to use transfer learning to bake in special speech features.</li>
    </ul>
  </li>
  <li><em><u>Why &amp; When to use Transfer Learning</u></em>:
    <ul>
      <li>Transfer learning is useful when you have insufficient data for a new domain you want handled by a neural network and there is a big pre-existing data pool that can be transferred to your problem.</li>
      <li>So you might have only 1,000 images of horses, but by tapping into an existing CNN such as ResNet, trained with more than 1 million images, you can gain a lot of low-level and mid-level feature definitions.</li>
    </ul>
  </li>
  <li><a href="https://developer.nvidia.com/tao-toolkit">NVIDIA TAO Toolkit</a>:
    <ul>
      <li>For developers and data scientists interested in accelerating their AI training workflow with transfer learning capabilities, the NVIDIA TAO Toolkit offers GPU-accelerated pre-trained models and functions to fine-tune your model for various domains such as intelligent video analytics and medical imaging.</li>
    </ul>
  </li>
</ul>

<h2 id="resnet-residual-networks">ResNet (Residual Networks)</h2>
<ul>
  <li>There are a number of world-class CNN architectures available to application developers for <em><u>image classification</u></em> and <em><u>image regression</u></em>.</li>
  <li><strong><em><u>PyTorch</u></em></strong> and other frameworks include access to pretrained models from past winners of the famous <strong><em>Imagenet Large Scale Visual Recognition Challenge (ILSVRC)</em></strong>, where researchers compete to correctly classify and detect objects and scenes with computer vision algorithms.</li>
  <li>In 2015, <strong><em><u>ResNet</u></em></strong><em><u> swept the awards in image classification, detection, and localization</u></em>.</li>
  <li>ResNet is a residual network, made with building blocks that incorporate “shortcut connections” that skip one or more layers.
<img src="/assets/images/ml_ai_dl/dl/resnet-18_residual.png" alt="resnet-18_residual" /></li>
  <li>The shortcut output is added to the outputs of the skipped layers. The authors of <a href="https://arxiv.org/pdf/1512.03385.pdf">Deep Residual Learning for Image Recognition</a> demonstrate that this technique makes the network easier to optimize, and have higher accuracy gains at greatly increased depths.</li>
  <li>The ResNet architectures presented <em><u>range from 18-layers deep, all the way to 152-layers deep</u></em>! The smallest network, ResNet-18 provides a good balance of performance and efficiency sized well for the Jetson Nano.</li>
  <li><strong><em><u>PyTorch</u></em></strong> includes a pre-trained ResNet-18 model that was trained on the <a href="http://image-net.org/challenges/LSVRC/2012/browse-synsets">ImageNet 2012 classification dataset</a>, which consists of 1000 classes. In other words, the model can recognize 1000 different objects already! Within the trained neural network are layers that find outlines, curves, lines, and other identifying features of an image. Important image features that were already learned in the original training of the model are now re-usable for our own classification task.</li>
  <li>The <em><u>last layer for ResNet-18 is a </u></em><strong><em><u>fully connected (fc) layer</u></em></strong>, pooled and flattened to 512 inputs, each connected to the 1000 possible output classes.</li>
</ul>

<h2 id="classification-vs-regression">Classification Vs. Regression:</h2>
<ul>
  <li>Unlike <strong><em>Image Classification</em></strong> applications, which map image inputs to <strong><em>discrete</em></strong> outputs (classes), the <strong><em>Image Regression</em></strong> task maps the image input pixels to <strong><em>continuous</em></strong> outputs.</li>
  <li>Continuous outputs can be the X and Y coordinates of various features on a face, such as a nose. Mapping an image stream to a location for <em><u>tracking</u></em> can be used in other applications, such as <em><u>following a line in mobile robotics</u></em>.</li>
  <li>Tracking isn’t the only thing a Regression model can do though. The output values could be something quite different such as steering values, or camera movement parameters.</li>
  <li><em><u>Evaluation</u></em>:
    <ul>
      <li>Classification and Regression also differ in the way they are evaluated.</li>
      <li>The discrete values of <strong><em>classification</em></strong> can be evaluated based on accuracy, i.e. a <strong><em>calculation of the percentage</em></strong> of “right” answers.</li>
      <li>In the case of <strong><em>regression</em></strong>, we are interested in getting as close as possible to a correct answer. Therefore, the <strong><em>root mean squared error</em></strong> can be used.</li>
    </ul>
  </li>
</ul>

<hr />

<h6 id="further-references">Further References:</h6>
<ul>
  <li><a href="https://developer.nvidia.com/discover/artificial-neural-network">Artificial Neural Network</a>
    <ul>
      <li>Explains: Neural Networks terms like: Neurons/Nodes, Unit, Activation Function, Layers</li>
    </ul>
  </li>
  <li><a href="https://developer.nvidia.com/cudnn">NVIDIA cuDNN</a>
    <ul>
      <li>The NVIDIA CUDA® Deep Neural Network library (cuDNN) is a GPU-accelerated library of primitives for deep neural networks. cuDNN provides highly tuned implementations for standard routines such as forward and backward convolution, pooling, normalization, and activation layers.</li>
      <li>cuDNN accelerates widely used deep learning frameworks, including Caffe2, Chainer, Keras, MATLAB, MxNet, PaddlePaddle, PyTorch, and TensorFlow.</li>
    </ul>
  </li>
  <li><a href="https://developer.nvidia.com/tensorrt">NVIDIA TensorRT</a>
    <ul>
      <li>TensorRT-based applications perform up to 40X faster than CPU-only platforms during inference. With TensorRT, you can optimize neural network models trained in all major frameworks, calibrate for lower precision with high accuracy.</li>
      <li>TensorRT is built on CUDA®, NVIDIA’s parallel programming model, and enables you to optimize inference leveraging libraries.</li>
      <li>TensorRT provides optimizations for production deployments of deep learning inference applications such as video streaming, speech recognition, recommendation, fraud detection, text generation, and natural language processing.</li>
      <li><a href="https://forums.developer.nvidia.com/t/tensorrt-vs-cudnn/155931">TensorRT internally use cuDNN for inference but with some extension.</a>
        <ul>
          <li>cuDNN is a operation level API and user will need to convert the model layer by layer.</li>
          <li>TensorRT provide several parsers and can support most public dnn model format directly.</li>
        </ul>
      </li>
      <li><a href="https://aws.amazon.com/blogs/machine-learning/amazon-sagemaker-neo-makes-it-easier-to-get-faster-inference-for-more-ml-models-with-nvidia-tensorrt/">Amazon SageMaker Neo makes it easier to get faster inference for more ML models with NVIDIA TensorRT</a></li>
    </ul>
  </li>
  <li><a href="https://developer.nvidia.com/tao-toolkit">NVIDIA TAO TOOLKIT</a>
    <ul>
      <li>Creating an AI/machine learning model from scratch can cost you a lot of time and money. Transfer learning is a popular technique that can be used to extract learned features from an existing neural network model to a new one.</li>
    </ul>
  </li>
</ul>

<h6 id="references">References:</h6>
<ul>
  <li><a href="https://blogs.nvidia.com/blog/2019/02/07/what-is-transfer-learning/">Transfer Learning</a></li>
  <li><a href="https://courses.nvidia.com/courses/course-v1:DLI+S-RX-02+V2/info">Getting Started with AI on Jetson Nano</a></li>
</ul>]]></content><author><name>Akhilesh Moghe</name></author><category term="Machine Learning" /><category term="Artificial Intelligence" /><category term="Deep Learning" /><category term="Jetson Nano" /><category term="Machine Learning" /><category term="Artificial Intelligence" /><category term="Deep Learning" /><category term="Jetson Nano" /><summary type="html"><![CDATA[AI and Deep Learning Evolution As humans, we generalize what we see based on our experience. In a similar way, we can use a branch of AI called Machine Learning to generalize and classify images based on experience in the form of lots of example data. In particular, we will use deep neural network models, or Deep Learning to recognize relevant patterns in an image dataset, and ultimately match new images to correct answers. Deep Learning Models A Deep Learning model consists of a neural network with internal parameters, or weights, configured to map inputs to outputs. In Image Classification, the inputs are the pixels from a camera image and the outputs are the possible categories, or classes that the model is trained to recognize. The choices might be 1000 different objects, or only two. Multiple labeled examples must be provided to the model over and over to train it to recognize the images. Once the model is trained, it can be run on live data and provide results in real time. This is called inference. Before training, the model cannot accurately determine the correct class from an image input, because the weights are wrong. Labeled examples of images are iteratively submitted to the network with a learning algorithm. If the network gets the “wrong” answer (the label doesn’t match), the learning algorithm adjusts the weights a little bit. Each iteration of training is supposed to improve the model’s performance, it is termed as epoch. Over many computationally intensive iterations, the accuracy improves to the point that the model can reliably determine the class for an input image. Convolutional Neural Networks (CNNs) Overview Deep learning relies on Convolutional Neural Network (CNN) models to transform images into predicted classifications. A CNN is a class of artificial neural network that uses convolutional layers to filter inputs for useful information, and is the preferred network for image applications. An artificial neural network is a computational model. At each layer, the network transforms input data by applying a nonlinear function to a weighted sum of the inputs. The intermediate outputs of one layer, called features, are used as the input into the next layer. The neural network, through repeated transformations, learns multiple layers of nonlinear features (like edges and shapes), which it then combines in a final layer to create a prediction (of more complex objects). The convolution operation specific to CNNs combines the input data (feature map) from one layer with a convolution kernel (filter) to form a transformed feature map for the next layer. CNNs for image classification are generally composed of an input layer (the image), a series of hidden layers for feature extraction (the convolutions), and a fully connected output layer (the classification). As it is trained, the CNN adjusts automatically to find the most relevant features based on its classification requirements. For example, a CNN would filter information about the shape of an object when confronted with a general object recognition task but would extract the color of the bird when faced with a bird recognition task. This is based on the CNN’s recognition through training that different classes of objects have different shapes but that different types of birds are more likely to differ in color than in shape. Transfer Learning: The Transfer Learning a deep learning technique enables developers to harness a neural network used for one task and apply it to another domain. For Example, take image recognition. Let’s say that you want to identify horses, but there aren’t any publicly available algorithms that do an adequate job. With transfer learning, you begin with an existing convolutional neural network commonly used for image recognition of other animals, and you tweak it to train with horses. Developers might start with ResNet-50 — a pre-trained deep learning model consisting of 50 layers — because it has a high accuracy level for identifying cats or dogs. Within the neural network are layers that are used to identify outlines, curves, lines and other identifying features of these animals. The layers required a lot of labeled training data, so using them saves a lot of time. Those layers can be applied to the task of carrying out the same identification on some horse features. You might be able to identify eyes, ears, legs and outlines of horses with ResNet-50, but to determine it was a horse and not a dog might require some additional training data. And with additional training by feeding labeled training data for horses — more horse-specific features can be built into the model. How it works: First, you delete what’s known as the “loss output” layer, which is the final layer used to make predictions, and replace it with a new loss output layer for horse prediction. This loss output layer is a fine-tuning node for determining how training penalizes deviations from the labeled data and the predicted output. Next, you would take your smaller dataset for horses and train it on the entire 50-layer neural network or the last few layers or just the loss layer alone. By applying these transfer learning techniques, your output on the new CNN will be horse identification. Transfer learning isn’t just for image recognition. Recurrent neural networks, often used in speech recognition, can take advantage of transfer learning, as well. However, you’ll need two similar speech-related datasets, such as a million hours of speech from a pre-existing model and 10 hours of speech specific to the new task. Baidu’s Deep Speech neural network offers a jump start for speech-to-text models, for example, allowing an opportunity to use transfer learning to bake in special speech features. Why &amp; When to use Transfer Learning: Transfer learning is useful when you have insufficient data for a new domain you want handled by a neural network and there is a big pre-existing data pool that can be transferred to your problem. So you might have only 1,000 images of horses, but by tapping into an existing CNN such as ResNet, trained with more than 1 million images, you can gain a lot of low-level and mid-level feature definitions. NVIDIA TAO Toolkit: For developers and data scientists interested in accelerating their AI training workflow with transfer learning capabilities, the NVIDIA TAO Toolkit offers GPU-accelerated pre-trained models and functions to fine-tune your model for various domains such as intelligent video analytics and medical imaging. ResNet (Residual Networks) There are a number of world-class CNN architectures available to application developers for image classification and image regression. PyTorch and other frameworks include access to pretrained models from past winners of the famous Imagenet Large Scale Visual Recognition Challenge (ILSVRC), where researchers compete to correctly classify and detect objects and scenes with computer vision algorithms. In 2015, ResNet swept the awards in image classification, detection, and localization. ResNet is a residual network, made with building blocks that incorporate “shortcut connections” that skip one or more layers. The shortcut output is added to the outputs of the skipped layers. The authors of Deep Residual Learning for Image Recognition demonstrate that this technique makes the network easier to optimize, and have higher accuracy gains at greatly increased depths. The ResNet architectures presented range from 18-layers deep, all the way to 152-layers deep! The smallest network, ResNet-18 provides a good balance of performance and efficiency sized well for the Jetson Nano. PyTorch includes a pre-trained ResNet-18 model that was trained on the ImageNet 2012 classification dataset, which consists of 1000 classes. In other words, the model can recognize 1000 different objects already! Within the trained neural network are layers that find outlines, curves, lines, and other identifying features of an image. Important image features that were already learned in the original training of the model are now re-usable for our own classification task. The last layer for ResNet-18 is a fully connected (fc) layer, pooled and flattened to 512 inputs, each connected to the 1000 possible output classes. Classification Vs. Regression: Unlike Image Classification applications, which map image inputs to discrete outputs (classes), the Image Regression task maps the image input pixels to continuous outputs. Continuous outputs can be the X and Y coordinates of various features on a face, such as a nose. Mapping an image stream to a location for tracking can be used in other applications, such as following a line in mobile robotics. Tracking isn’t the only thing a Regression model can do though. The output values could be something quite different such as steering values, or camera movement parameters. Evaluation: Classification and Regression also differ in the way they are evaluated. The discrete values of classification can be evaluated based on accuracy, i.e. a calculation of the percentage of “right” answers. In the case of regression, we are interested in getting as close as possible to a correct answer. Therefore, the root mean squared error can be used. Further References: Artificial Neural Network Explains: Neural Networks terms like: Neurons/Nodes, Unit, Activation Function, Layers NVIDIA cuDNN The NVIDIA CUDA® Deep Neural Network library (cuDNN) is a GPU-accelerated library of primitives for deep neural networks. cuDNN provides highly tuned implementations for standard routines such as forward and backward convolution, pooling, normalization, and activation layers. cuDNN accelerates widely used deep learning frameworks, including Caffe2, Chainer, Keras, MATLAB, MxNet, PaddlePaddle, PyTorch, and TensorFlow. NVIDIA TensorRT TensorRT-based applications perform up to 40X faster than CPU-only platforms during inference. With TensorRT, you can optimize neural network models trained in all major frameworks, calibrate for lower precision with high accuracy. TensorRT is built on CUDA®, NVIDIA’s parallel programming model, and enables you to optimize inference leveraging libraries. TensorRT provides optimizations for production deployments of deep learning inference applications such as video streaming, speech recognition, recommendation, fraud detection, text generation, and natural language processing. TensorRT internally use cuDNN for inference but with some extension. cuDNN is a operation level API and user will need to convert the model layer by layer. TensorRT provide several parsers and can support most public dnn model format directly. Amazon SageMaker Neo makes it easier to get faster inference for more ML models with NVIDIA TensorRT NVIDIA TAO TOOLKIT Creating an AI/machine learning model from scratch can cost you a lot of time and money. Transfer learning is a popular technique that can be used to extract learned features from an existing neural network model to a new one. References: Transfer Learning Getting Started with AI on Jetson Nano]]></summary></entry></feed>