Category Archives: Geeky

How to Control (start/stop/mask/unmask) Services Using Systemd

How to Control (start/stop/mask/unmask) Services Using Systemd

Starting and Stopping Services

Services need to be stopped or started manually for a number of reasons: perhaps the service needs to be updated; the configuration file may need to be changed; or a service may need to be uninstalled, or an administrator may manually start an infrequently used service.

To start a service, first verify that it is not running with systemctl status. Then, use the systemctl start command as the root user (using sudo if necessary). The example below shows how to start the sshd.service service:

[root@host ~]# systemctl start sshd.service

The systemd service looks for .service files for service management in commands in the absence of the service type with the service name. Thus the above command can be executed as:

[root@host ~]# systemctl start sshd

To stop a currently running service, use the stop argument with the systemctl command. The example below shows how to stop the sshd.service service:

[root@host ~]# systemctl stop sshd.service

Restarting and Reloading Services

During a restart of a running service, the service is stopped and then started. On the restart of service, the process ID changes and a new process ID gets associated during the startup. To restart a running service, use the restart argument with the systemctl command. The example below shows how to restart the sshd.service service:

[root@host ~]# systemctl restart sshd.service

Some services have the ability to reload their configuration files without requiring a restart. This process is called a service reload. Reloading a service does not change the process ID associated with various service processes. To reload a running service, use the reload argument with the systemctl command. The example below shows how to reload the sshd.service service after configuration changes:

[root@host ~]# systemctl reload sshd.service

In case you are not sure whether the service has the functionality to reload the configuration file changes, use the reload-or-restart argument with the systemctl command. The command reloads the configuration changes if the reloading functionality is available. Otherwise the command restarts the service to implements the new configuration changes:

[root@host ~]# systemctl reload-or-restart sshd.service

Listing Unit Dependencies

Some services require that other services be running first, creating dependencies on the other services. Other services are not started at boot time but rather only on demand. In both cases, systemd and systemctl start services as needed whether to resolve the dependency or to start an infrequently used service. For example, if the CUPS print service is not running and a file is placed into the print spool directory, then the system will start CUPS-related daemons or commands to satisfy the print request.

[root@host ~]# systemctl stop cups.service
Warning: Stopping cups, but it can still be activated by:
   cups.path
   cups.socket

To completely stop printing services on a system, stop all three units. Disabling the service disables the dependencies. The ‘systemctl list-dependencies UNIT’ command displays a hierarchy mapping of dependencies to start the service unit. To list reverse dependencies (units that depend on the specified unit), use the –reverse option with the command.

[root@host ~]# systemctl list-dependencies sshd.service
sshd.service
● ├─system.slice
● ├─sshd-keygen.target
● │ ├─sshd-keygen@ecdsa.service
● │ ├─sshd-keygen@ed25519.service
● │ └─sshd-keygen@rsa.service
● └─sysinit.target
...output omitted...

Masking and Unmasking Services

At times, a system may have different services installed that are conflicting with each other. For example, there are multiple methods to manage mail servers (postfix and sendmail, for example). Masking a service prevents an administrator from accidentally starting a service that conflicts with others. Masking creates a link in the configuration directories to the /dev/null file which prevents the service from starting.

[root@host ~]# systemctl mask sendmail.service
Created symlink /etc/systemd/system/sendmail.service → /dev/null.
[root@host ~]# systemctl list-unit-files --type=service
UNIT FILE                                   STATE
sendmail.service                            masked
...output omitted...

Attempting to start a masked service unit fails with the following output:

[root@host ~]# systemctl start sendmail.service
Failed to start sendmail.service: Unit sendmail.service is masked

Use the systemctl unmask command to unmask the service unit.

[root@host ~]# systemctl unmask sendmail
Removed /etc/systemd/system/sendmail.service.

Enabling Services to Start or Stop at Boot

Starting a service on a running system does not guarantee that the service automatically starts when the system reboots. Similarly, stopping a service on a running system does not keep it from starting again when the system reboots. Creating links in the systemd configuration directories enables the service to start at boot. The systemctl commands create and remove these links.

To start a service at boot, use the systemctl enable command.

[root@root ~]# systemctl enable sshd.service
Created symlink /etc/systemd/system/multi-user.target.wants/sshd.service → /usr/ lib/systemd/system/sshd.service.

