5초마다 실행되는 systemd 서비스를 timer를 이용해 만들어보자.


환경

  • Ubuntu 18.04


목표

  • systemd의 서비스를 특정 날짜에 혹은 반복적으로 crontab처럼 사용하고 싶을때 사용하는 timer의 예제를 직접 작성해본다.
  • systemd의 timer는 OnActiveSec=, OnBootSec=, OnStartupSec=, OnUnitActiveSec=, OnUnitInactiveSec=와 같은 옵션과 OnCalendar=를 사용하는데 아래 예제에서는 OnCalendar=를 사용합니다.


systemd service and timer

systemd

  • systemd: Wikipedia에 따르면 init 시스템을 대신해 사용자 공간을 부트스트래핑하고 최종적으로 모든 프로세스들을 관리하는 시스템이라고 한다.

service

  • service: systemd에 있는 unit으로 systemd에 의해 관리되는 프로세스에 대해 기술한 파일이며 이를 통해 어떤 서비스나 프로그램이 실행된다.

timer

  • timer: systemd에 있는 unit으로 특정 시간이나 이벤트에 따라 사용할 service를 위해 사용한다.


systemd service timer 파일 예제

만들어야할 파일

  • 사용할 service 파일과 이벤트를 등록할 timer가 필요하다.
  • timer로 돌리려는 service는 파일명이 둘이 같아야합니다!
  • 예제에서 이름은 각각 on-calendar.service 그리고 on-calendar.timer입니다.


on-calendar.service

[Unit]
Description=Test for OnCalendar timer

[Service]
Type=oneshot
ExecStart=/usr/bin/test_on_calendar.sh

[Install]
WantedBy=multi-user.target
  • Description: 이 서비스 파일에 대한 설명입니다.
  • Type: 실행할 서비스의 타입에 대한부분으로 simple, oneshot 그리고 forking과 같은 다양한 타입이 있지만 여기서는 oneshot으로 했습니다. oneshot는 한번 사용하고 끝낼 서비스에 주로 사용되며 서비스의 프로세스가 끝날때까지 기다립니다. 해당 옵션을 사용하면 사용할때 activating으로 바뀌고 다 끝나면 inactive가 됩니다.
  • ExecStart: 해당 서비스가 실행할 파일의 절대경로를 넣어주시면 됩니다.
  • WantedBy: Unit이 어떻게 활성화(enable)될 것인지에 대한 부분이며 systemctl enable 명령어를 사용하면 해당 부분의 target에 명시된 대로 /etc/systemd/system 아래 .wants에 들어가게 됩니다. 부팅시 속한 .wants에 따라서 실행되게 됩니다.

/usr/bin/test_on_calendar.sh

  • 사용할 실행 스크립트입니다.
#!/bin/bash

date >> /tmp/OnCalendarLog.txt
  • 실행 권한을 줍니다.
chmod a+x /usr/bin/test_on_calendar.sh


on-calendar.timer

[Unit]
Description=Test for OnCalendar timer

[Timer]
OnCalendar=*-*-* *:*:0/5
AccuracySec=1s

[Install]
WantedBy=timers.target
  • Description: 이 타이머에 대한 설명입니다.
  • OnCalendar: 언제 혹은 어느 주기에 서비스를 실행할지에 대한 옵션입니다. 형식은 년-월-일 시:분:초로 나타냅니다. 만약 n초마다 서비스를 실행하고 싶으면 위의 예제처럼 *-*-* *:*:0/n으로 해주면 되며 시나 분도 똑같습니다. 해당 옵션을 다양하게 사용가능합니다.
  • AccuracySec: 타이머를 돌릴때 확인하는 주기를 의미합니다. 기본값은 1분이며 1분마다 확인하여 이벤트가 발생할 시간이 맞다면 서비스를 실행합니다. 만약 초단위로 실행을 하고 싶으면 위의 예제처럼 AccuracySec=1s를 추가해야합니다.
  • WantedBy: Unit이 어떻게 활성화(enable)될 것인지에 대한 부분이며 systemctl enable 명령어를 사용하면 해당 부분의 target에 명시된 대로 /etc/systemd/system 아래 .wants에 들어가게 됩니다. 부팅시 속한 .wants에 따라서 실행되게 됩니다.


