레이블이 NET-NTP인 게시물을 표시합니다. 모든 게시물 표시
레이블이 NET-NTP인 게시물을 표시합니다. 모든 게시물 표시

4/25/2020

GPS/GNSS Device 관련내용

1. GPS/GNSS 의 구조 

일반적인 GPS는 Serial 통신으로 설정이 되어있으며, Chip에따라 속도변경도 가능하다.
또한 Serial Protocol인 NMEA를 이용하여 GPS의 정보를 Parsing해서 관련정보를 얻는다.

GPS의 Chipset 
  https://wiki.openstreetmap.org/wiki/GPS_Chipset

GPS와 GNSS 차이
  https://www.semiconductorstore.com/blog/2015/What-is-the-Difference-Between-GNSS-and-GPS/1550/


1.1 GPS의 PPS역할 

GPS의 Serial은 1Hz를 맞추어 Serial로 개별 Commad를 Update하지만, Serial에 대한 Latency가 존재하므로
실제로 정밀하게 시간을 맞추지 못한다.


  • PPS의 역할 및 동작 
GPS는 PPS라는 외부 Pin이 존재하며, PPS Pin의 1Hz에 맞추어 Serial의 NMEA정보는 보낸다.
하지만 PPS Pin 기준으로 1Hz마다 Serial의 Data를 전송하더라도 Latency는 존재하며, 이를  맞추기 위해서 PPS Pin에 맞추어 시간보정가능하다.

1 Pulse 다양하게 설정 될 수 있다고 함 
  https://en.wikipedia.org/wiki/Pulse-per-second_signal

1 Pulse 100ms 언급
  http://zone.ni.com/reference/en-XX/help/373629D-01/nisynclv/ppstimeprotocol/
  https://www.frontiersin.org/articles/10.3389/fbuil.2018.00082/full

GPS의 Serial 과 PPS를 이용한 NTP Server
  https://www.satsignal.eu/ntp/Raspberry-Pi-NTP.html
  https://vanheusden.com/time/rpi_gpio_ntp/

GPS의 PPS 부분 Time Sync
  https://onlinelibrary.wiley.com/doi/pdf/10.4218/etrij.08.0106.0306


  • PPS 이용한 시간보정방법 (Latency 문제)
예를들면, 070844.389 , 7시 08분 44.389 초를 Serial를 통해 받으면 Serial Latency가 존재하므로 이 시간으로 바로 설정하면
시간이 정확하지 않지만, 다음은 분명 070845.389로 받을 것이므로, 다음 PPS 신호에 맞추어서 이 시간으로 설정하면 정확한 시간으로 설정 될 것 같다.


  • NTP의 시간보정방법
NTP Server의 시간이 정확하다는 가정하에 NTP Client는 NTP Server와 통신을 한 후 각 Time offset를 이용하여 구하는데, 의외로 재미있지만,
Network의 상황이 불안정해서 정확한 Time offset은 구하기 힘들다면 어떻게 되는지가 궁금하다.
  https://en.wikipedia.org/wiki/Network_Time_Protocol


1.2 GPS의 Antenna 

GPS에 따라 LNA의 존재 여부에 따라 각 Antenna 연결부분이 달라지며, 각 HW 부분을 확인하자.

LNA (AMP)
  https://en.wikipedia.org/wiki/Low-noise_amplifier

  • GPS의 Antenna Type
  1. Passive Antenna: Antenna에 내부에 LNA가 없음
  2. Active Antenna:  Antenna에 내부에 LNA가 있음   
Passive 와 Active Antenna 차이 
  https://techship.com/faq/difference-active-and-passive-antenna/


1.3  GPS/GNSS Serial 정보 

  • GPS/GNSS Serial Protocol 
  1. NMEA기반으로 Serial 정보
  2. Ublox Protocol
상위와 같이 두 가지로 제공을 해주는 것으로 보이며, 주로 NMEA를 기반으로 많이 사용하는 것 같다.


2. NMEA의 기본구조 

GPS의 Serial 부분에서 기본 시간정보좌표정보를 얻을 수 있으며, 별도의 PPS Pin 연결부분을 이용하여 정확히 1Hz마다 정보를 Update를 한다
Baudrate는 default 9600bps이며, 변경도 가능하다고 하다고 하지만, 변경의 의미는 크게 없을 것 같다.

기본구조 거의 동일하며, Preamble "$" 시작하여  Checksum(*2bytes) + <CR><LF>으로 종료되어진다.

  • Preamble 이후 
다음과 같이 시작이 되어지므로, 실제 분석을 하려고 하며, 이 뒤의 개별 Command를 가지고 봐야한다.
  1. GP,GN,GL : GPS + GLONASS
  2. GP,GL : GPS only
  3. GP,GN,GL : GLONASS only 

NMEA 관련내용 (ASCII Code구성)
이 부분 Manual을 자세히 읽어보면 대충 어떻게 동작하는지 쉽게 이해한다.
  https://www.gpsinformation.org/dale/nmea.htm

NMEA 의 Checksum 의 구조 
  https://nmeachecksum.eqth.net/

NMEA Command 
  https://www.rhydolabz.com/documents/25/NMEA-CommandManual_%28FTX-HW-13002%29.pdf


2.1 NMEA의 PMTK 


PMTK 설정
  https://www.sparkfun.com/datasheets/GPS/Modules/PMTK_Protocol.pdf
  https://www.rhydolabz.com/wiki/?p=16770

Satelite Search 할 경우 각 Chip마다 다를 수 있으며, 관련부분은 PMTK Command를 보면될 것 같으며, 이외에도
다양한 Command로 GPS Chip을 Control 가능한 것 같다.

세부부분은 각각의 GPS Chip의 Datasheet를 확인하자

  • 위성 Search 기능 
GLONASS satellites only
GPS satellites only
GLONASS and GPS satellites
BDS satellites only
..

$PMTK313,1*2E<CR><LF>  //Enable to search a SBAS satellite or not

2.2 NMEA 의 기본분석 

아래의 Command들 중심으로 각 검색을 하면, 각 1Hz 단위로 Update가 진행되며, 시간정보는 GPS내부에 RTC가 별도로 존재하기 때문에,
연결이 되지 않아도 시간정보를 정확하게 줄 수 있는 것으로 보인다.

  • NMEA 의 RMC로 시간과 날짜 와 좌표분석
GPS의 NMEA의 시간정보와 위치정보를 동시에 얻을 수 있으며, 안테나 문제로 연결이 안될 경우 시간정보라도 확인가능

RMC 의 시간정보 와 날짜정보 와 위치정보  
NMEA sentence format: $xxRMC,time,status,lat,NS,long,EW,spd,cog,date,mv,mvEW,posMode*cs <CR><LF>
Valid fix: $GPRMC,083559.34,A,4717.11437,N,00833.91522,E,0.004,77.52,091202,,,A*00
No fix: $GPRMC,,V,,,,,,,,,,N*00

각 Argument는 ","로 구분되며, 1Hz 주기로 Update 됨 

1st Argument (Time 분석): 083559.34
-  08시 35분 59.34초  UTC  (Local Time: Seoul +9)

2nd Argument (동작여부): A or V
-  Status A=active or V=Void.

3st/4st Argument (Latitude): 4717.11437,N
-  위도 Latitude 47 deg 17.11437' N

5st/6st Argument (Longitude): 00833.91522,E
-  경도 Longitude 008 deg 33.91522' E

9st Argument (Date 분석): 091202
-  9월 12일 2002년 


  • RMC 정보 간단히 확인
$ cat /dev/ttyxx | grep RMC   //GPS Serial 3Hz 단위 문제있음
//No fix 의 예로 상위 V로 쉽게 파악 가능하며, 1Hz 단위로 동작해야한다 
$GPRMC,070050.799,V,,,,,0.00,0.00,060180,,,N*47 // 07 시 00분 50.799초 UTC  
$GPRMC,070053.799,V,,,,,0.00,0.00,060180,,,N*44
$GPRMC,070056.799,V,,,,,0.00,0.00,060180,,,N*41
$GPRMC,070059.799,V,,,,,0.00,0.00,060180,,,N*4E
$GPRMC,070102.799,V,,,,,0.00,0.00,060180,,,N*41