The above command creates a symbolic link from the service unit file, usually in the /usr/lib/systemd/system directory, to the location on disk where systemd looks for files, which is in the /etc/systemd/system/TARGETNAME.target.wants directory. Enabling a service does not start the service in the current session. To start the service and enable it to start automatically during boot, execute both the systemctl start and systemctl enable commands.

To disable the service from starting automatically, use the following command, which removes the symbolic link created while enabling a service. Note that disabling a service does not stop the service.

[root@host ~]# systemctl disable sshd.service
Removed /etc/systemd/system/multi-user.target.wants/sshd.service.

To verify whether the service is enabled or disable, use the systemctl is-enabled command.

Summary of systemctl Commands

Services can be started and stopped on a running system and enabled or disabled for an automatic start at boot time.

Useful Service Management Commands:

TASK COMMAND
View detailed information about a unit state. systemctl status UNIT
Stop a service on a running system. systemctl stop UNIT
Start a service on a running system. systemctl start UNIT
Restart a service on a running system. systemctl restart UNIT
Reload the configuration file of a running service. systemctl reload UNIT
Completely disable a service from being started, both manually and at boot. systemctl mask UNIT
Make a masked service available. systemctl unmask UNIT
Configure a service to start at boot time. systemctl enable UNIT
Disable a service from starting at boot time. systemctl disable UNIT
List units required and wanted by the specified unit. systemctl list-dependencies UNIT

Source: How to Control (start/stop/mask/unmask) Services Using Systemd

Quicken interchange format (QIF)

Q: What is the Quicken interchange format (QIF)?

A: The Quicken interchange format (QIF) is a specially formatted text (ASCII) file that lets you to move Quicken transactions:

  • From one Quicken account register into another Quicken account register, or
  • To/From another application that supports the QIF format.

Note: For Quicken to translate data from a text file into the Quicken register as transactions, the text file must be in the QIF format.

Required File Formatting:

  • Each transaction must end with a symbol, indicating the end of entry.
  • Each item in the transaction must display on a separate line.
  • When Quicken exports an account register or list, it adds a line to the top of the file that identifies the type of account or list. Listed below are the header lines Quicken adds to the exported files:
Header Type of data
!Type:Bank Bank account transactions
!Type:Cash Cash account transactions
!Type:CCard Credit card account transactions
!Type:Invst Investment account transactions
!Type:Oth A Asset account transactions
!Type:Oth L Liability account transactions
!Account Account list or which account follows
!Type:Cat Category list
!Type:Class Class list
!Type:Memorized Memorized transaction list

 

You can force Quicken to import all transfers, regardless of whether Ignore Transfers is selected when the file is imported. You must add a line to the file being imported into a Quicken account. Use a text editor or word processor to put the following line right after the header line at the top of the file:

!Option:AllXfr

Items for Non-Investment Accounts

Each item in a bank, cash, credit card, other liability, or other asset account must begin with a letter that indicates the field in the Quicken register. The non-split items can be in any sequence:

Field Indicator Explanation
D Date
T Amount
C Cleared status
N Num (check or reference number)
P Payee
M Memo
A Address (up to five lines; the sixth line is an optional message)
L Category (Category/Subcategory/Transfer/Class)
S Category in split (Category/Transfer/Class)
E Memo in split
$ Dollar amount of split
^ End of the entry

Note: Repeat the S, E, and $ lines as many times as needed for additional items in a split. If an item is omitted from the transaction in the QIF file, Quicken treats it as a blank item.

Items for Investment Accounts

Field Indicator Explanation
D Date
N Action
Y Security
I Price
Q Quantity (number of shares or split ratio)
T Transaction amount
C Cleared status
P Text in the first line for transfers and reminders
M Memo
O Commission
L Account for the transfer
$ Amount transferred
^ End of the entry

Items for Account Information

The account header !Account is used in two places-at the start of an account list and the start of a list of transactions to specify to which account they belong.

Field Indicator Explanation
N Name
T Type of account
D Description
L Credit limit (only for credit card accounts)
/ Statement balance date
$ Statement balance amount
^ End of entry

Items for a Category List

Field Indicator Explanation
N Category name:subcategory name
D Description
T Tax related if included, not tax related if omitted
I Income category
E Expense category (if category type is unspecified, quicken assumes expense type)
B Budget amount (only in a Budget Amounts QIF file)
R Tax schedule information
^ End of entry

Items for a Class List

Field Indicator Explanation
N Class name
D Description
^ End of entry

