Pages

Search This Blog

Thursday, February 25, 2021

GNU, Unix, Linux, *nix, FOSS, F(L)OSS,..


Woah, that's a long list keywords..and yes, these are some of the basic terms that comes in the minds of programmers or sysadmins(i guess the latter encounter more on these).


Did Linux come first? Are FOSS and F(L)OSS same?what about the GPL?
These are not chicken-egg problems and all these have definitions or well defined history behind it (unlike those manipulated histories out there, the CS people do well in documenting/preserving history and naming stuffs, there is a general saying "There are only two hard things in Computer Science: cache invalidation and naming things").


Which came first Unix or Linux?

UNIX ofcourse...
 


History goes like this(fast-forwarded till Unix) --> Charles Babbage invented Analytical Engine in 1822 and Ada Lovelace wrote the first algorithm(she has this title of 'first computer programmer'). Then comes the Punched card system, Alan Turing's Turing machine, etc, all these were Analog computers.
Then cometh the era of digital computers (1938 onwards) replacing the mechanical stuffs with electronic circuits and it was the World War 2 season and most of these first digital machines with vacum tubes were used for encryption and decryption- the German encryption using 'Enigma' and the British codebreakers 'Colossus'   :-D

Then came ENIAC, first electronic programmable computer (intersting fact: the programmers of ENIAC were 6 women, called 'ENIAC girls') followed by UNIVAC, the first commercial computer for business and goverments in 1946. Bell Labs invents transistor in 1947, first commercial stored program computer IBM 701 in 1952 followed by first programming language COBOL in 1952 and FORTRAN, invention of Integrated Circuit by Jack Kilby in 1958.
The 1960s saw large mainframe computers become much more common in large industries and with the US military and space program. IBM became the unquestioned market leader in selling these large, expensive, error-prone, and very hard to use machines. These mainframes used COBOL as its programming language and this language is one of the oldest continuously used programming language.

 In the mid 1960s, MIT, Bell Labs, and General Electric were developing Multics, a time-sharing operating system for the GE-645 mainframe computer. Frustrated by the size and complexity of Multics, but not by its goals, individual researchers at Bell Labs started withdrawing from the project. The last to leave (these are some well-known names in computer science) the organisation were Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna; they decided to re-implement the project in a smaller scale with their experiences, but this was not backed by the organisation and it haven't had a name then. This new OS was a single tasking system, and in 1970 the group coined this name Unics (as a pun for Multics, Uniplexed information and Computing Systems) which later began to know by the name Unix. Unix solved many compatibility issues that were present in the earlier OS by DEC like TOPS-10(for the PDP-10 line of computers). First Unices were written in Assembly language and later re-written entirely to C as its programming/development language(guess who is in the team, the designer of C itself..lol)

Coming back to our history timeline, after the IC revolution started by Jack, computers began to get manufactured commercially for academic purposes and for other business/commercial use. During the late 1970s and early 1980s, the influence of Unix in academic circles led to large-scale adoption of Unix, hence even though it was initially intended to use in Bell Labs, AT&T licensed the Unix to outside parties  leading to academic and commercial Unix variants from vendors including

System V Release 4(SVR4) developed by AT&T, University of California, Berkeley (BSD), Microsoft (Xenix), Sun Microsystems (SunOS/Solaris), HP/HPE (HP-UX), and IBM (AIX).


Unix Systems were characterized by the various concepts including the modular design called as 'Unix Philosophy' which upholds "the idea that the power of a system comes more from the relationships among programs than from the programs themselves".
In the 1990s, Unix and Unix-like systems grew in popularity and became the operating system of choice for over 90% of the world's top 500 fastest supercomputers, as BSD and Linux(wait a sec when did this come?) distributions were developed through collaboration by a worldwide network of programmers. In 2000, Apple released Darwin, also a Unix system, which became the core of the Mac OS X operating system, later renamed macOS. There goes the history and the conquest of Unix....


So..When did Linux come?what about GNU?

In 1984 the Bell Labs began selling Unix as a proprietary product, were users were not  allowed to modify Unix. Some were not happy about this, especially Richard Stallman. He began his career in MIT's Artificial Intelligence Lab in 1971 (were you guys born at that time? not me...) and he worked in a group which used free software (which means, the users have the freedom to run, copy, distribute, study, change and improve the software). Even computer companies often distributed free software. Programmers were free to cooperate with each other, and often did. So in 1980s like Unix, almost all softwares was proprietory and it had owners who forbid and prevent cooperation by users. This made the GNU Project necessary.  

 