$ cat /dev/ttyxx | grep RMC   //GPS Serial 1Hz 단위 문제없음
$GPRMC,064147.087,V,,,,,0.00,0.00,260620,,,N,V*38 // 06 시 41분 47.087초 UTC 이와 PPS와 연동하여 정확한 시간보정 
$GPRMC,064148.087,V,,,,,0.00,0.00,260620,,,N,V*37
$GPRMC,064149.087,V,,,,,0.00,0.00,260620,,,N,V*36
$GPRMC,064150.087,V,,,,,0.00,0.00,260620,,,N,V*3E
$GPRMC,064151.087,V,,,,,0.00,0.00,260620,,,N,V*3F
$GPRMC,064152.087,V,,,,,0.00,0.00,260620,,,N,V*3C
$GPRMC,064153.087,V,,,,,0.00,0.00,260620,,,N,V*3D
$GPRMC,064154.087,V,,,,,0.00,0.00,260620,,,N,V*3A

//상위는 baud rate를 별도로 설정을 안했으며, minicom에서 재 테스트 진행 
$ minicom -s   // 다 설정진행   Ctrl+A , Z 종료 
$ minicom -D /dev/ttyxxx    // Baudrate 만 설정 


RMC 분석
  https://www.gpsinformation.org/dale/nmea.htm#RMC

  • NMEA 의 GGA로 시간과 좌표분석 
위성을 제대로 못 찾는다면, 시간이라도 확인

GGA 의 좌표정보
NMEA sentence format: $xxGGA,time,lat,NS,long,EW,quality,numSV,HDOP,alt,M,sep,M,diffAge,diffStation*cs<CR><LF>
Valid fix: $GPGGA,092725.00,4717.11399,N,00833.91590,E,1,08,1.01,499.6,M,48.0,M,,*5B

각 Argument는 ","로 구분되며, 1Hz 주기로 Update 됨 

1st Argument (Time 분석): 092725.00
-  09시 27분 25.00초  UTC  (Local Time: Seoul +9)

2nd/3st Argument (Latitude): 4717.11399,N
-  위도 Latitude 47 deg 17.11399' N

4st/5st Argument (Longitude): 00833.91590,E
-  경도 Longitude 008 deg 33.91590' E

9st/10st Argument (Altitude): 499.6,M
-  높이/고도 Altitude  499.6 Meter above mean sea level

11st/12st Argument (일반적으로 이 정보까지는 필요없을 것 같음): 48.0,M
-  해상높이  48.0 Height of geoid (mean sea level) above WGS84



  • CGA 정보 간단히 확인
$ cat /dev/ttyxx | grep GGA   //GPS Serial 
//만약 동작하지 않는다면,아래와 같이 동작 다만 1Hz단위인지 확인 
$GPGGA,061713.087,,,,,0,0,,,M,,M,,*45 // 06 시 17분 13.087초 
$GPGGA,061714.087,,,,,0,0,,,M,,M,,*42
$GPGGA,061715.087,,,,,0,0,,,M,,M,,*43
$GPGGA,061716.087,,,,,0,0,,,M,,M,,*40
$GPGGA,061717.087,,,,,0,0,,,M,,M,,*41

GGA 분석
  https://www.gpsinformation.org/dale/nmea.htm#GGA


3. Ublox Protocol (참조)

NMEA이외에도 Ublox의 Protocol도 존재하는 것으로 보임

  https://www.sparkfun.com/datasheets/GPS/Modules/u-blox5_Protocol_Specifications(GPS.G5-X-07036).pdf
  https://gpsd.gitlab.io/gpsd/ubxtool.html


4. GPS 관련소스 및 Parsing 부분

Ublox 와 NMEA기반의 Parser가 다르며, 각 정보의 구조가 다르다.

GPS Parsing 관련소스  
  https://github.com/JeonghunLee/lora_gateway/blob/master/libloragw/src/loragw_gps.c
  https://github.com/JeonghunLee/lora_gateway/blob/master/libloragw/inc/loragw_gps.h
  https://github.com/JeonghunLee/lora_gateway/blob/master/libloragw/tst/test_loragw_gps.c

1/27/2020

systemd 로만 관리될 경우 정리

1. systemd 로 부팅


1.1 systemctl 사용법

systemd 에서는 기본 control은 systemctl 이지만 이외에도 사용되어지는 command들이 존재하며 이부분은 이전 내용참조

  • systemctl 와 이외 사용되어지는 명령어 사용법 
  1. systemctl  사용법 
  2. networkctl 사용법 
  3. timedatectl 사용법 

systemctl 및 이외 명령 관련내용 참조  (반드시 참고)
  https://ahyuo79.blogspot.com/2017/03/systemctl.html

systemctl Manual 
  https://www.freedesktop.org/software/systemd/man/systemctl.html#


2. systemd의 Unit 구성 및 종류


  • Unit의 종류 (11개의 종류이지만 필요한것만 사용)
  1. *.service units : 주로 daemon 과 일반 process로 구성
  2. *.socket units:  IPC or Socket 기반의 활동 (encapsulate동작)
  3. *.target units:  Unit들을 group 화 하고 boot 동기화를 할때 유용
  4. *.device units:  Kernel device를 사용할 경우 udev sys
  5. *.mount units:  filesystem 안에 mount point
  6. *.automount units:  filesystem의 automount
  7. *.timer units: 다른 unit의 timer기반의 trigger로 사용
  8. *.swap units:  mount unit 과 유사하며 memory sway 과 OS의 file (encapsulate동작)
  9. *.path units: path 기반으로 변경될 때 동작되는 구조
  10. *.slice units: group unit으로 scope와 service를 계층으로 관리가 가능
  11. *.scope units:  service unit과 거의 유사하지만 외부 process 관리목적

상위 이외에도 systemd.exec 및 systemd.kill 존재하는데, 중복이 되는 것을 알수 있으며,  각 실행파일이 있으므로, 
모든 Section의 Directives의 Index에서 세부파악하자 

모든 Section의 Directives(Option) Index (중요)

  • Unit의 역할이 이미 정해진 것들 반드시 확인
Unit의 종류와 다양한 기능이 존재하지만, 이미 역할이 거의 정해진 것이 많으므로 각각의 특징을 알아보며 세부역할을 알자 

systemd 기반의 Init 관련된 부분 (SysVinit 과 차이)
  https://www.freedesktop.org/software/systemd/man/init.html#

사용용도가 특별한용도로 정해진것 아래에서 확인필요 (반드시 확인)
  https://www.freedesktop.org/software/systemd/man/systemd.special.html#


2.1 Unit의 기본구성 및 문법 

Unit의 기본 문법구성은 SectionDirective(Option)으로 설정이 가능하며 관련 Manual을 찾아서 각 기능을 보자

systemd 의 기본문법 및 구조소개 
  https://www.freedesktop.org/software/systemd/man/systemd.syntax.html#

  • 기본으로 Service 부분 Simple 예
아래의 경우 3개의 Section [Unit] 와 [Service] 와 [Install]로 구성되며 각각의 Manual 참조
$ cat *.service or *.target 
## 주석 
[Unit]  ## Section 이라고함 
Description=Wait for Network to be Configured   ## Section의 Directive or Options 이라고함 
Documentation=man:systemd-networkd-wait-online.service(8)
DefaultDependencies=no

[Service]  ## Section에 따라 Directive의 기능이 달라지므로 주의 
Type=oneshot


[Install]   ## 모든 Unit이 필요한것이 아니므로 주의 
WantedBy=multi-user.target

상위 Service의 기본 분석은 아래의 두개로 시작을 하면 될 것이다.

Unit Section 과 Unit의 Directives(Option) 기능확인
System Unit Search PATH부터 정확히 파악하고 각각의 설정을 파악 
  https://www.freedesktop.org/software/systemd/man/systemd.unit.html
  https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files

Service Section 과 Service의 Directives(Option)기능확인
  https://www.freedesktop.org/software/systemd/man/systemd.service.html#


  • 세부분석을 위한 참조사항 
상위에서 설명했듯이 세부분석시 중요 

모든 Section의 Directives(Option) Index
  https://www.freedesktop.org/software/systemd/man/systemd.directives.html

systemd의 사용되어지는 File index
  https://www.freedesktop.org/software/systemd/man/index.html

  • Target Unit 
systemd의 Unit Target 에 내부 Wants 와 Requires 
  https://www.freedesktop.org/software/systemd/man/systemd.target.html#


2.2 Unit 의 기본분석 