Items for a Memorized Transaction List

Immediately preceding the ^ character, each entry must end with one of the following file indicators to specify the transaction type.

  • KC
  • KD
  • KP
  • KI
  • KE

With that exception, memorized transaction entries have the same format as regular transaction entries (non-investment accounts). However, the Date or Num field is included. All items are optional, but if an amortization record is included, all seven amortization lines must also be included.

Field Indicator Explanation
KC Check transaction
KD Deposit transaction
KP Payment transaction
KI Investment transaction
KE Electronic payee transaction
T Amount
C Cleared status
P Payee
M Memo
A Address
L Category or Transfer/Class
S Category/class in split
E Memo in split
$ Dollar amount of split
1 Amortization: First payment date
2 Amortization: Total years for loan
3 Amortization: Number of payments already made
4 Amortization: Number of periods per year
5 Amortization: Interest rate
6 Amortization: Current loan balance
7 Amortization: Original loan amount
^ End of entry

 

Examples of QIF files

Normal Transactions Example

Transaction Item Comment (not in file)
!Type:Bank Header
D6/ 1/94 Date
T-1,000.00 Amount
N1005 Check number
PBank Of Mortgage Payee
L[linda] Category
S[linda] First category in split
$-253.64 First amount in split
SMort Int Second category in split
$-746.36 Second amount in split
^ End of the transaction
D6/ 2/94 Date
T75.00 Amount
PDeposit Payee
^ End of the transaction
D6/ 3/94 Date
T-10.00 Amount
PJoBob Biggs Payee
MJ.B. gets bucks Memo
LEntertain Category
A1010 Rodeo Dr. Address (line 1)
AWaco, Tx Address (line 2)
A80505 Address (line 3)
A Address (line 4)
A Address (line 5)
A Address (line 6)
^ End of the transaction

 

Investment Example

Transaction Item Comment (not in file)
!Type:Invst Header line
D8/25/93 Date
NShrsIn Action (optional)
Yibm4 Security
I11.260 Price
Q88.81 Quantity
CX Cleared Status
T1,000.00 Amount
MOpening Balance Memo
^ End of the transaction
D8/25/93 Date
NBuyX Action
Yibm4 Security
I11.030 Price
Q9.066 Quantity
T100.00 Amount
MEst. price as of 8/25/93 Memo
L[CHECKING] Account for transfer
$100.00 Amount transferred
^ End of the transaction

 

Memorized List Example

Transaction Item Comment (not in file)
!Type:Memorized Header line
T-50.00 Amount
PJoe Hayes Payee
MRent Memo
KC Check transaction
^ End of the transaction
T-25.00 Amount
T-25.00 Company Payee
LTelephone Category
KP Payment transaction
^ End of the transaction

How the browser renders a web page – DEV

How the browser renders a web page

My thinking: if I’m going to build websites that are fast and reliable, I need to really understand the mechanics of each step a browser goes through to render a web page, so that each can be considered and optimised during development. This post is a summary of my learnings of the end-to-end process at a fairly high level.


A lot of this is based on the fantastic (and FREE!) Website Performance Optimization course by Ilya Grigorik and Cameron Pittman on Udacity. I’d highly recommend checking it out.

Also very helpful was the article How Browsers Work: Behind the scenes of modern web browsers by Paul Irish and Tali Garsiel. It’s from 2011 but many of the fundamentals of how browsers work remain relevant at the time of writing this blog post.

Ok, here we go. The process can be broken down into these main stages:

  1. Start to parse the HTML
  2. Fetch external resources
  3. Parse the CSS and build the CSSOM
  4. Execute the JavaScript
  5. Merge DOM and CSSOM to construct the render tree
  6. Calculate layout and paint

Source: How the browser renders a web page – DEV

Vim Stuff

Since the 1970s, Vi and Vim are popular amongst developers and are present on most UNIX-based servers.

These free and open source modal text editors can be a bit hard to use at first, but they are extremely powerful.

Table of Contents  show 

A Quick Intro to Vim