The GNU Project was conceived in 1983 by Richard Stallman(RMS, you can visit him here, he is cool -->https://stallman.org/ ) as a way of bringing back the cooperative spirit that prevailed in the computing community in earlier days—to make cooperation possible once again by removing the obstacles to cooperation imposed by the owners of proprietary software.

 
 Hence in 1984 the Free Software Foundation(FSF) was founded to help develop GNU, and RMS wrote this manifesto for freedom called  GNU General Public License (GNU GPL) in 1989. GPL is a series of widely-used free software licenses that guarantee end users the freedom to run, study, share, and modify the software.The GPL series are all copyleft licenses, which means that any derivative work must be distributed under the same or equivalent license terms. You can view the GPL in plain text here https://www.gnu.org/licenses/gpl-3.0.txt .  During 1990s the GNU project had everything for a Unix-like OS, compilers, editors, text formatters, mail software, graphical interfaces, libraries, games and many other things. BUT EXCEPT ONE THING, the Kernel. 

Then Linux, a Unix-like kernel, was developed by Linus Torvalds in 1991 and made it as a free software in 1992. Combining Linux with the almost-complete GNU system resulted in a complete operating system: the GNU/Linux system.


 For these Unix-like systems(which includes the linux/unix-like kernel) we can call it with a wildcard tag (a leet hashtag back then) *nix.


FOSS or F(L)OSS?

The two political camps in the free software community are the free software movement and open source. The free software movement is a campaign for computer users' freedom; we say that a nonfree program is an injustice to its users.  The free software movement campaigns for freedom for the users of computing; it is a movement for freedom and justice. Open-source software (OSS) is a type of computer software in which source code is released under a license(with defined terms and conditions) in which the copyright holder grants users the rights to use, study, change, and distribute the software to anyone and for any purpose. Free and open-source software (FOSS) is software that can be classified as both free software and open-source software. That is, anyone is freely licensed to use, copy, study, and change the software in any way, and the source code is openly shared so that people are encouraged to voluntarily improve the design of the software.
As by RMS and FSF team,  The open source camp declines to see the issue as a matter of justice to the users, and bases its arguments on practical benefits only.

A researcher studying practices and methods used by developers in the free software community decided that these questions were independent of the developers' political views, so he used the term “FLOSS,” meaning “Free/Libre and Open Source Software,” to explicitly avoid a preference between the two political camps. If you wish to be neutral, this is a good way to do it, since this makes the names of the two camps equally prominent.


So...which movement/philosophy do you stand with? (hehe just kidding..but yeah we need to)




References:
https://www.gnu.org
https://en.wikipedia.org/wiki/Unix
https://www.livescience.com/20718-computer-history.html




Friday, December 11, 2020

The messed up 'User-Agent' string !!

This is interesting. Ever wondered why all the User-Agents start with Mozilla? please read on...

What is User-Agent?

When you browse a web page via your browser, the browser sends this particular string called User-Agent along with other request headers. Below is the definition for User-Agent from Mozilla developers.

The User-Agent request header is a characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.

 

What is the need for User-Agent? In HTTP, the User-Agent string is often used for content negotiation, where the origin server selects suitable content or operating parameters for the response. For example, the User-Agent string might be used by a web server to choose variants based on the known capabilities of a particular version of client software. The concept of content tailoring is built into the HTTP standard in RFC 1945 "for the sake of tailoring responses to avoid particular user agent limitations.”. User-Agent is used to identify webcrawlers which uses the respective spiderbot name in their User-Agent. The other reason is for sniffing the client browser, for business gains which the below content is all about.


A typical User-Agent string looks like this (which can be found by checking your browser's request headers in developer tools or by hitting F12 and checking the Request headers in Headers section):

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0 

 

The UA(User-Agent) string definition by Mozilla team is as follows :

Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion
1 Mozilla/5.0 is the general token that says the browser is Mozilla-compatible. For historical reasons, almost every browser today sends it. 
2 platform describes the native platform the browser is running on (Windows, Mac, Linux, Android, etc.), and if it's a mobile phone. Firefox OS phones simply say Mobile — the web is the platform. Note that platform can consist of multiple "; "-separated tokens. See below for further details and examples.  
3 rv:geckoversion indicates the release version of Gecko (such as "17.0"). In recent browsers, geckoversion is the same as firefoxversion.  
4 Gecko/geckotrail indicates that the browser is based on Gecko. (On Desktop, geckotrail is always the fixed string 20100101.)  
5 Firefox/firefoxversion indicates the browser is Firefox, and provides the version (such as "17.0").

 

And if we check the same on a Google-Chrome browser this is what we get, and why on earth does it say Safari and Gecko:

User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36


So why  do all these User-Agent string start with Mozilla?  

It follows a historical reason as mentioned by the Mozilla team in the above definition and the history goes like this...

Even though Tim Berners Lee's WorldWideWeb is the first web client/browser, the popularity explosion happened with  NCSA Mosaic which was a graphical browser (with pictures along with text) running originally on Unix and Mosaic called itself NCSA_Mosaic/2.0 (Windows 3.1)

Marc Andreessen, who was the leader of the Mosaic team at NCSA, quit to form a company that would later be known as Netscape Communications Corporation. Netscape released its flagship Navigator product in October 1994, and it took off the next year. 

The Netscape web browser did not use any NCSA Mosaic code. The internal codename for the company's browser was Mozilla, which stood for "Mosaic killer", as the company's goal was to displace NCSA Mosaic as the world's number one web browser. This codename they incorporated as their User-Agent header Mozilla/1.0. 

Microsoft, which had thus far not marketed a browser, finally entered the arena with its Internet Explorer product (version 1.0 was released 16 August 1995), purchased from Spyglass, Inc. This began what is known as the "browser wars" in which Microsoft and Netscape competed for the Web browser market.

Why the user-agent along with header? because at that time the “user agent sniffing” is done by webmasters to give the features to the particular browser request and not to other. Mozilla/Netscape2.0 had many cool features back then like frames, java, plugins etc.,   and to “Mozilla” user-agent's webmasters sent frames, but to other browsers they sent not frames. Guess what these browsers were not free at that time :)

Interesting history: 
In 1996, Netscape's share of the browser market reached 86% (with Internet Explorer edging up 10%); but then Microsoft began integrating its browser with its operating system and bundling deals with OEMs. 

 

When user-agent sniffing was the need of the hour, to get the features from Webmasters like frames, a feature supported by both Netscape and IE, but not other browsers of the era, IE spoofed the Mozilla string into their UA. 

The UA string for IE at that time was:
Mozilla/1.22 (compatible; MSIE 2.0; Windows 95),   
 

Unable to continue commercially funding their product's development, Netscape responded by open sourcing its product, creating Mozilla.  The Mozilla Organization rewrote the entire browser's source code based on the Gecko rendering engine, and all future Netscape releases were based on this rewritten code.

Mozilla updated it's UA string with Gecko as follows (the first two 'windows' fields being platform on which the browser runs):
Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.1) Gecko/20020826,
 
Mozilla then became firefox and followed the below UA for firefox:   
Mozilla/5.0 (Windows; U; Windows NT 5.1; sv-SE; rv:1.7.5) Gecko/20041108 Firefox/1.0, 
 
Gecko rendering engine was widely accepted and many browsers began to use the Gecko rendering engine like the below examples: 
  • Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7.2) Gecko/20040825 Camino/0.8.1 
  • Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.8) Gecko/20071008 SeaMonkey/1.0 