Systemd의 Unit는 다양하므로 본인이 원하는 기능을 볼때 동작 여부와 종속성을 확인하여 정확하게 어떻게 동작하는지 파악하자.

systemctl 및 이외 명령 관련내용 참조  (반드시 참고)
  https://ahyuo79.blogspot.com/2017/03/systemctl.html

  • 각 Unit Linux 분석 (target)
현재 Target Unit의 동작여부를 ACTIVE에서 확인가능.

$ systemctl list-units --type target    // target을 분석 (화살표키로 움직임가능) 
UNIT                LOAD   ACTIVE SUB    DESCRIPTION
basic.target        loaded active active Basic System
getty.target        loaded active active Login Prompts
local-fs-pre.target loaded active active Local File Systems (Pre)
local-fs.target     loaded active active Local File Systems
machines.target     loaded active active Containers
multi-user.target   loaded active active Multi-User System
network.target      loaded active active Network
nss-lookup.target   loaded active active Host and Network Name Lookups
paths.target        loaded active active Paths
remote-fs.target    loaded active active Remote File Systems
slices.target       loaded active active Slices
sockets.target      loaded active active Sockets
swap.target         loaded active active Swap
sysinit.target      loaded active active System Initialization
time-sync.target    loaded active active System Time Synchronized
timers.target       loaded active active Timers
LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

  • 각 Unit 의 종류 및 동작상태 확인 
$ systemctl list-units --type target | grep target    // target을 분석 (나열식) 
상위와 동일 

$ systemctl list-units --type target --state active   // 보통 Service를 Target중심으로 하면 Active되었는지 확인 
or
$ systemctl list-units --type target --state active | grep target 

$ systemctl list-units --all --full | grep ".device"  // device을 세부분석 (나열식으로 전체를 볼수있음)  
  dev-disk-by\x2did-mmc\x2d00000_0x0cf64c62.device                                                                    loaded    active   plugged   /dev/disk/by-id/mmc-00000_0x0cf64c62
  dev-disk-by\x2did-mmc\x2d00000_0x0cf64c62\x2dpart1.device                                                           loaded    active   plugged   /dev/disk/by-id/mmc-00000_0x0cf64c62-part1
  dev-disk-by\x2did-mmc\x2dS0J57X_0x184f6793.device                                                                   loaded    active   plugged   /dev/disk/by-id/mmc-S0J57X_0x184f6793
  dev-disk-by\x2did-mmc\x2dS0J57X_0x184f6793\x2dpart1.device                                                          loaded    active   plugged   /dev/disk/by-id/mmc-S0J57X_0x184f6793-part1
  dev-disk-by\x2did-mmc\x2dS0J57X_0x184f6793\x2dpart2.device                                                          loaded    active   plugged   /dev/disk/by-id/mmc-S0J57X_0x184f6793-part2
  dev-disk-by\x2did-mmc\x2dS0J57X_0x184f6793\x2dpart3.device                                                          loaded    active   plugged   /dev/disk/by-id/mmc-S0J57X_0x184f6793-part3
  dev-disk-by\x2did-mmc\x2dS0J57X_0x184f6793\x2dpart4.device                                                          loaded    active   plugged   /dev/disk/by-id/mmc-S0J57X_0x184f6793-part4
  dev-disk-by\x2did-mmc\x2dS0J57X_0x184f6793\x2dpart5.device                                                          loaded    active   plugged   /dev/disk/by-id/mmc-S0J57X_0x184f6793-part5
  dev-disk-by\x2did-mmc\x2dS0J57X_0x184f6793\x2dpart6.device                                                          loaded    active   plugged   /dev/disk/by-id/mmc-S0J57X_0x184f6793-part6
  dev-disk-by\x2dlabel-boot.device                                                                                    loaded    active   plugged   /dev/disk/by-label/boot
.....


  • Target Unit의 종속성확인

$ systemctl status  // 현재 systemd의 실행상태확인 가능하며, 종속성 확인 (주의: 실행한 후 종료된 것은 제외됨) 
........

$ systemctl list-dependencies --all  // 전체 종속관계 확인  
.....

$ systemctl list-dependencies multi-user.target  // 전체구조파악 하며, 이 안에서 다시 세부 Target 분석  
.....

$ systemctl list-dependencies sockets.target // sockets.target 분석하며, 일반적인 Server Bind 분석  
.....

$ systemctl list-dependencies network-online.target // network-online.target 종속부분확인 
network-online.target
● └─systemd-networkd-wait-online.service


  • 상위 Target 종속성을 확인 후 관련 서비스 확인 
$ cat /lib/systemd/system/systemd-networkd-wait-online.service // network-online.target에 관련된 service분석 
#  SPDX-License-Identifier: LGPL-2.1+
#
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

[Unit]
Description=Wait for Network to be Configured
Documentation=man:systemd-networkd-wait-online.service(8)
DefaultDependencies=no
Conflicts=shutdown.target
Requires=systemd-networkd.service
After=systemd-networkd.service
Before=network-online.target shutdown.target

[Service]
Type=oneshot
ExecStart=/lib/systemd/systemd-networkd-wait-online
RemainAfterExit=yes

[Install]
WantedBy=network-online.target


$ readelf -a /lib/systemd/systemd-networkd-wait-online // 말그대로 network가 online이 될때까지 기다리는 실행파일  

  • systemd-analyze 분석 (중요)
systemd-analyze를 이용하여 booting 속도 및 각 Unit 연관성을 세부적으로 분석가능하므로 반드시 알아야함

systemd-analyze 부분 아래 참조 
  https://ahyuo79.blogspot.com/2017/04/systemd-analyze.html
  https://jlk.fjfi.cvut.cz/arch/manpages/man/systemd-analyze.1

  • network.target 및 관련내용 
  https://unix.stackexchange.com/questions/209832/debian-systemd-network-online-target-not-working
  https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/
  https://www.freedesktop.org/software/systemd/man/systemd-networkd-wait-online.service.html


2.3 기본 Service Unit 문법 


$ vi *.service
[Unit]
Description=Mx Encrypted Folder
Requires=local-fs.target
After=local-fs.target

## Requires 와 After 설정 중요하며, 종속(dependency)이 아니라면 Requreis 제거 
## After 의 local-fs.target Local File System Mount 된 시점
## After 의 network.target (network.target 진입 후 )
## After 의 network-online.target (network 가 연결될 경우)

[Service]
Type=oneshot
ExecStart=/usr/bin/mxmountencrypted
RemainAfterExit=true
ExecStop=/usr/bin/mxunmountencrypted

## ExecStart 이 서비스가 시작시 
## ExecStop 이 서비스를 systemctl stop으로 중지가능 
## RemainAfterExit yes or no로 Exit되어도 유지하는지 설정 (아래 Directives Index 참조)
## StandardOutput=journal  (systemd-journal log로 사용)


[Install]
WantedBy=multi-user.target

## WantedBy or RequiredBy= [Install] Section에서 주로 사용된다 
## 더불어 각각 *.wants 와 .requres directory에 심볼링크를 생성한다 
## 이 대표적인 예가 systemctl enable/disable 설정이 될 것 같다. 


기본 Service Example 
  https://stackoverflow.com/questions/47293195/running-systemd-unit-directly-after-local-fs-target-and-before-basic-target
  https://www.freedesktop.org/software/systemd/man/systemd.service.html

각 Section 과 Directive 한글설명 
  https://fmd1225.tistory.com/93


  • 내가 만든 service 기본서비스
Network가 물리적으로 online되면, 즉 After 와 Wants를 확인

$ vi *.service  //systemd 가 network를 물리적으로 online 된 경우 실행 
## Unit Section 
[Unit]
Description=Setup and Start my Service
After=network-online.target
Wants=network-online.target

## After network-online.target 후 동작가능 (HW Network가 동작가능)
## Wants 충분조건이라고 함 Requires가 필요조건

[Service]
Type=simple
ExecStart=/usr/bin/setup.sh
Restart=on-failure

## ExecStart 상위 조건을 만족하면 실행 
## Restart=on-failure 비정상 종료면 다시 실행
or 
## Restart=always , 상위는 비정상 종료일 경우만 실행이지만, 이는 항상 무조건 실행
## RestartSec=1     매번 Restart시 1s Delay 
 

[Install]
WantedBy=multi-user.target

 https://wiki.archlinux.org/index.php/systemd
 https://wiki.archlinux.org/index.php/systemd#Targets
 https://www.freedesktop.org/wiki/Software/systemd/
 https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/