Vi is a modal text editor first released in 1976 for Unix systems. Vim, (Vi Improved) Vi’s successor, was first released in 1991. Despite its very old age, Vim is extremely popular among web developers and system administrators, as it is installed by default on all Unix-based systems (Mac OS and Linux distros).Unlike classic text editors, Vim features different modes used for different operations. Vim has a total of 12 modes, although you will mostly use the following:

  • Insert Mode: This mode is used to insert text by typing, like you would do on any other text editor. To enter insert mode, type i while in command mode.
  • Command Mode: Also named Normal Mode, this mode is used to type Vim commands such as those you’ll find in our Vim Cheat Sheet. To exit insert mode and enter command mode, hit the Esc key of your keyboard.
  • Visual Mode: Similar to command mode, but used to highlight areas of text. Normal commands are run on the highlighted area, which, for instance, can be used to move or edit a selection. Press the v key to start visual mode. To exit visual mode, press the Esc key.

Basics

Let’s start with basic commands that will allow you to write, save and quit files. Remember that these Vim commands need to be typed while in command or visual mode. Exit insert mode by hitting the Esc key, then type the command of your choice.

:e filename Open filename for edition
:w Save file
:q Exit Vim
:q! Quit without saving current file
😡 Write/Save file (if changes has been made) and exit
:sav filename Save current file as filename
. Repeat the last change made in normal mode
5. Repeat 5 times the last change made in normal mode

Moving In The File

Vim features powerful commands that allow you to easily move the cursor position to any desired location within the current file, making it quick and easy to insert text.