each pretending to be Mozilla, and all of them powered by Gecko.

 

Konquerer browser which comes with Linux distros, used KHTML rendering engine, but it was not Gecko, and to get the Gecko tag (for browser sniffers) in UA string it appended  “like Gecko” to render good pages like that of Gecko.

Mozilla/5.0 (compatible; Konqueror/3.2; FreeBSD) (KHTML, like Gecko) 

 

Apple built Safari, and used KHTML, and added many features, by forkingthe project, and called it AppleWebKit, but wanted pages written for KHTML, so the spoofing continues by appending KHTML string along with Webkit.

Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/85.7 (KHTML, like Gecko) Safari/85.5,

 

Then comes the Chrome with much spoofing, which used the Webkit engine and wanted to get the pages build for Safari, here is that great impersonation with AppleWebKit and Safari tag:

Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36


The bottom-up approach of this spoofing/impersonations goes like this:

Chrome used WebKit, and pretended to be Safari(AppleWebKit), and WebKit pretended to be KHTML(KHTML), and KHTML pretended to be Gecko (like Gecko), and all browsers pretended to be Mozilla (Mozilla) 


Are you building a web-browser? If so, please follow the above mess !!



References:

Sunday, December 6, 2020

Disk IOPS - Throughput, Block size...,

We all might have heard these terms IOPS/Throughput, Disk blocks, Latency etc., let's look into these details.

What is IOPS? 

Input/output operations per second (IOPS, pronounced eye-ops) is an input/output performance measurement used to characterize computer storage devices like hard disk drives (HDD), solid state drives (SSD), and storage area networks (SAN).
To meaningfully describe the performance characteristics of any storage device, it is necessary to specify a minimum of three metrics simultaneously: IOPS, response time, and (application) workload. Absent simultaneous specifications of response-time and workload, IOPS are essentially meaningless.
IOPS number vary greatly with the input parameters that testers use, including the balance of read and write operations, the mix of sequential and random access patterns, the number of worker threads and queue depth, as well as the data block sizes. 
 

Sequential and Random access on IOPS performance: 

Sequential operations access locations on the storage device in a contiguous manner and are generally associated with large data transfer sizes, e.g. 128 kB. 
Random operations access locations on the storage device in a non-contiguous manner and are generally associated with small data transfer sizes, e.g. 4kB. 

For HDDs and similar electromechanical storage devices, the random IOPS numbers are primarily dependent upon the storage device's random seek time, whereas, for SSDs and similar solid state storage devices, the random IOPS numbers are primarily dependent upon the storage device's internal controller and memory interface speeds. 

IOPS = 1000 milliseconds / (Average Seek Time + Average Latency), with the latter two also measured in milliseconds.

What is Average Latency and Average Seek Time: 

Average Latency is the time it takes the disk platter to spin halfway around. It is calculated by dividing 60 seconds by the Rotational Speed of the disk, then dividing that result by 2 and multiplying everything by 1,000 milliseconds. ((60 / RPM)/2)*1,000. 

Average Seek Time is the time it takes for the head (the piece that reads data) to reach the area on the disk upon which that data is stored. The head needs to move around the storage area in order to locate the targeted data. You must average both read and write seek times in order to find the average seek time. 