2.4 NTP Client 설정 

systemd의 NTP Client 설정은 아래와 같이 기본으로 timesyncd에서 담당한다.

  • NTP Client 관련기본설정 
systemd의 NTP Service

$ cat /etc/systemd/timesyncd.conf
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.
#
# See timesyncd.conf(5) for details.

[Time]
#NTP=
#FallbackNTP=time1.google.com time2.google.com time3.google.com time4.google.com
#RootDistanceMaxSec=5
#PollIntervalMinSec=32
#PollIntervalMaxSec=2048

상위 timedatectl 명령어 참조 

$ timedatectl show-timesync --all //명령어로 확인 

// 이곳에 설정하면 NTP와 DNS를 같이 설정가능
// 이 설정이 상위 NTP에도 적용가능 
// 이 설정이 /etc/resolv.conf에 적용가능 

systemd의 NTP (timesyncd)
  https://stackframe.tistory.com/16
  https://www.freedesktop.org/software/systemd/man/timesyncd.conf.html
  https://wiki.archlinux.org/index.php/systemd-timesyncd

timedatectl (상위 링크참조)
  https://ahyuo79.blogspot.com/2017/03/systemctl.html

timedatectl (manual and example)
  http://man7.org/linux/man-pages/man1/timedatectl.1.html
  http://man7.org/linux/man-pages/man1/systemd-firstboot.1.html
  https://www.tecmint.com/set-time-timezone-and-synchronize-time-using-timedatectl-command/


2.5 SSH Server 설정 및 동작

  • SSH Server 설정변경 

$ cat /etc/ssh/sshd_config              //sftp 지원을 위해 수정 
# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

# 이곳에서 Port는 설정하지 말자 
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile      .ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
PermitEmptyPasswords yes

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#PermitUserEnvironment no
Compression no
ClientAliveInterval 15
ClientAliveCountMax 4
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Jeonghun
# changed options for SFTP 
# override default of no subsystems
#Subsystem      sftp    /usr/libexec/sftp-server
Subsystem       sftp    internal-sftp

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

  • SSH Server Port 설정 변경 및 확인 

//sshd.service는 별도로 없으며, sshd.socket만 존재하므로 관련부분 검색 
$ find /lib -name sshd.socket
/lib/systemd/system/sshd.socket

$ find /etc -name sshd.socket                               //sshd.service는 별도로 없으며, sshd.socket만 존재 
/etc/systemd/system/sockets.target.wants/sshd.socket

$ find /etc -name sshd*                                     //상위로도 못찾을 경우 
$ find /lib -name sshd*      


// systemd 는 /lib -> /etc 찾아실행되므로 최종은 etc 이며, 보통 이럴 경우 link임 
$ cat /etc/systemd/system/sockets.target.wants/sshd.socket   // sshd.socket에서 직접 port 변경 
[Unit]
Conflicts=sshd.service

[Socket]
ExecStartPre=/bin/mkdir -p /var/run/sshd
#ListenStream=22
ListenStream=3333
Accept=yes

## 아래의 WantedBy 부분참조하면, 
## systemctl enable/disable 할 경우 sockets.target.wants directory에 심볼 link 생성/삭제됨 
## /lib/systemd/system/sshd.socket 기반으로 link 생성/삭제 
[Install]
WantedBy=sockets.target 

  • SSH Server Port 적용 및 상태확인 

$ systemctl status sshd.socket        // sshd.socket 동작상태 확인 
or
$ systemctl status sshd               // sshd.service 동작상태 확인 (현재 없음) 


$ systemctl daemon-reload
$ systemctl restart sshd.socket.      //sshd.socket  만 있을 경우 sshd 재시작 
or 
$ systemctl restart sshd              //sshd.service 가 있을 경우 


  • SSH or SFTP 동작안될 경우 재확인 

$ netstat -a | grep 3333    // 우선적으로 SSH or SFTP 변경된 Port 동작 검색  
tcp        0      0 :::3333                 :::*                    LISTEN

$ systemctl status sshd.socket // sshd.socket 상태확인  

// 방화벽으로 인한부분 확인
$ iptables -S               // Iptables 설정확인  
-P INPUT DROP               // Iptables INPUT이 DROP이므로 별도 추가 하거나 Policy 변경  
-P FORWARD DROP
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
-A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 53 -j ACCEPT
-A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
-A OUTPUT -p tcp -m tcp --dport 123 -j ACCEPT
-A OUTPUT -p udp -m udp --dport 123 -j ACCEPT

$ iptables -A INPUT  -p tcp --dport 3333  -j ACCEPT // Iptables INPUT 새로변경된 Port 추가        
$ iptables -A OUTPUT -p tcp --dport 3333  -j ACCEPT 


  • SSH or SFTP TEST 진행 
$ ssh -p 3333 root@192.168.1.60
$ sftp -P 3333 root@192.168.1.60    //만약 server의 key 정보가 다르다면 ssh-keygen 한 후 재연결 (ssh-keygen -f "/home/jhlee/.ssh/known_hosts" -R 192.168.1.60) 
sftp> pwd                           // remote path 확인
sftp> help                          // 기본 명령어 확인 
sftp> get test                      // remote path의 test file 가져옴 
$ sftp -P 3333 root@192.168.1.60:test1     // sftp로 바로 get test1 


2.6 SysV 기반의 Network 설정 (Systemd 같이사용)

SysV Script 기반으로는 /etc/network/interfaces 에 Network Interface를 추가하여, service로 각각의 관리를 진행을 했다.
이 부분은 systemd 와 SysV Script를 혼합해서 사용할 경우 알아두도록 하자 

  • 일반적인 /etc/network/interface 예제 (SysV Script)
SysV Script 기반으로 구성되며, Main은 ifup/ifdown이 전체 Control 하고 각각의 Shell Script 같이 분석해야함 

$ cat /etc/network/interfaces  //systemd로만 구성할 경우 사용안함 
source-directory /etc/network/interfaces.d

# The loopback network interface
auto lo
iface lo inet loopback

## DHCPC Client 예제
auto eth0
iface eth0 inet dhcp
## Static IP 예제
auto eth1
iface eth1 inet static
	address 192.168.1.11 
	netmask 255.255.255.0
	gateway 192.168.1.1
## USB hotplug
allow-hotplug usb0
iface usb0 inet static
	address 192.168.3.7
	netmask 255.255.255.0
    
$ ls /etc/network/     //각 Shell Script 과 Interface 확인 
if-down.d  if-post-down.d  if-pre-up.d  if-up.d  interfaces  interfaces.d

$ ls /etc/network/if-up.d/  //각각의 Shell script 혹은 Symbol Link  내부에서 $IFACE로 Interface 구분 
000resolvconf  avahi-daemon  ethtool  wpasupplicant

$ service --status-all    //network 관련서비스 name 확인 (SysV Script 사용할 경우 service이용) 
...
$ sudo service networking restart //network 관련서비스 재실행 
or
$ systemctl restart networking.service

  • ifup/ifdown  (상위 설정 및 Shell Script 연결)
$ cat /lib/systemd/system/networking.service //ifup ifdown 이 /etc/network/interfaces 사용
.......
[Install]
WantedBy=multi-user.target
WantedBy=network-online.target

[Service]
Type=oneshot
EnvironmentFile=-/etc/default/networking
ExecStart=/sbin/ifup -a --read-environment
ExecStop=/sbin/ifdown -a --read-environment --exclude=lo
RemainAfterExit=true
TimeoutStartSec=5min

/etc/network/interfaces 관련 좋은예제

/sbin/ifup and ifdown 관련사항


2.7 Systemd 의 Network 설정

처음에 NTP 및 DNS / DHCP 관련부분 설정을 다른 곳에서 설정하려고 했으나 아래와 같이 한곳에서 설정하면 다 적용이 되는 부분을 찾았다.

  • systemd 로만 network 설정할 경우 
systemd의 network interface 설정은 기존과 다른게 systemd-networkd에서 담당한다

만약 systemd로만 구성할 경우 /etc/network/interface의 설정은 불필요한 것으로 보이는데,여기서 설정하지 못하는 것은 
추가로 상위와 같이 보완용 ifup/ifdown 기반으로 넣을 수도 있을 것 같다. 

systemd로만 network를 구성할 경우  /etc/systemd/network/xxx.network 로 network interface를 추가하고 설정하는 구조이다