systemd service timer 사용 예제

부팅 후에도 사용할 수 있게 enable

$ systemctl enable on-calendar.timer

systemd timer 시작

$ systemctl restart on-calendar.timer

timer 등록 확인

$ systemctl list-timers
NEXT                         LEFT          LAST                         PASSED       UNIT                         ACTIVATES
Sun 2020-02-09 00:02:35 KST  1s left       Sun 2020-02-09 00:02:30 KST  2s ago       on-calendar.timer            on-calendar.service

예제 파일 결과

$ cat /tmp/OnCalendarLog.txt
Sun Feb  9 00:02:10 KST 2020
Sun Feb  9 00:02:15 KST 2020
Sun Feb  9 00:02:20 KST 2020
Sun Feb  9 00:02:25 KST 2020
Sun Feb  9 00:02:30 KST 2020


참고자료

Make systemd service which runs every 5 seconds by using timer.


Environment and Prerequisite

  • Ubuntu 18.04


Goal

  • Create timer example which is for using systemd service in specific date, time or event.
  • systemd timer have options like OnActiveSec=, OnBootSec=, OnStartupSec=, OnUnitActiveSec=, OnUnitInactiveSec= and OnCalendar=. This post example use OnCalendar=


systemd service and timer

systemd

  • systemd: According to Wikipedia, systemd is a software suite that provides an array of system components for Linux operating systems.

service

  • service: A unit configuration file whose name ends in “.service” encodes information about a process controlled and supervised by systemd.

timer

  • timer: A unit configuration file in systemd which is for using service in specific date, time or event.


systemd service timer file example

Necessary files

  • We need service and timer file.
  • service which is run by timer should have same file name with that timer
  • In this example, each name is on-calendar.service and on-calendar.timer


on-calendar.service

[Unit]
Description=Test for OnCalendar timer

[Service]
Type=oneshot
ExecStart=/usr/bin/test_on_calendar.sh

[Install]
WantedBy=multi-user.target
  • Description: Description of this file
  • Type: It is type of service which can has simple, oneshot, forking or etc. This example use oneshot. oneshot is used for short-lived and one-off tasks because it blocks on operation and wait process to be finished. When option is oneshot, then its service state will be activating while running and will be changed to inactive after it.
  • ExecStart: Give absolute path of running file or program.
  • WantedBy: It is for specifying how a unit should be enabled. By using systemctl enable command its symbolic link is added to .wants directory under /etc/systemd/system depending on its specified target. It will be run after booting depends on its .wants

/usr/bin/test_on_calendar.sh

  • Script for running.
#!/bin/bash

date >> /tmp/OnCalendarLog.txt
  • Give execution permission
chmod a+x /usr/bin/test_on_calendar.sh


on-calendar.timer

[Unit]
Description=Test for OnCalendar timer

[Timer]
OnCalendar=*-*-* *:*:0/5
AccuracySec=1s

[Install]
WantedBy=timers.target
  • Description: Description of this file
  • OnCalendar: This options specifies when to run or how frequently run. Its format is YEAR-MONTH-DAY HOUR:MINUTE:SECOND. If you like to run service in every n seconds, just make it to *-*-* *:*:0/n. It is also same in hour or minute. It can be used in many various ways.
  • AccuracySec: This unit is used to set the level of accuracy with which the timer should be adhered to. Its default value is 1 minute. So if you want to run timer in second, you need to set AccuracySec=1s like above example.
  • WantedBy: It is for specifying how a unit should be enabled. By using systemctl enable command its symbolic link is added to .wants directory under /etc/systemd/system depending on its specified target. It will be run after booting depends on its .wants