The reason for SSD's having higher IOPS is because that for solid state drives, the average latency drops significantly, as there is no rotating disk inside. The seek time is also nil/null/N/A. 

While traditional HDDs have about the same IOPS for read and write operations, most NAND flash-based SSDs are much slower writing than reading due to the inability to rewrite directly into a previously written location forcing a procedure called garbage collection. 

 

What is Throughput? 

Throughput measures the data transfer rate to and from the storage media in megabytes per second.The disk throughput describes how many data may be transferred per second,hence disk block size play an important role: 

throughput = [IOPS] * [block size] 

Let's consider as the sample the 3000 IOPS and SQL database engine, the block size in terms of db engine is called the page size and for SQL Server it's equal to 8 KB. If you wish to calculate the actual throughput, if the IOPS defined, you will end up with the formula below:

 throughput = [IOPS] * [block size] = 3000 * 8 = 24 000 KB/s = 24 MB/s 

IOPS can therefore become a bottleneck for throughput. It is likely that your CPU and memory will not be a limiting factor, as they can handle more information per second than most storage devices and networks. A serially-attached storage device might only have a maximum throughput of up to 2,812 MBps, while Ethernet reaches up to 12,500 MBps and fiber channel networks reach 4,000 MBps. The size and number of blocks traversing the network can make a big difference in throughput. A 1 MB block will take longer to pass through the network but you may not move as many of them. A 4 KB block will move very quickly, but you’ll likely face a high volume. 

 

So what is a Block size/blocks? 