일반 MII기반의 ethernet은 ethx.network  , USB-CDC 기반의 network는 usbx.network
이외의 network의 이름일 경우 상위와 동일하게 각 interface name으로 설정.
** 주의 우선순위가 될 것이며, /etc 가 가장 높으므로, 이 위주로 설정진행  
** 주의 wvdial의 ppp의 경우 이곳에서 설정하지 않음 
  • eth0 Interface기반 Network DHCP 설정
$ cat /etc/systemd/network/eth0.network  
[Match]
Name=eth0

[Network]
DHCP=yes
NTP=1.kr.pool.ntp.org
DNS=8.8.8.8
DefaultRouteOnDevice=yes

  • eth0 Interface기반 Network Static IP설정
$ cat /etc/systemd/network/eth0.network  
[Match]
Name=eth0

[Network]
##Static IP로 직접설정  192.168.1.67/24  24는 NetMask의 bits수 Netmask 255.255.255.0 
Address=192.168.1.67/24
Gateway=192.168.1.1
NTP=1.kr.pool.ntp.org
DNS=8.8.8.8
DefaultRouteOnDevice=yes

DefaultRouteOnDevice를 해야지 route table에 default로 등록가능

/etc/systemd/network/eth0.network  설정사항
  https://www.freedesktop.org/software/systemd/man/systemd.network.html

/etc/systemd/network/99-default.link (현재 /dev/null 로 link됨)

  • Route Table 설정확인 및 분석
$ route  
or
$ netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG        0 0          0 eth0
192.168.1.0     0.0.0.0         255.255.255.0   U         0 0          0 eth0
192.168.1.1     0.0.0.0         255.255.255.255 UH        0 0          0 eth0

$ ls /etc/network/
if-down.d       if-post-down.d  if-pre-up.d


  • DNS Server 설정확인
/var/run/resolv.conf
/etc/resolve.conf


  • RTC 관련사항
/dev/rtc 기능으로  i.MX SNVS
PMIC의 별도의 Battery Generator 와 i.MX의 RTC기능이며, 배터리로 RTC가 유지가 되어진다.

세부사항은 timedatectl 설정에서 확인가능
  https://www.digi.com/resources/documentation/digidocs/90001546/reference/bsp/cc6/r_real_time_clock.htm
  https://developer.toradex.com/knowledge-base/how-to-use-the-real-time-clock-in-linux

3/30/2017

systemctl 사용법 과 networkctl/timedatectl 설정 및 그외설정

1. systemctl 의 기본사용법

systemctl은 기본적으로 root권한이 필요하기 때문에 아래와 같이 실행하며, systemd의 상태를 확인 및 제어가 가능하며
이 command를 이용하여, 각각의 service를 비롯하여 다양한 분석도 가능하다.


  • 기본실행방법

$ sudo -s 
$ exit
or 
$ sudo systemctl     


systemctl - manual
  https://www.freedesktop.org/software/systemd/man/systemctl.html


  • systemd의 동작을 트리형태로 파악 
일반적으로 시스템의 서비스가 트리형태로 보여주며, 관련사항 정보를 나열해준다.

$ systemctl status // systemd 의 전체 서비스의 실행되는 구조를 쉽게 파악 
● raspberrypi
    State: running
     Jobs: 0 queued
   Failed: 0 units
    Since: Thu 1970-01-01 09:00:01 KST; 49 years 1 months ago
   CGroup: /
           ├─user.slice
           │ └─user-1000.slice
           │   ├─session-c3.scope
           │   │ ├─ 833 sshd: pi [priv]
           │   │ ├─ 848 sshd: pi@pts/0
           │   │ ├─ 851 -bash
           │   │ ├─1090 systemctl status
           │   │ └─1091 pager


상위에 적용되어지는 Option확인
  https://www.freedesktop.org/software/systemd/man/systemctl.html#Options

  • 개별 unit status 확인