systemd service timer usage example

Make it to enable

$ systemctl enable on-calendar.timer

systemd timer start

$ systemctl restart on-calendar.timer

timer list check

$ systemctl list-timers
NEXT                         LEFT          LAST                         PASSED       UNIT                         ACTIVATES
Sun 2020-02-09 00:02:35 KST  1s left       Sun 2020-02-09 00:02:30 KST  2s ago       on-calendar.timer            on-calendar.service

Example result

$ cat /tmp/OnCalendarLog.txt
Sun Feb  9 00:02:10 KST 2020
Sun Feb  9 00:02:15 KST 2020
Sun Feb  9 00:02:20 KST 2020
Sun Feb  9 00:02:25 KST 2020
Sun Feb  9 00:02:30 KST 2020


Reference

AWS CLI를 통해서 EC2 인스턴스를 생성, 나열 그리고 삭제를 해보자.


환경

  • Ubuntu 18.04
  • AWS CLI
  • Bash shell(/bin/bash)


과정

  1. AWS CLI 설치
  2. 기본 환경 설정(구성 및 자격 증명 설정)
  3. EC2 인스턴스 생성, 나열 그리고 삭제


AWS CLI 설치

패키지 업데이트 및 업그레이드

sudo apt-get update -y && sudo apt-get upgrade -y

pip3을 설치

sudo apt-get install python3-pip

AWS CLI 설치

  • aws 명령어를 인식하지 못하면 로그아웃하고 다시 로그인한다.
pip3 install awscli --upgrade --user

AWS CLI 버전 확인

$ aws --version
aws-cli/1.16.310 Python/3.6.9 Linux/4.15.0-72-generic botocore/1.13.46


기본 환경 설정(구성 및 자격 증명 설정)

사전 점검 사항

aws configure

$ aws configure
AWS Access Key ID [None]: [YOUR KEY]
AWS Secret Access Key [None]: [YOUR KEY]
Default region name [None]: ap-northeast-2
Default output format [None]: json

~/.aws/credentials 설정 확인

$ cat ~/.aws/credentials
[default]
aws_access_key_id = [YOUR KEY]
aws_secret_access_key = [YOUR KEY]

~/.aws/config 설정 확인

$ cat ~/.aws/config
[default]
region = ap-northeast-2
output = json


EC2 인스턴스 생성, 나열 그리고 삭제

사전 점검 사항

  • 만들어진 EC2 보안 그룹이 있다고 가정
  • 보안 그룹은 AWS에서 만들 수 있으며 테스트를 위해 만든 보안 그룹의 인바운드는 SSH 포트만 열고 아웃바운드는 모두 열어놓았다.

키 페어 생성

  • 아래 명령어로 만들어진 키 페어는 따로 보관
  • 기존에 있는 키 페어를 사용해도 무관하다. 단, 공개키는 AWS에 저장되어 있고 개인키는 보관하고 있어야 한다.
aws ec2 create-key-pair --key-name TestKeyPair --query 'KeyMaterial' --output text > TestKeyPair.pem

EC2 인스턴스 생성

  • --image-id: 인스턴스에 사용할 이미지 ID
  • ami-082bdb3b2d54d5a19: Ubuntu Server 16.04 LTS (HVM), SSD Volume Type
  • --count: 생성할 인스턴스의 수
  • --key-name: 사용할 키 페어의 키
  • TestKeyPair: 위에서 만든 키 페어
  • --security-group-ids: 보안그룹 ID
aws ec2 run-instances --image-id ami-082bdb3b2d54d5a19 --count 1 --instance-type t2.micro --key-name TestKeyPair --security-group-ids [YOUR SECURITY GROUP ID]

EC2 인스턴스 나열

  • --filters: 인스턴스들을 불러올 때 사용할 필터로 예제에서는 instance-typet2.micro인 인스턴스들만 가져옴
  • --query: 인스턴스들을 불러와서 보여줄때 사용할 수 있는 옵션으로 예제에서는 인스턴스들의 ID만 나열하도록함
aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro" --query "Reservations[].Instances[].InstanceId"

EC2 인스턴스 연결

  • 키 파일 권한 설정
chmod 400 TestKeyPair.pem
  • ssh를 이용해 인스턴스에 접속
ssh -i "TestKeyPair.pem" [USER NAME]@[PUBLIC IP or PUBLIC AWS DNS]

EC2 인스턴스 삭제

  • --instance-ids: 인스턴스 ID를 이용해 삭제
aws ec2 terminate-instances --instance-ids [YOUR INSTANCE ID]


참고자료

Create, list and delete EC2 instance using AWS CLI


Environment and Prerequisite

  • Ubuntu 18.04
  • AWS CLI
  • Bash shell(/bin/bash)


Process

  1. Install AWS CLI
  2. Basic Setting(Configuration and Credential File Settings)
  3. EC2 Instance Create, List and Delete


Install AWS CLI

Package update and upgrade

sudo apt-get update -y && sudo apt-get upgrade -y

Install pip3

sudo apt-get install python3-pip

Install AWS CLI

  • Logout and login again if aws command is not work.
pip3 install awscli --upgrade --user

Check AWS CLI version

$ aws --version
aws-cli/1.16.310 Python/3.6.9 Linux/4.15.0-72-generic botocore/1.13.46


Basic Setting(Configuration and Credential File Settings)

Before setting

aws configure

$ aws configure
AWS Access Key ID [None]: [YOUR KEY]
AWS Secret Access Key [None]: [YOUR KEY]
Default region name [None]: ap-northeast-2
Default output format [None]: json

Check ~/.aws/credentials setting

$ cat ~/.aws/credentials
[default]
aws_access_key_id = [YOUR KEY]
aws_secret_access_key = [YOUR KEY]

Check ~/.aws/config 설정 확인 setting

$ cat ~/.aws/config
[default]
region = ap-northeast-2
output = json


EC2 Instance Create, List and Delete

Before setting

  • Consider that there is already made EC2 security group
  • You can make security group in aws website. My security group opens only ssh port in inbound and opens all ports in outbound.

Create key pair

  • Store key pair in your computer which is made from below command.
  • You can use your own key pair. However, public key should be in AWS and private key should be kept in your computer.
aws ec2 create-key-pair --key-name TestKeyPair --query 'KeyMaterial' --output text > TestKeyPair.pem

Create EC2 instance

  • --image-id: Instance image ID
  • ami-082bdb3b2d54d5a19: Ubuntu Server 16.04 LTS (HVM), SSD Volume Type
  • --count: Number of instances
  • --key-name: Key pair key
  • TestKeyPair: The key pair that we made above
  • --security-group-ids: Security group ID
aws ec2 run-instances --image-id ami-082bdb3b2d54d5a19 --count 1 --instance-type t2.micro --key-name TestKeyPair --security-group-ids [YOUR SECURITY GROUP ID]

List EC2 instances

  • --filters: It is filter for instances. In this example, it gets instances of which instance-type is t2.micro.
  • --query: It is option for showing results of instances. In this example, it shows only ID of instances.
aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro" --query "Reservations[].Instances[].InstanceId"

Connect to EC2 instance

  • Set key file permission
chmod 400 TestKeyPair.pem
  • Access to instance using ssh
ssh -i "TestKeyPair.pem" [USER NAME]@[PUBLIC IP or PUBLIC AWS DNS]

Delete EC2 instance

  • --instance-ids: Delete using instance ID
aws ec2 terminate-instances --instance-ids [YOUR INSTANCE ID]


Reference

네트워크 본딩(Network Bonding)을 해보고 실제 본딩된 slave 인터페이스를 끊어도 네트워크가 잘 되는지 확인해보자.


환경

  • CentOS 7.7.1908
  • Ubuntu 18.04
  • VirtualBox
  • Bash shell(/bin/bash)