k or Up Arrow move cursor up one line
j or Down Arrow move cursor down one line
e move cursor to the end of the word
b move the cursor to the beginning of the word
0 move the cursor to the first non-blank character of the line
G move the cursor to the end of the file
gg move the cursor position to the beginning of the file
L move the cursor to the bottom of the screen
:59 move cursor to line 59. Replace 59 by the desired line number.
% Move cursor to matching parenthesis
[[ Jump to function start
[{ Jump to block start

Cut, Copy & Paste

Vim features powerful functions to cut, copy, and paste. This section of our Vim Cheat Sheet will show you how to easily perform those operations. Please note that y stands for yank in Vim, which in other editors is usually called copy.

y Yank/Copy the selected text to clipboard
p Paste clipboard contents
dd Cut current line
yw Yank/Copy word
yy Yank/Copy current line
y$ Yank/Copy to end of line
D Cut to end of line

Search

Searching a string within a huge file or multiple files can be tricky. Thanks to Vim, using a few commands you can easily find whatever you’re looking for.

/word Search word from top to bottom
?word Search word from bottom to top
* Search the word under cursor
/\cstring Search STRING or string, case insensitive
/jo[ha]n Search john or joan
/\< the Search the, theatre or then
/the\> Search the or breathe
/\< the\> Search the
/\< ¦.\> Search all words consisting of 4 letters
/\/ Search fred but not alfred or frederick
/fred\|joe Search fred or joe
/\<\d\d\d\d\> Search exactly 4 digits
/^\n\{3} Find 3 empty lines
:bufdo /searchstr/ Search in multiple files
bufdo %s/something/somethingelse/g Search something in all the open buffers and replace it with somethingelse

Replace

Similar to Search, Vim features powerful commands to replace any given text. This part of our cheat sheet contains Vim commands for replacing any portion of text with another.

:%s/old/new/g Replace all occurrences of old with new in file
:%s/onward/forward/gi Replace onward with forward, case insensitive
:%s/old/new/gc Replace all occurrences with confirmation
:2,35s/old/new/g Replace all occurrences between lines 2 and 35
:5,$s/old/new/g Replace all occurrences from line 5 to EOF
:%s/^/hello/g Replace the beginning of each line by hello
:%s/$/Harry/g Replace the end of each line by Harry
:%s/onward/forward/gi Replace onward with forward, case insensitive
x Delete character
:%s/ *$//g Delete all white spaces and keep any non-blank character
:g/string/d Delete all lines containing string
:v/string/d Delete all lines not containing string
:s/Bill/Steve/ Replace the first occurrence of Bill with Steve in current line
:s/Bill/Steve/g Replace Bill with Steve in current line
:%s/Bill/Steve/g Replace Bill with Steve in all of the file
:%s/^M//g Delete DOS carriage returns (^M)
:%s/\r/\r/g Transform DOS carriage returns in returns
:%s#<[^>]\+>##g Delete HTML tags but keep text
:%s/^\(.*\)\n\1$/\1/ Delete lines that appear twice
Ctrl+a Increment number under the cursor
Ctrl+x Decrement number under cursor
ggVGg? Change text to Rot13

Case

Vim provides very interesting commands to deal with case. Let’s continue to explore our Vim Cheat Sheet with super useful case-related commands.

Vu Lowercase line
VU Uppercase line
g~~ Invert case
vEU Switch word to uppercase
vE~ Modify word case
ggguG Set all text to lowercase
gggUG Set all text to uppercase
:set ignorecase Ignore case in searches
:set smartcase Ignore case in searches except if an uppercase letter is used
:%s/\<./\u&/g Sets the first letter of each word to uppercase
:%s/\<./\l&/g Sets the first non-blank character of each word to lowercase
:%s/.*/\u& Sets the first character of the line to uppercase
:%s/.*/\l& Sets the first character of the line to lowercase

Read and Write Files

Vim allows easy manipulation of files. Listed below are a few examples of file manipulation with Vim.

:1,10 w outfile Save lines 1 to 10 in outfile
:1,10 w >> outfile Append lines 1 to 10 to outfile
:r infile Insert the content of infile
:23r infile Insert the content of infile under line 23

File Explorer

Vim features a built-in file explorer that allows its users to quickly visualize and open files in the editor.

:e . Open integrated file explorer
:Sex Split window and open integrated file explorer
:Sex! Same as :Sex but splits window vertically
:browse e Graphical file explorer
:ls List buffers
:cd .. Move to parent directory
:args List files
:args *.php Open file list
:grep expression *.php Return a list of .php files contening expression
gf Open file name under cursor

Interacting With Unix

As Vi and Vim were initially built for Unix systems, the text editor can interact with the OS.

:!pwd Execute the pwd Unix command, then return to Vi
!!pwd Execute the pwd unix command and insert output in file
:sh Temporary return to Unix
$exit Return to Vi

Alignment

Using Vim, it’s possible to automatically align lines using a few simple commands. Here are the main important ones:

:%!fmt Align all lines
!}fmt Align all lines at the current position
5!!fmt Align the next 5 lines

Tabs and Windows

Vim can use various tabs and windows, which is very useful for working with many files at once.

:tabnew Create/Open a new tab
gt Show next tab
:tabfirst Show first tab
:tablast Show last tab
:tabm n(position) Rearrange tabs
:tabdo %s/foo/bar/g Execute a command in all tabs
:tab ball Puts all open files in tabs (Each in a new tab)
:new abc.txt Edit abc.txt in new window

Window Spliting

As a web developer, I always like to split my Vim editor in two parts, one for my HTML and one for my CSS stylesheet. This part of our Vim Cheat Sheet describes how to split the main editor window.

:e filename Edit filename in current window
:split filename Split the window and open filename
ctrl-w up arrow Put cursor in top window
ctrl-w ctrl-w Put cursor in next window
ctrl-w_ Maximize current window vertically
ctrl-w| Maximize current window horizontally
ctrl-w= Gives the same size to all windows
10 ctrl-w+ Add 10 lines to current window
:vsplit file Split window vertically
:sview file Same as :split in Read Only Mode
:hide Close current window
:­nly Close all windows, except current
:b 2 Open #2 in this window

Auto Completion

Like much more modern editors, Vim can auto-complete your code and use dictionaries.

Ctrl+N Ctrl+P (in insert mode) Complete word
Ctrl+x Ctrl+l Complete line
:set dictionary=dict Define dict as a dictionary
Ctrl+x Ctrl+k Complete with dictionary

Markers

Vim allows its users to set marks at a position of their choice, so they can easily jump back to that predefined position. A must when working with large files.

m {a-z} Marks current position as {a-z}
‘ {a-z} Move to position {a-z}
Move to previous position

Abbreviations

Another handy Vim function is the possibility to define abbreviations.

:ab mail mail@provider.org Define mail as abbreviation of mail@provider.org

Text Indent

Indentation is the key to readable and easy-to-maintain code. Vim possesses a few commands that will come in handy for indenting any file.

:set autoindent Turn on auto-indent
:set smartindent Turn on intelligent auto-indent
:set shiftwidth=4 Define 4 spaces as indent size
ctrl-t, ctrl-d Indent/un-indent in insert mode
>> Indent
<< Un-indent
=% Indent the code between parenthesis
1GVG= Indent the whole file

Syntax Highlighting

Syntax highlighting is often very useful for preventing coding mistakes and typos. Vim can work with many different syntax highlighting modes, depending on which programming language you are coding with.

:syntax on Turn on syntax highlighting
:syntax off Turn off syntax highlighting
:set syntax=perl Force syntax highlighting