$ systemctl status avahi-daemon.service   //설정화면으로 들어감 
● avahi-daemon.service - Avahi mDNS/DNS-SD Stack
   Loaded: loaded (/lib/systemd/system/avahi-daemon.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Sun 2019-02-17 01:44:46 KST; 2min 23s ago
  Process: 1169 ExecStart=/usr/sbin/avahi-daemon -s (code=exited, status=0/SUCCESS)
 Main PID: 1169 (code=exited, status=0/SUCCESS)
   Status: "avahi-daemon 0.6.32 starting up."
     ......

$ systemctl is-enabled avahi-daemon.service
enabled


  • units 의 종속성 확인 
각 Units의 종속성을 확인가능하며, 이 부분은 종속성만 확인

$ systemctl list-dependencies   //default가 default.target
default.target
● ├─acct.service
● ├─bootchart-done.service
● ├─bootchart.service
● ├─dphys-swapfile.service
● ├─lightdm.service
● ├─raspi-config.service
● ├─systemd-update-utmp-runlevel.service
● └─multi-user.target
●   ├─acct.service
●   ├─avahi-daemon.service
●   ├─bluealsa.service
●   ├─bootchart-done.service
....

$ systemctl list-dependencies --all  //모든 종속성을 확인가능 

$ systemctl list-dependencies --after  //default.target 기준으르 After (Unit 설정부분참조)

$ systemctl list-dependencies --before  //default.target 기준으르 Before

$ systemctl list-dependencies raspi-config.service  // 본인보고싶은 unit의 종속성확인 
 


1.1 systemd의 unit의 제어 

systemd의 command는 file(아래참조) 기반 과 systemd에서 생성된 unit(즉,실행되어 memory 존재),file 기반은 아래의 1,2번에 있는 unit들을 말한다.
더불어 systemd는 아래의 순서대로 찾지만 우선순위는 /etc가 높으므로, 최종제어는 /etc에서 한다
  1. /lib/systemd/system
  2. /etc/systemd/system
**/run/systemd 는 생략 (실행중인 정보들 )

  • unit 에 enable/disable 추가/제거 (file 기반)
file기반의 unit을 enable을 하므로써, 링크를 생성하여 load가 되며, 이후에는 start/stop/restart 명령진행가능

$ systemctl enable avahi-daemon.service  // /etc에 각 symbolic link 생성  
Created symlink /etc/systemd/system/dbus-org.freedesktop.Avahi.service → /lib/systemd/system/avahi-daemon.service.
Created symlink /etc/systemd/system/multi-user.target.wants/avahi-daemon.service → /lib/systemd/system/avahi-daemon.service.
Created symlink /etc/systemd/system/sockets.target.wants/avahi-daemon.socket → /lib/systemd/system/avahi-daemon.socket.

$ systemctl disable avahi-daemon.service  // /etc에 각 symbolic link 제거  
Removed /etc/systemd/system/dbus-org.freedesktop.Avahi.service.
Removed /etc/systemd/system/multi-user.target.wants/avahi-daemon.service.
Removed /etc/systemd/system/sockets.target.wants/avahi-daemon.socket.

$ systemctl is-enabled avahi-daemon.service  // 확인 
enabled

// /lib 와 /etc wants 중심으로 기능확인 
$ ls /lib/systemd/system/*wants
.....
/lib/systemd/system/multi-user.target.wants:
dbus.service                          systemd-logind.service
getty.target                          systemd-update-utmp-runlevel.service
systemd-ask-password-wall.path
....
/lib/systemd/system/sockets.target.wants:
dbus.socket                      systemd-journald.socket
systemd-initctl.socket           systemd-udevd-control.socket
systemd-journald-audit.socket    systemd-udevd-kernel.socket
systemd-journald-dev-log.socket
......

$ ls /etc/systemd/system/*wants
.....
/etc/systemd/system/multi-user.target.wants:
avahi-daemon.service      machines.target           rngd.service
busybox-klogd.service     ofono.service             systemd-networkd.service
busybox-syslog.service    power-setup.service       systemd-resolved.service
....
/etc/systemd/system/sockets.target.wants:
avahi-daemon.socket      sshd.socket
...

  • unit mask/unmask 제외 (file 기반)
mask는 disalbe 보다 더 강력한 명령으로 unit 제외 해버리겠다는 의미으로 enable 해도 소용이 없으며
만약 list-unit-files에는 검색은 되지만, enable이 제대로되지 않는다면, 이부분을 보자.

$ systemctl mask avahi-daemon.service  // /lib 에 이미 존재하지만, /etc에서 막음 
Created symlink /etc/systemd/system/avahi-daemon.service → /dev/null.

$ systemctl unmask avahi-daemon.service // /etc에서 막은 것을 제거 (etc가 우선순위가 높음) 
Removed /etc/systemd/system/avahi-daemon.service

$ systemctl list-unit-files | grep masked  // mask 상태 확인 가능 


  • 개별 unit start/stop/restart/reload 동작제어 (memory 기반)
enable이 된 상태의 avahi를 예를들면 아래와 같이 각각의 unit 명령을 실행가능하다.

$ systemctl start avahi-daemon.service

$ systemctl stop avahi-daemon.service

$ systemctl restart avahi-daemon.service



  • service enable /disable  한 후 동작확인 예 (timesyncd)

 // service stop 한 후 disable 하여 다음 부팅시에도 미동작  
$ systemctl stop systemd-timesyncd
$ systemctl disable systemd-timesyncd

// service enable 한 후 start   
$ systemctl enable systemd-timesyncd
$ systemctl start  systemd-timesyncd
$ systemctl restart  systemd-timesyncd  //문제시 다시 restart 

//이 service 의 active or disable 확인
$ systemctl is-active  systemd-timesyncd
$ systemctl is-enabled systemd-timesyncd
$ systemctl list-units --type service   


1.2 Systemd 의 전체 Units 정보확인 

일반적인 systemd의 unit 확인방법은 Memory에 있는 Unit(실행된 Unit)과 File에 존재하는 Unit로 검색이 가능하며,
세부옵션을 설정하여 다양하게 검색이 가능하다. .

  • 세부옵션 
  1. -t -type: Unit의 종류 (e.g service, target, timer, mount ...) 
  2. -a -all: 모든 Unit의 정보를 보여준다. 
  3. --state: Unit의 상태 입력 (e.g active, inactive, failed ... )
상위에 적용되어지는 Option확인
  https://www.freedesktop.org/software/systemd/man/systemctl.html#Options

  • list-units로 (in memory)
list-units의 경우 memory에 있는 unit를 기준으로 찾아주며, default로 활성화된 상태인 systemd의 unit을 확인가능하며, 이외의 옵션을 주어
다양하게 검색이 가능하다

$ systemctl list-units or systemctl // default가 활성화된 Unit를 검색 및 device 분석 
UNIT                                                                                         LOAD   ACTIVE SUB       DESCRIPTION                
proc-sys-fs-binfmt_misc.automount                                                            loaded active waiting   Arbitrary Executable File F
sys-devices-platform-soc-3f201000.serial-tty-ttyAMA0-hci0.device                             loaded active plugged   /sys/devices/platform/soc/3
sys-devices-platform-soc-3f201000.serial-tty-ttyAMA0.device                                  loaded active plugged   /sys/devices/platform/soc/3
sys-devices-platform-soc-3f202000.mmc-mmc_host-mmc0-mmc0:aaaa-block-mmcblk0-mmcblk0p1.device loaded active plugged   /sys/devices/platform/soc/3
sys-devices-platform-soc-3f202000.mmc-mmc_host-mmc0-mmc0:aaaa-block-mmcblk0-mmcblk0p2.device loaded active plugged   /sys/devices/platform/soc/3
sys-devices-platform-soc-3f202000.mmc-mmc_host-mmc0-mmc0:aaaa-block-mmcblk0.device           loaded active plugged   /sys/devices/platform/soc/3
sys-devices-platform-soc-3f300000.mmc-mmc_host-mmc1-mmc1:0001-mmc1:0001:1-net-wlan0.device   loaded active plugged   /sys/devices/platform/soc/3
sys-devices-platform-soc-3f980000.usb-usb1-1\x2d1-1\x2d1.1-1\x2d1.1:1.0-net-eth0.device      loaded active plugged   SMSC9512/9514 Fast Ethernet
sys-devices-platform-soc-soc:audio-bcm2835_alsa-sound-card0.device                           loaded active plugged   /sys/devices/platform/soc/s
sys-devices-virtual-block-ram0.device                                                        loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram1.device                                                        loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram10.device                                                       loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram11.device                                                       loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram12.device                                                       loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram13.device                                                       loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram14.device                                                       loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram15.device                                                       loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram2.device                                                        loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram3.device                                                        loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram4.device                                                        loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram5.device                                                        loaded active plugged   /sys/devices/virtual/block/
sys-devices-virtual-block-ram6.device                                                        loaded active plugged   /sys/devices/virtual/block/
....

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type

// UNIT 의 device들을 보면, 실제위치는 DESCRIPTION에 /sys filesystem 기반으로 구성되며, sys-devices 는 /sys/devices 이런식변경
// 최종 /sys의 device directory에서 uevent 확인  
// 최종 /sys의 device directory에서 of_node/ 에서 각 속성확인  


$ systemctl list-units | grep mount // mount 부분분석 
  -.mount                                                                                                          loaded active mounted   Root Mount                                         
  home-root.mount                                                                                                  loaded active mounted   /home/root                                         
  sys-fs-fuse-connections.mount                                                                                    loaded active mounted   FUSE Control File System                           
  sys-kernel-config.mount                                                                                          loaded active mounted   Kernel Configuration File System                   
  sys-kernel-debug.mount                                                                                           loaded active mounted   Kernel Debug File System                           
  tmp.mount                                                                                                        loaded active mounted   Temporary Directory (/tmp)                         
  var-log.mount                                                                                                    loaded active mounted   /var/log                                           
  var-volatile.mount                                                                                               loaded active mounted   /var/volatile                                      
  systemd-remount-fs.service                                                                                       loaded active exited    Remount Root and Kernel File Systems                  
....

$ find /etc/systemd/  -name *mount* // file mount 아무것도 없음
$ find /lib/systemd/  -name *mount* // file mount 부분분석   
/lib/systemd/system/sys-fs-fuse-connections.mount
/lib/systemd/system/sys-kernel-config.mount
/lib/systemd/system/systemd-remount-fs.service
/lib/systemd/system/machines.target.wants/var-lib-machines.mount
/lib/systemd/system/sysinit.target.wants/sys-fs-fuse-connections.mount
/lib/systemd/system/sysinit.target.wants/sys-kernel-config.mount
/lib/systemd/system/sysinit.target.wants/dev-hugepages.mount
/lib/systemd/system/sysinit.target.wants/dev-mqueue.mount
/lib/systemd/system/sysinit.target.wants/sys-kernel-debug.mount
/lib/systemd/system/dev-hugepages.mount
/lib/systemd/system/umount.target
/lib/systemd/system/var-lib-machines.mount
/lib/systemd/system/remote-fs.target.wants/var-lib-machines.mount
/lib/systemd/system/dev-mqueue.mount
/lib/systemd/system/local-fs.target.wants/systemd-remount-fs.service
/lib/systemd/system/local-fs.target.wants/tmp.mount
/lib/systemd/system/tmp.mount
/lib/systemd/system/sys-kernel-debug.mount
/lib/systemd/systemd-remount-fs        // binary 파일  

// -.mount , home-root.mount , var-log.mount var-volatile.mount 는 상위에 존재하지 않음
// /lib/systemd/systemd-remount-fs 이 /etc/fstab 참조하여, 생성된 unit 이며, 이후 fsck로 filesystem 체크  

$ cat /lib/systemd/system/systemd-remount-fs.service
#  SPDX-License-Identifier: LGPL-2.1+
#
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

[Unit]
Description=Remount Root and Kernel File Systems
Documentation=man:systemd-remount-fs.service(8)
Documentation=https://www.freedesktop.org/wiki/Software/systemd/APIFileSystems
DefaultDependencies=no
Conflicts=shutdown.target
After=systemd-fsck-root.service
Before=local-fs-pre.target local-fs.target shutdown.target
Wants=local-fs-pre.target
ConditionPathExists=/etc/fstab

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/lib/systemd/systemd-remount-fs

$ fdisk -l   // 각 partition 확인
or
$ systemd-mount --list 
  https://www.freedesktop.org/software/systemd/man/systemd.html#


  • 이외 세부검색방법

$ systemctl list-units -all  // 모든 Unit 검색 (비활성화부분포함)
or
$ systemctl list-units -a   // 모든 Unit 검색 (비활성화부분포함)


$ systemctl list-units -t service // 활성화된 service unit만 검색 
or
$ systemctl  list-units -type service // 활성화된 service unit만 검색 


$ systemctl list-units -t target   // 활성화된 target unit만 검색 (Unit 11개 종류가 있으므로 각각설정)

$ systemctl list-units -t timer   // 활성화된 timer unit만 검색 (Unit 11개 종류가 있으므로 각각설정)


$ systemctl list-units -t service  --state=inactive  // 비활성화된 Unit의 Serivce만 검색 


$ systemctl list-units --state=failed    // Failed Unit 검색
or 
$ systemctl --failed   // Failed Unit 검색



  • list-sockets (in memory)
socket unit는 Network관련된 것이므로, 동작 중인 socket unit의 세부정보인 Network 정보확인가능, 즉 Server의 존재 및 동작확인가능

$ systemctl list-sockets   // SOCKET의 LISTEN (Server)를 표시 (동작확인) (NETWORK 정보확인)

$ systemctl list-units -t socket  // 상위와 같이 UNIT의 status 만 확인 

  • list-timers (in memory)
timer unit는 기존의 cron과 유사하며, 동작 중인 timer의 상태와 세부정보를 별도로 볼 수 있다.

$ systemctl list-timers   // NEXT(다음동작)  LEFT (남은시간)  LAST (마지막실행) 동작확인   

$ systemctl list-units -t timer  // 상위와 같이 UNIT의 status 만 확인 

  • list-unit-files (in file)
/lib/systemd/system or /etc/systemd/system 에 설치된 files 확인검색하며, 각 상태를 확인가능하다.

$ systemctl list-unit-files
UNIT FILE                              STATE    
proc-sys-fs-binfmt_misc.automount      static   
-.mount                                generated
boot.mount                             generated
dev-hugepages.mount                    static   
dev-mqueue.mount                       static   
proc-fs-nfsd.mount                     static   
proc-sys-fs-binfmt_misc.mount          static   
run-rpc_pipefs.mount                   static   
sys-fs-fuse-connections.mount          static   
sys-kernel-config.mount                static   
sys-kernel-debug.mount                 static   
systemd-ask-password-console.path      static   
systemd-ask-password-plymouth.path     static   
systemd-ask-password-wall.path         static   
session-c1.scope                       transient
session-c2.scope                       transient
session-c3.scope                       transient
acct.service                           generated
alsa-restore.service                   static   
alsa-state.service                     static   
alsa-utils.service                     masked   
apply_noobs_os_config.service          disabled 
apt-daily-upgrade.service              static   
apt-daily.service                      static   
auth-rpcgss-module.service             static   
autologin@.service                     enabled  
autovt@.service                        disabled 
.....



  • service unit의 설정보기 

$ systemctl show avahi-daemon.service
Type=dbus
Restart=no
NotifyAccess=main
RestartUSec=100ms
TimeoutStartUSec=1min 30s
TimeoutStopUSec=1min 30s
RuntimeMaxUSec=infinity
WatchdogUSec=0
WatchdogTimestampMonotonic=0
FailureAction=none
PermissionsStartOnly=no
RootDirectoryStartOnly=no
RemainAfterExit=no
GuessMainPID=yes
MainPID=0
ControlPID=0
BusName=org.freedesktop.Avahi
FileDescriptorStoreMax=0
NFileDescriptorStore=0
StatusText=avahi-daemon 0.6.32 starting up.
StatusErrno=0
Result=success
UID=4294967295
GID=4294967295
...



  https://wiki.archlinux.org/index.php/systemd
  https://websetnet.com/ko/manage-systemd-services-and-units/
  https://www.conory.com/note_linux/42241
  https://www.freedesktop.org/wiki/Software/systemd/
  http://linux.systemv.pe.kr/centos-7-systemd-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0/


2. systemctl 이외의 설정 


2.1 networkctl 설정 

ifconfig 처럼 각각의 network의 정보를 확인 가능한 명령

  • 물리적인 network 확인  

$ networkctl --help
networkctl [OPTIONS...]

Query and control the networking subsystem.

  -h --help             Show this help
     --version          Show package version
     --no-pager         Do not pipe output into a pager
     --no-legend        Do not show the headers and footers
  -a --all              Show status for all links

Commands:
  list [LINK...]        List links
  status [LINK...]      Show link status
  lldp [LINK...]        Show LLDP neighbors
  label                 Show current address label entries in the kernel


$ networkctl list // ifconfig 처럼 물리적인 network 연결상태확인 

$ networkctl status -a  // ifconfig 처럼 network IP 및 정보학인 

networkctl (systemd-networkd)
  https://www.freedesktop.org/software/systemd/man/networkctl.html#
  https://www.freedesktop.org/software/systemd/man/systemd-networkd.service.html#


2.2 timedatectl 설정 

시간에 관련된 설정으로 NTP를 비롯하여, Hardware 적인 시간인 RTC와 System Clock 와 지역 설정까지 가능하다.

  • timedatectl 사용법
$ timedatectl --help
timedatectl [OPTIONS...] COMMAND ...

Query or change system time and date settings.

  -h --help                Show this help message
     --version             Show package version
     --no-pager            Do not pipe output into a pager
     --no-ask-password     Do not prompt for password
  -H --host=[USER@]HOST    Operate on remote host
  -M --machine=CONTAINER   Operate on local container
     --adjust-system-clock Adjust system clock when changing local RTC mode
     --monitor             Monitor status of systemd-timesyncd
  -p --property=NAME       Show only properties by this name
  -a --all                 Show all properties, including empty ones
     --value               When showing properties, only print the value

Commands:
  status                   Show current time settings
  show                     Show properties of systemd-timedated
  set-time TIME            Set system time
  set-timezone ZONE        Set system time zone
  list-timezones           Show known time zones
  set-local-rtc BOOL       Control whether RTC is in local time
  set-ntp BOOL             Enable or disable network time synchronization

systemd-timesyncd Commands:
  timesync-status          Show status of systemd-timesyncd
  show-timesync            Show properties of systemd-timesyncd



  • timedatectl 기본상태확인
$ timedatectl   // Time에 관련된 일반적인 상태확인 
or  
$ timedatectl status                                  
               Local time: Tue 2017-04-14 01:48:24 UTC       // UTC Time +9이지만 현재 /etc/localtime을 사용하여 제대로 동작안됨
           Universal time: Tue 2017-04-14 01:48:24 UTC       // UTC Time 
                 RTC time: Tue 2017-04-14 01:48:23           // RTC기반으로 동작 
                Time zone: n/a (UTC, +0000)                  // UTC Time에 Time zone은 /etc/localtime으로 설정되어있음 (Seoul +9)
System clock synchronized: no                                // 시간을 Sytem clock 과 동기화기능 
              NTP service: active                            // NTP Client로 timesyncd 이용
          RTC in local TZ: no                                // RTC의 Timezon 사용여부 (timedatectl set-local-rtc  0) 


  • timezone 기능확인 
$ timedatectl list-timezones   //  timezones list를 보여줌 
//만약 동작하지 않는다면, timezone의 directory 확인 (/etc/localtime -> /usr/share/zoneinfo/Asia/Seoul)

$ timedatectl set-timezone “Asia/Seoul” // 상위 /etc/localtime 링크변경 


  • timedatectl 날짜시간설정
$ timedatectl set-ntp 0
//변경시 주의사항.1 NTP설정(timedatectl set-ntp true)이면, set-time부분에서 에러발생
//변경시 주의사항.2 RTC에도 적용되므로 반드시 같이 확인
$ timedatectl set-time 2015-11-20              //날짜만 변경 
$ timedatectl set-time 15:58:30              //시간만 변경  
$ timedatectl set-time "2012-10-3018:17:16"  //날짜시간동시변경  


  • Last login 정보지우기 (NTP/RTC 미사용시 이시간사용)
// 주의: Last Login Time 정보 Linux가 시스템 Time 설정가능

// 아래 파일은 binary가 있으므로 존재여부만 확인
$ cat /var/log/lastlog        // Last Login 정보이지만, Binary이므로 깨짐 
$ cat /var/log/utmp           // last -f /var/log/utmp (picture of users logins at which terminals, logouts,) 
$ cat /var/log/wtmp           // last -f /var/log/wtmp (utmp의 history)   
$ cat /var/log/btmp           // last -f /var/log/btmp (records only failed login attempts.)

// lastlogin 정보확인
$ who                                // 명령어로 본인 및 Last Login Time 확인 
$ lastlog                            // last login 정보확인 (/var/log/lastlog 기반) 

// NTP Client Service Stop and Disable
$ systemctl stop systemd-timesyncd
$ systemctl disable systemd-timesyncd
$ systemctl status systemd-timesyncd

// 원하는 시간으로 변경
$ timedatectl set-time "2012-10-3018:17:16"

// 주의: NTP 미사용 과 RTC 미사용한 후 시간설정이 되면 외부의 Device(GPS or 외부 RTC) 혹은 Build Time 에서 설정될 가능성이 높음
// lastlogin 정보삭제
$ lastlog -u root -C               // last login user:root -C clear (lastlog가 /var/log/lastlog 기반)
$ rm /var/log/lastlog
$ rm /var/log/*tmp
$ sync
// HW Reset or Power On/Off

lastlog 정보
  https://unixserveradmin.wordpress.com/2014/08/10/how-to-read-or-view-utmp-wtmp-and-btmp-files-in-linux/

  • RTC 와 NTP 상태확인 
// 상위설정상태 확인 가능, 아래 Timezone도 나와야함 
$ timedatectl show 
LocalRTC=no                                // RTC on /off (timedatectl set-ntp 1 or 0)
CanNTP=yes                                 // NTP Client Service 존재여부 
NTP=yes                                    // NTP Service on / off (timedatectl set-ntp 1 or 0) 
NTPSynchronized=yes                        // NTP Server에 접속후 Sync 여부  
TimeUSec=Tue 2017-07-02 10:38:38 KST       // System 의 실제동작 시간 (date)
RTCTimeUSec=Tue 2017-07-02 10:38:39 KST    // RTC Time Sec (/proc/driver/rtc or /dev/rtc) 


  • NTP Server 연결상태확인
//확인시 주의사항 NTP설정(timedatectl set-ntp true)일 경우에만 확인
//NTP Server 동작확인  및 systemd-timesyncd service 설정확인 
$ timedatectl timesync-status    // NTP Packet 확인 (Network 문제로 접속못함)
       Server: (null) (time3.google.com)
Poll interval: 0 (min: 32s; max 34min 8s)
 Packet count: 0

$ timedatectl timesync-status    // NTP Packet 확인 (Network 문제로 접속한 후 주기적으로 Sync)
       Server: 216.239.35.0 (time1.google.com)
Poll interval: 32s (min: 32s; max 34min 8s)
         Leap: normal
      Version: 4
      Stratum: 1
    Reference: GOOG
    Precision: 1us (-20)
Root distance: 167us (max: 5s)
       Offset: -886.603ms
        Delay: 70.981ms
       Jitter: 0
 Packet count: 1
    Frequency: +0.000ppm
$ timedatectl show-timesync    // NTP 설정부분 확인 (systemd-timesyncd 설정확인필요) 
......


  • NTP Service 사용여부결정
//NTP 설정 부분 상위 
$ timedatectl set-ntp true
$ timedatectl set-ntp false


  • RTC 사용여부 결정
//RTC의 Local Time 적용여부 설정 
$ timedatectl set-local-rtc  1  // /dev/rtc 사용하며, Local Time 적용여부 on (timedatectl status 확인) 
//이것으로 사용
$ timedatectl set-local-rtc  0  // /dev/rtc 사용하며, Local Time 적용여부 off


  https://www.tecmint.com/set-time-timezone-and-synchronize-time-using-timedatectl-command/
  https://www.freedesktop.org/software/systemd/man/timedatectl.html#
  https://www.freedesktop.org/software/systemd/man/systemd-firstboot.html#
  http://man7.org/linux/man-pages/man1/timedatectl.1.html
  http://man7.org/linux/man-pages/man1/systemd-firstboot.1.html

  • RTC 동작확인 
$ ls  /dev/rtc*  // rtc->rtc0 link 
/dev/rtc   /dev/rtc0  

$ cat /proc/driver/rtc
rtc_time        : 16:31:36
rtc_date        : 2017-03-13
alrm_time       : 00:00:00
alrm_date       : 1970-01-01
alarm_IRQ       : no
alrm_pending    : no
update IRQ enabled      : no
periodic IRQ enabled    : no
periodic IRQ frequency  : 1
max user IRQ frequency  : 64
24hr            : yes

  • RTC 와 Linux System 시간 동기화  
timedatectl이 제대로 동작안되면 busybox의 hwclock으로 강제설정

$ hwclock -r          // RTC Time 확인 

$ hwclock -w          // system 시간 ->  /dev/rtc 시간저장

$ hwclock -s          // /dev/rtc    ->  system 시간 

AP의 경우 PMIC와 같이 사용할 경우, RTC를 PMIC와 함께 사용하는 경우가 있으므로, 반드시 관련 Kernel config와 관련 Datasheet 참조

  http://man7.org/linux/man-pages/man8/hwclock.8.html
  https://www.digi.com/resources/documentation/digidocs/90001546/reference/bsp/cc6/r_real_time_clock.htm


2.3 systemd에서 사용되어지는 ctrl 설정 

그외에도 사용되어지는 ctrl command들이 존재하지만 경우에따라 다 지원하지는 않는것 같다.

사용한다면 아래의 Manual에서 확인하자

homectl
  https://www.freedesktop.org/software/systemd/man/homectl.html#

hostnamectl

$ hostnamectl --help
hostnamectl [OPTIONS...] COMMAND ...

Query or change system hostname.

  -h --help              Show this help
     --version           Show package version
     --no-ask-password   Do not prompt for password
  -H --host=[USER@]HOST  Operate on remote host
  -M --machine=CONTAINER Operate on local container
     --transient         Only set transient hostname
     --static            Only set static hostname
     --pretty            Only set pretty hostname

Commands:
  status                 Show current hostname settings
  set-hostname NAME      Set system hostname
  set-icon-name NAME     Set icon name for host
  set-chassis NAME       Set chassis type for host
  set-deployment NAME    Set deployment environment for host
  set-location NAME      Set location for host
  https://www.freedesktop.org/software/systemd/man/hostnamectl.html#

loginctl

$ loginctl --help
loginctl [OPTIONS...] {COMMAND} ...

Send control commands to or query the login manager.

  -h --help                Show this help
     --version             Show package version
     --no-pager            Do not pipe output into a pager
     --no-legend           Do not show the headers and footers
     --no-ask-password     Don't prompt for password
  -H --host=[USER@]HOST    Operate on remote host
  -M --machine=CONTAINER   Operate on local container
  -p --property=NAME       Show only properties by this name
  -a --all                 Show all properties, including empty ones
     --value               When showing properties, only print the value
  -l --full                Do not ellipsize output
     --kill-who=WHO        Who to send signal to
  -s --signal=SIGNAL       Which signal to send
  -n --lines=INTEGER       Number of journal entries to show
  -o --output=STRING       Change journal output mode (short, short-precise,
                             short-iso, short-iso-precise, short-full,
                             short-monotonic, short-unix, verbose, export,
                             json, json-pretty, json-sse, cat)
Session Commands:
  list-sessions            List sessions
  session-status [ID...]   Show session status
  show-session [ID...]     Show properties of sessions or the manager
  activate [ID]            Activate a session
  lock-session [ID...]     Screen lock one or more sessions
  unlock-session [ID...]   Screen unlock one or more sessions
  lock-sessions            Screen lock all current sessions
  unlock-sessions          Screen unlock all current sessions
  terminate-session ID...  Terminate one or more sessions
  kill-session ID...       Send signal to processes of a session

User Commands:
  list-users               List users
  user-status [USER...]    Show user status
  show-user [USER...]      Show properties of users or the manager
  enable-linger [USER...]  Enable linger state of one or more users
  disable-linger [USER...] Disable linger state of one or more users
  terminate-user USER...   Terminate all sessions of one or more users
  kill-user USER...        Send signal to processes of a user

Seat Commands:
  list-seats               List seats
  seat-status [NAME...]    Show seat status
  show-seat [NAME...]      Show properties of seats or the manager
  attach NAME DEVICE...    Attach one or more devices to a seat
  flush-devices            Flush all device associations
  terminate-seat NAME...   Terminate all sessions on one or more seats
  https://www.freedesktop.org/software/systemd/man/loginctl.html#

userdbctl
  https://www.freedesktop.org/software/systemd/man/userdbctl.html#

  https://www.freedesktop.org/software/systemd/man/index.html