기본 네트워크 구조

  • NIC 2개를 본딩
  • 호스트 전용 어댑터(Host-only Adapter)를 통해 각 VM의 2개의 NIC는 vboxnet0에 연결됨
  • VirtualBox에서 설정-네트워크에서 어댑터1에는 기존 NAT를 연결
  • VirtualBox에서 설정-네트워크에서 어댑터2와 어댑터3를 새로 연결


시나리오

  1. Client에서 Server에 Bonding된 IP주소로 Ping을 보낸다.
  2. Server의 active slave를 Down으로 만든다.
  3. 끊기지 않고 Ping이 계속 가는지 확인한다.


네트워크 본딩 설정

CentOS

centos-client

  • bond0
  • /etc/sysconfig/network-scripts/ifcfg-bond0
TYPE=Bond
BOOTPROTO=static
DEFROUTE=no
NAME=bond0
DEVICE=bond0
ONBOOT=yes
PREFIX=24
IPADDR=192.168.99.101
BONDING_OPTS="mode=1 miimon=100 fail_over_mac=1"
  • enp0s8
  • /etc/sysconfig/network-scripts/ifcfg-enp0s8
NAME=enp0s8
DEVICE=enp0s8
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
  • enp0s9
  • /etc/sysconfig/network-scripts/ifcfg-enp0s9
NAME=enp0s9
DEVICE=enp0s9
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes

centos-server

  • bond0
  • /etc/sysconfig/network-scripts/ifcfg-bond0
TYPE=Bond
BOOTPROTO=static
DEFROUTE=no
NAME=bond0
DEVICE=bond0
ONBOOT=yes
PREFIX=24
IPADDR=192.168.99.102
BONDING_OPTS="mode=1 miimon=100 fail_over_mac=1"
  • enp0s8
  • /etc/sysconfig/network-scripts/ifcfg-enp0s9
NAME=enp0s8
DEVICE=enp0s8
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
  • enp0s9
  • /etc/sysconfig/network-scripts/ifcfg-enp0s9
NAME=enp0s9
DEVICE=enp0s9
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes


Ubuntu

  • 18.04는 netplan을 이용해 네트워크를 세팅한다.
  • yaml 파일을 만들고 sudo netplan apply를 통해서 네트워크 설정들을 적용

ubuntu-client

  • /etc/netplan/50-cloud-init.yaml
# This file is generated from information provided by
# the datasource.  Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
    ethernets:
        enp0s3:
            dhcp4: true
        enp0s8:
            dhcp4: false
        enp0s9:
            dhcp4: false
    version: 2
    bonds:
        bond0:
            dhcp4: false
            addresses:
                - 192.168.225.101/24
            gateway4: 192.168.225.1
            interfaces:
                - enp0s8
                - enp0s9
            parameters:
                mode: active-backup
                primary: enp0s8
                fail-over-mac-policy: active
                mii-monitor-interval: 100

ubuntu-server

  • /etc/netplan/50-cloud-init.yaml
# This file is generated from information provided by
# the datasource.  Changes to it will not persist across an instance.
# To disable cloud-init's network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
    ethernets:
        enp0s3:
            dhcp4: true
        enp0s8:
            dhcp4: false
        enp0s9:
            dhcp4: false
    version: 2
    bonds:
        bond0:
            dhcp4: false
            addresses:
                - 192.168.225.102/24
            gateway4: 192.168.225.1
            interfaces:
                - enp0s8
                - enp0s9
            parameters:
                mode: active-backup
                primary: enp0s8
                fail-over-mac-policy: active
                mii-monitor-interval: 100


테스트

각각 active slave 확인

  • 명령어: cat /proc/net/bonding/bond0
  • 왼쪽이 Client 오른쪽이 Server
  • Active slave: enp0s8


Client -> Server ping 시작



Ping이 끊기지 않고 제대로 가는지 확인


Server에서 active slave가 누군지 확인

  • enp0s8 -> enp0s9


참고자료