A sector is a physical spot on a formatted disk that holds information (please see the above disk diagram). When a disk is formatted, tracks are defined (concentric rings from inside to the outside of the disk platter. Each track is divided into a slice, which is a sector. On hard drives and floppies, each sector can hold 512 bytes of data. 

A block, on the other hand, is a group of sectors that the operating system can address (point to). A block might be one sector, or it might be several sectors (2,4,8, or even 16). The bigger the drive, the more sectors that a block will hold. 

So why are there blocks. Why doesn't the operating system just point straight to the sectors? Because there are limits to the number of blocks, or drive addresses, that an operating system can address. By defining a block as several sectors, an OS can work with bigger hard drives without increasing the number of block addresses. 

True or False: When a file is copied from a hard drive to a floppy, it will usually take up less space than it takes up on a hard drive --> TRUE. 
If you tend to store lots of small files on your hard drive the blocks used to store all those little files can have a lot of wasted space in them. 
Likewise, compressing lots of little files may not save as much space on a big hard drive with a big block size 
 
Every file takes up one block no matter its size, so choosing the correct block size to efficiently consume storage can make a big difference when it comes to performance. 
For example. SQL server logs in 64 kb blocks, while Windows Server might use 4 kb blocks, and the underlying vSphere hypervisor uses 1 MB blocks. As you’ll see, the block size and IOPS have a snowballing effect on network traffic throughput. 

 

Typically Linux and Windows use a 4KB default filesystem block size. 
Even though the disk Sector size (logical/physical) shows 512 bytes, the OS filesystem IO block will be 4K. 
In a Linux machine you can verify this using the below commands: 
 
#fdisk -l /dev/(diskname) 
#cat /sys/block/sd*/queue/hw_sector_size
#cat /sys/block/sd*/queue/physical_block_size 
#stat -f filename
  File: "IOPS" ID: e68758737c7b7176 Namelen: 255 Type: ext2/ext3    Block size:   4096 Fundamental block size: 4096

For blocksize and performance, you can refer the link --> https://knowledgebase.progress.com/articles/Article/18293 

 

I find the below analogy quite easy and enjoyable to understand on IOPS/Throughput (thanks to @Kgothatso Kurt -stackoverflow) 

You have 4 buckets (Disk blocks) of the same size that you want to fill or empty water. You'll be using a jug to transfer the water into the buckets. 

Now your question will be : 

At a given time (per second), how many jugs of water can you pour(write) or withdraw (read)? This is IOPS 

At a given time (per second) what's the amount(bit, kb, mb, ect) of water the jug can transfer into/out of the bucket continuously? This is throughput. 

Additionally, there is a delay in the process of you pouring and or withdrawing the water. This is Latency. 

There are 3 things to consider about IOPS and Throughput. 

- Size (file size/ block size) 
- Patterns (Random/Sequential) 
- Mix (Read/Write) percentage 
(all these factors has been explained as of now) 

 

Disk IOPS info from iostat:

In GNU/Linux, iostat is a command line tool which comes with the package systat 

iostat output on a machine with low IO usage:

# iostat
Linux 3.10.0-1062.18.1.el7.x86_64 (infra-85)     Sunday 06 December 2020     _x86_64_    (2 CPU)

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           1.53    0.00    0.65    1.66    0.16   96.00

Device:            tps    kB_read/s    kB_wrtn/s    kB_read    kB_wrtn
xvda              2.63         7.80        26.39  112212822  379585947


%tps : The tps number here is the number of I/O Operations Per Second (IOPS), transactions per second. 

%iowait : is first and foremost a CPU metric that measures the percentage of time the CPU is idle while waiting for an I/O operation to complete. This metric is heavily influenced by both your CPU speed and CPU load The only thing %iowait tells us for sure is that the CPU is occasionally idle and can thus handle more computational work.

 -x will give details report 

-m shows result in MB 

-d show disk utilization 

 

#iostat -dmx
Linux 3.10.0-1062.18.1.el7.x86_64 (infra-85)     Sunday 06 December 2020     _x86_64_    (2 CPU)

Device:         rrqm/s   wrqm/s     r/s     w/s    rMB/s    wMB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
xvda              0.00     0.09    0.28    2.35     0.01     0.03    25.97     0.26  100.18  138.73   95.59  18.27   4.81

 

%avgqu-sz : The avgqu-sz metric is an important value. it shows the number of operations that were either queued or being serviced. Single digit numbers with the occasional double digit spike are safe(ish) values. Triple digit numbers are generally not. Note that this metric is unlikely to hover around zero unless you are doing very little I/O. A certain amount of queueing is generally unavoidable as modern storage devices reorder disk operations so as to improve overall performance. 

%await : The await metric is the average time from when a request is put in the queue to when the request is completed. Therefore, this metric is the sum of the time a request spent waiting in the queue and the time your storage device was working on servicing the request. This number is highly dependent on the number of items in the queue. Much like avgqu-sz, you'll want to have an idea of the value of this metric during normal operations for use as a reference when trouble occurs. 

%util : Percentage of elapsed time during which I/O requests were issued to the device (bandwidth utilization for the device). Device saturation occurs when this value is close to 100% for devices serving requests serially. But for devices serving requests in parallel, such as RAID arrays and modern SSDs, this number does not reflect their performance limits.

#iostat 5 2

gives 2 statistics in 5 seconds interval 

What is a good or bad number though? As with most metrics, if the first time you look at it is when you are in trouble then it’s less helpful. You should have an idea of how much IO you typically do, then if you experience issues and are doing 10x that or only getting 1/10 from the disks then you have a good candidate explanation for them.

Generally a HDD will have an IOPS range of 55-180, while a SSD will have an IOPS from 3,000 – 40,000. 

 

Below tables shows the IOPS as per the manufacturer: 

HDD's/Mechanical drives:
SSD's IOPS:

 

References: 

Friday, September 4, 2020

Memory/RAM usage in GNU/Linux¶

 

The Memory calculation in Linux (/Unix) is different from that of Windows OS

Memory that is: You'd call it: Linux calls it:
used by applications                      
Used Used
used, but can be made available Free (or Available) Used (and Available)
not used for anything Free Free

What is procps? 

procps is a package that provides command line and full screen utilities for browsing procfs, a "pseudo" file system dynamically generated by the kernel to provide information about the status of entries in its process table (such as whether the process is running, stopped, or a "zombie"). 

As you know the different commands to check the process states such as ps, free, vmstat etc, all these commands use this procps package to provide the output.

procps contains free, kill, pkill, pgrep, pmap, ps, pwdx, skill, slabtop, snice, sysctl, tload, top, uptime, vmstat, w, and watch. 

 

Memory usage calculation

For ex: Below is the output of free command (procps version < 3.3)

[root@RGIUSMARTWEB ~]# free -m
             total       used       free     shared    buffers     cached
Mem:         11912      11194        718          0        214       9354
-/+ buffers/cache:       1624      10287
Swap:        17999          9      17990
[root@RGIUSMARTWEB ~]#

The used mem is calculated as Total - free, i.e. 11912 - 718 = 11194(size in mbs). Actually, in *nix these used_mem is that of cached and buffers which can be reclaimable by the programs or apps in user-space.

So, the used memory by the apps/pgms in user-space is calculated as used = total - free - cached - buffers
i.e. 11912 - 718 - 214 - 9354 = 1626

Hence the real available memory for the apps/pgms in user-space is total - used, i.e., 11912 - 1626 = 10286
So 10286 mb is free in above scenario.

The upgraded version of procps includes an available column which shows the above value derived using the same method.
The Mem used(kb_main_used) field value is now calculated like this:
used = total - free - cached - buffers
Previously, it used to be:
used = total - free

Below is the output of free command with procps version 3.3.10

[root@RGIUSMARTWEB procps-ng-3.3.10]# free -m
              total        used        free      shared  buff/cache   available
Mem:          11912        1253         611           0       10047       10381
Swap:         17999           9       17990
[root@RGIUSMARTWEB procps-ng-3.3.10]#

Please note the 'available' column which matches the previous value calculated, available=10381 (little change is due to the slab/cache difference)

Newer linux kernels has the MemAvailable segment in /proc/meminfo which shows the somewhat same range of value.

As of the new available field, for Linux kernels older than 2.6.27, its value is the same as the free value, but for the later versions of the Kernel, its a bit different:

Estimation of how much memory is available for starting new applications, without swapping. Unlike the data provided by the cache or free fields, this field takes into account page cache and also that not all reclaimable memory slabs will be reclaimed due to items being in use (MemAvailable in /proc/meminfo, available on kernels 3.14, emulated on kernels 2.6.27+, otherwise the same as free)

Kernel commit for /proc/meminfo (hey! look who has made that commit..)

https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773

Newer versions of procps package (> 3.3) has the available column which shows an accurate value of memory available for applications and programs in userspace

Procps package commit with available column: --> https://gitlab.com/procps-ng/procps/commit/6cb75efef85f735b72e6c96f197f358f511f8ed9

References:
https://www.linuxatemyram.com/
https://www.dynatrace.com/news/blog/improved-host-memory-metrics-now-include-reclaimable-memory/

Sunday, July 19, 2020

vi - A fast and powerful Text Editor


About this first blog, I was sure it would be about this beautiful little program called 'vi', the command-line text editor that amuse the users(sysads/progmrs) by its simple, yet powerful features. As a user spent time interacting with this little editor, more cool features gets unveiled before the user.



vi was originally created for Unix systems, by  Bill Joy in 1976, as the visual mode for a line editor called ex that Joy had written with Chuck Haley.  vi was derived from a sequence of UNIX command line editors, starting with ed, which was a line editor designed to work well on teleprinters, rather than display terminals. You could find this 'ed' editor in earlier distros of GNU/Linux ( I've seen it in Debian wheezy, but now in buster its not packaged). This ed editor has its own history too (ever wondered how the 'grep' command name originated?).

Joy was responsible for creating the first BSD Unix release in March, 1978, and included ex 1.1 in the distribution, thereby exposing his editor to an audience beyond UC Berkeley. From that release of BSD Unix onwards, the only editors that came with the Unix system were ed and ex. 

Eventually it was observed that most ex users were spending all their time in visual mode,and thus in ex 2.0, Joy created vi as a hard link to ex, such that when invoked as vi, ex would automatically start up in its visual mode. Thus, vi is not the evolution of ex, vi is ex. In your *nix distro you can verify this by executing ex -v filename which is the execution of the same vi .

Despite the existence of vi clones with enhanced featuresets, sometime before June 2000, Gunnar Ritter ported Joy's vi codebase (taken from 2.11BSD, February 1992) to modern Unix-based operating systems, such as Linux and FreeBSD. Initially, his work was technically illegal to distribute without an AT&T source license, but, in January 2002, those licensing rules were relaxed,[29] allowing legal distribution as an open-source project. Ritter continued to make small enhancements to the vi codebase similar to those done by commercial Unix vendors still using Joy's codebase, including changes required by the POSIX.2 standard for vi. His work is available as Traditional Vi, and runs today on a variety of systems.

You can read complete history here https://en.wikipedia.org/wiki/Vi from which the above excerpt is taken.


What are vi, ex, view; why are these binaries in my system.

Vi is a screen oriented text editor.

Ex is a line-oriented text editor. Ex and vi are different interfaces to the same program, and it is possible to switch back and forth during an edit session.

View behaves identically to vi except that it automatically opens all files as read-only.It is the equivalent of using the -R (read-only) option of vi.

The vi and ex components will be explained in the section Components of vi

All these binaries are actually links to one another, for e.g: in the Debian buster release vi, ex, and view are links to the binary vim.tiny.

root@localhost:~# readlink -f /usr/bin/vi

/usr/bin/vim.tiny


root@localhost:~# dpkg -S /usr/bin/vim.tiny

vim-tiny: /usr/bin/vim.tiny


root@localhost:~# ls -l /usr/bin/vi

lrwxrwxrwx 1 root root 20 Jan  6  2020 /usr/bin/vi -> /etc/alternatives/vi


root@localhost:~# ls -l /usr/bin/ex

lrwxrwxrwx 1 root root 20 Jan  6  2020 /usr/bin/ex -> /etc/alternatives/ex


root@localhost:~# ls -l /usr/bin/view

lrwxrwxrwx 1 root root 22 Jan  6  2020 /usr/bin/view -> /etc/alternatives/view


root@localhost:~# ls -l /etc/alternatives/vi

lrwxrwxrwx 1 root root 17 Jan  6  2020 /etc/alternatives/vi -> /usr/bin/vim.tiny


root@localhost:~# ls -l /etc/alternatives/ex

lrwxrwxrwx 1 root root 17 Jan  6  2020 /etc/alternatives/ex -> /usr/bin/vim.tiny


root@localhost:~# readlink -f /usr/bin/ex

/usr/bin/vim.tiny


root@localhost:~# ls -l /etc/alternatives/view

lrwxrwxrwx 1 root root 17 Jan  6  2020 /etc/alternatives/view -> /usr/bin/vim.tiny

In a Redhat distro, you will find these binaries are provided by package named vim-minimal ; ex and view are direct links to the vi binary

ex:
Start in Ex mode. Go to Normal mode with the ":vi" command. Can also be done with the "-e" argument.

view:
Start in read-only mode. You will be protected from writing the files. Can also be done with the "-R" argument.

vi will detect the name it was invoked as and act accordingly.

I think all these binaries and its relations boils down to the UNIX_philosopy "the power of a system comes more from the relationships among programs than from the programs themselves. Many UNIX programs do quite trivial things in isolation, but, combined with other programs, become general and useful tools."



vim- as the name sounds was earlier known as 'vi-imitation' which then later called as vi-Improved because of the added new features. vim is a clone, with additions, of vi editor. As vi editor was not free for a while, many clones began to get ported to Linux/FreeBSD's and vim is one such clone of vi.
In addition to syntax highlighting (when compiled with a support for it), Multi-level undo, it does automatic conversions of charactersets, line-endings and such. It has multiple ways of numbering lines, which is really convenient.
Vim certainly has a lot that speaks for it.  IMO and like-minded others, vim breaks the vi philosophy by mixing the editor modes and introducing a vast number of redundant functions.
Today, in most *nix distros, vi is actually a reference to vim.


Most of the GNU/Linux distros comes with vi/vim, if your OS release doesn't have vi/vim, you can install it via the package manager available in your OS.
Debian: apt install vim
Redhat: yum install vim
BSD: pkg install vim-console


There are two components to vi: a screen editor (Vi), and a line editor (Ex).
Each has a different set of commands; you can invoke the line editor from within the screen editor and conversely, you can invoke the screen editor from within the line editor.

In the screen editor, you are in either insert mode or command mode. In command mode, every character you type is immediately interpreted as a command. In insert mode, every character you type is added to the text that you are editing.

$ vi filename

Entering vi, by default you will be greeted by the normal mode that is the command mode where each characters you press will be interpreted as commands. Below are the commands that will help you move-by your first-steps.
       h      Move the cursor left one character.

       j      Move the cursor down one line.

       k      Move the cursor up one line.

       l      Move the cursor right one character.
            <cursor-arrows>
              The cursor arrow keys should work, too.

Press 'i' and you will be in the insert mode where every character you type is added to the text that you are editing.

Press 'Esc' and you will be back to normal mode (command mode).

Press ':' and you will be in the Ex mode, that is line editor mode. (you can also start the mode by invoking the command under the name ex; or you can invoke it under the name vi but specify the -e option. Similarly, there are two ways to start your session in Vi mode; you can invoke the command under the name vi without specifying -e; or you can invoke it under the name ex but specify -v ).

You can type ':q' which will tell the editor to quit the session or ':q!' to quit forcefully without saving.
 

Newbie vi troubleshooting

This is because you are in default vi version, that is vi compatible, if you need to use arrow keys in the insert mode, create a file named vimrc in your home directory and insert the line set nocompatible

$ vi ~.vimrc 
#(press i for insert mode)
set nocompatible

#(press Esc for command mode and enter :wq for saving the file in ex mode)

or
you can use the ex mode command by typing :set nocompatible  (the ex command need to be executed in normal mode/command mode) but the only problem is you need to issue this command each time you start vi. If this is in .vimrc then the set commands will automatically be executed while starting vi editor.

Why is the backspace not working? backspace working only with the current line and not working with the previous line.

This is also the default behaviour of original vi version. If you need to work this like a normal text editor, you can just execute the ex command  :set backspace=indent,eol,start  which sets backspacing for inserted indentation, line breaks and start of insert.
 
or
Like mentioned above you can create a .vimrc file in your home directory with the set commands in each lines.
$ vi ~.vimrc 
#(press i for insert mode)
set nocompatible
set backspace=indent,eol,start
At the time of vi development, the keyboard layout was a Lear Siegler ADM-3A terminal. On this terminal, the Escape key was at the location now occupied by the Tab key on the widely used IBM PC keyboard (on the left side of the alphabetic part of the keyboard, one row above the middle row). This made it a convenient choice for switching vi modes. Also, the keys h,j,k,l served double duty as cursor movement keys and were inscribed with arrows, which is why vi uses them in that way. There were no other arrow keys :P




It'll be easier if you go through an online interactive tutorial of vi/vim so that it'll make you hands-on to the editor in an interactive session. Below is such an interactive website which I found helpful.


Come back, once you have completed/learned the basics via those interactive lessons, which will help you understand the remaining commands:

All the below commands are entered in vi normal/command mode (if you are in insert mode the last line of the vi will show INSERT)
The commands to enter new text are: (which will enter you in insert mode go to command mode by 
<escape>)
a Append new text, after the cursor. i Insert new text, before the cursor. o Open a new line below the line the cursor is on, and start entering text. O Open a new line above the line the cursor is on, and start entering text. <escape> Once you've entered input mode using the one of the a, i, O or o commands, use <escape> to quit enter- ing text and return to command mode.
The commands to copy text are: yy Copy the line the cursor is on. p Append the copied line after the line the cursor is on. The commands to delete text are: dd Delete the line the cursor is on. x Delete the character the cursor is on. The commands to write the file are: :w<carriage-return> Write the file back to the file with the name that you originally used as an argument on the vi com- mand line. :w file_name<carriage-return> Write the file back to the file with the name ``file_name''.
The commands to quit editing and exit the editor are: :q<carriage-return> Quit editing and leave vi (if you've modified the file, but not saved your changes, vi will refuse to quit). :q!<carriage-return> Quit, discarding any modifications that you may have made.

[ At this point, if you are interested, you can read the man page of vi from 1996 -->


Above are the basic commands, you can find the vi/vim cheat sheet that explains the basic functions of each characters in vi command in the below link. You can download and save the sheet as lessons from this link.





Each command can be combined with other commands to perform related functions. For example:

                        w     for next word
                       dw    delete next word
                     2dw    delete next 2 words
                      5yy    yank 5 lines

                         
You can always repeat the previous command with vi command ' . '   If you have executed p command(which pasted the lines in the buffer to cursor) and you need to repeat the same command for 5 lines from cursor you can use '5 .' as a vi command

Buffers:

The result of a vi command will always be stored in a buffer. Objects that are deleted or otherwise manipulated have their original values placed in this buffer, You can use a named buffer. Buffers are named with single lowercase letters.

You can record the vi command actions and put it in a named buffer and execute those actions whenever necessary. The command is q for recording, followed by a character for named buffer. The below vi command will record the actions to buffer a (represented by @a)
                                    qa
You perform some actions say move the cursors and delete a character using the x command. Press Esc followed by q to stop recording. Then you can anytime use this buffer to be in action. If you need to perform the recorded action to 3 lines from the cursor position, the below command need to be executed.
                                    3@a
                            
You can mark the current cursor position to a named buffer. The vi command is m. If you need to mark the current cursor to buffer b, the command is
                                    mb
At any point of time in the editor if you need to go back to the marked cursor position you can execute the command
                                       `b
If you need to delete everything from the current cursor position to the marked position, the below command can be used
                                    d`b


ex Command Mode

vi enters Ex command mode if the program is invoked with the -e option or if the Q command is issued from Vi. You can issue a single Ex command from Vi mode by using the : command.

An Ex command takes the general form

[address-list] [[command] [!] [parameters]]

Each part is optional and may be invalid for some commands. You may specify multiple commands on a line by separating them with a vertical line character (|).

address-list 

Commands may take zero, one, or two addresses. The address % is a short form to indicate the entire file. You may omit any or all of the addresses

               
The basic and most useful ex command is the replace commands like below:

:%s/old/new/g Replace all occurences of old by new in file
:%s/old/new/gw Replace all occurences with confirmation
:2,35s/old/new/g Replace all occurences between lines 2 and 35

Do you need to delete lines from 13 to 56, just execute in ex mode :13,56d


Note:
You need to escape special characters using backslash in ex mode. Like, if you need to replace the word /home to /root (/ is a special character, likewise for %, <,>,*, $, etc.,)
                            :%s/\/home/\root/g

Search command:

You can use / (slash) to search for a character(s) in your file. if you need to search for foo just type below command in vi command mode.
                             /foo
by default it will show you with case, if you need to search without case you can set it in ex mode as :set ignorecase

For basic searching:

        /pattern       - search forward for pattern
        ?pattern       - search backward
        n              - repeat forward search
        N              - repeat backward

Some variables you might want to set:

        :set ignorecase - case insensitive
        :set smartcase  - use case if any caps used 
        :set incsearch  - show match as search proceeds
        :set hlsearch   - search highlighting


You can open multiple files in vi using filenames as arguments
                    localhost:~$ vi file1 file2
this will open two files in vi in the same window and you can switch between these files using ex command :n for next and :N for previous file
You can also use the split window ex command to split the screen vertically or horizontally by invoking
                            :vsplit filename  
                            :split filename


In some cases you need to see what files are in the current directory or to move the pwd  to some other directory, you can use the ex command
                             :sh  
which will put you in the current shell and you can execute commands and to return to vi you can execute the exit command in shell.


Indenting lines

If you are a programmer you might always want to indent those lines in the block, vi has this set of ex commands that you can use
             :set tabstop=8 - tabs are at proper location
             :set expandtab - don't use actual tab character (ctrl-v)
             :set shiftwidth=4 - indenting is 4 spaces
             :set autoindent - turns it on
             :set smartindent - does the right thing (mostly) in programs
             :set cindent - stricter rules for C programs

To indent current line(s):
In command(normal) mode, type >> to indent the current line, or << to unindent.
(combining commands example) 5>>.. shifts five lines to the right, and then repeats the operation twice so that the five lines are shifted three times.


------------------------------------------------------------------------------------------------------------------------------------


You can go through the below links which will help you master the vi editor commands, most of the commands will be common in these links but of-course there are commands that are unique to the specific author.

Basic level:

Basic - Intermediate

Advanced:


Please let me know if any of the above external links are not working. I would love to hear what your favourite secret little vi commands are.

GNU, Unix, Linux, *nix, FOSS, F(L)OSS,..

Woah, that's a long list keywords..and yes, these are some of the basic terms that comes in the minds of programmers or sysadmins(i gues...