31 Ocak 2021 Pazar

find komutu name seçeneği - Belirtilen glob/wildcard'a Uyanları Kabul Eder

Giriş
name seçeneği düzenli ifade (regular expression) değil glob/wildcard kullanır. dolayısıyla "*" karakterini kullanabiliriz. Açıklaması şöyle
The -name predicate takes a glob, not a regular expression.
In a regular expression, * would match zero or more of the preceding item. But since this is a glob, it matches zero or more of any character. That is, * in a glob means the same thing as .* in a regular expression.
Wildcard dilediğimiz yerde kullanılabilir. Wildcard not ile birlikte kullanılabilir. Not için istersek harfle "not" veya "!" yazabiliriz.

2. -regex Alternatifi
Açıklaması şöyle. glob/wildcard yerine regex kullanmak mümkün ancak ben bu yöntemi hiç sevmedim.
GNU find's -regex non-standard extension does take a regexp (old style emacs type by default), but that's applied on the full path (like the standard -path which also takes wildcards), not just the file name (and are anchored implicitly)

So to find files of type directory whose name starts with machine, you'd need:

find . -name 'machine*' -type d
Or:

find . -regextype posix-extended -regex '.*/machine[^/]*' -type d
-name yerine - regex ne zaman lazım olur?
Elimizde şöyle bir komut olsun. Bu komut çalışmaz. Çünkü -name ile globbing yerine brace expansion yapılmaya çalışılıyor
find $directory -name '*.[hc]' -exec clang-format -i {} \;
 Bu  gibi durumlarda regex daha iyi. Şöyle yaparız
find . -regextype posix-extended -regex '.*\.(c|h|cpp)'
3. Kullanım
Örnek - karakter sayısı
Şöyle yaparız
find "$HOME" -type d -name 'bowtie*1.[!2]*'
Açıklaması şöyle
The pattern matches names starting with bowtie and then contains 1.n, where n is not 2.
Örnek - not name kullanımı
Şöyle yaparız. Bu sefer not için harfle "not" kullanılıyor.
$ find -not -name mongodb.log -name "*.log"
Örnek - not extension kullanımı
Şöyle yaparız.
find src -type f -name '*.ts' ! -name '*.d.ts'
Örnek - not name kullanımı
İsmi belirtilen örüntüye uymayanları listelemek için not kullanılır. İsmi "." ve ".." olmayan dizinleri bulmak için şöyle yaparız.
find . -maxdepth 1 -type d ! -name "\.*"
Örnek - and name ve not name kullanımı
İsmi master ile başlayan ancak master-2018 ile başlamayanları silmek için şöyle yaparız.
$ find -name 'master*' \! -name 'master-2018*' -print0 |
     xargs -0 echo rm -fr
Örnek - extension
mp3 dosyalarını bir üst dizine taşımak için şöyle yaparız.
find . -path "*/flac/*" -name '*.mp3' -execdir mv -t ../ {} +
Örnek - name + extension
unl uzantılı dosyaları bulmak için şöyle yaparız.
find . -type f -name 'cbs_cdr_vou_20180615*.unl' -exec cat {} + >/home/fifa/cbs/test.txt

base64 komutu

Örnek
Şöyle yaparız
echo -n '{plaintext}' | base64
Örnek
Şöyle yaparız
$ echo '{"foo":"bar","baz":"bat"}' | base64
eyJmb28iOiJiYXIiLCJiYXoiOiJiYXQifQo=

$ echo "eyJmb28iOiJiYXIiLCJiYXoiOiJiYXQifQo=" | base64 -di
{"foo":"bar","baz":"bat"}

24 Ocak 2021 Pazar

Linux Scheduler'ları

Giriş
Linux'ta bir sürü çeşit scheduler var. Bunlar bir arada da çalışabiliyor.

Realtime Scheduler'lar
Önceliği 1-99 arasında olan uygulamalar Realtime Scheduler'lardan birisi tarafından çalıştırılırlar
Bunlar şöyle
1. SCHED_FIFO
2. SCHED_RR

POSIX Açısından SCHED_FIFO Nedir - Time Quantum Kavramı Yok
Öncelik sırasına göre koşturuyor. POSIX'e göre bu uygulamaların önceliği 0 - 99 arasındadır. İşletim sistemleri daha farklı değerler kullanmışlar. Zaman dilimi (time quantum) kavramı yok. Uygulama bir şey üzerinde bloke oluncaya kadar koşuyor. Yani pre-emption yok.
A SCHED_FIFO process runs until either it is blocked by an I/O request, it is preempted by a higher priority process, or it calls sched_yield(2).
POSIX Açısından SCHED_RR Nedir - Time Quantum Kavramı Var
SCHED_FIFO'ya benziyor. Öncelik sırası yüksek olan herkesin önüne geçiyor. Ancak en önemli fark, bu tipte bir zaman dilimi kavramı varBurada şöyle bir cümleye denk geldim.
"SCHED_RR can be preempted by time slicing". 
Süresi biten uygulamadan sonra bir sonraki en yüksek önceliğe sahip uygulama koşturuluyor. Eğer herkes eşitse önceliğe sahipse round robin şeklinde seçim yapılıyor.

Normal Scheduler
Önceliği (priority) 0 olan uygulamalar Normal Scheduler tarafından çalıştırılırlar. Sadece 1 tane var
1. SCHED_NORMAL. Bunun POSIX'teki ismi SCHED_OTHER

POSIX Açısından SCHED_OTHER Nedir
Normal uygulamalar SCHED_OTHER seviyesinde koşarlar. POSIX'e göre bu uygulamaların önceliği 100 - 139 arasındadır. İşletim sistemleri daha farklı değerler kullanmışlar. 

nice komutu bu aralıktaki uygulamalar içindir. SCHED_OTHER dışında bir policy kullanmak için root olmak gerekir.

Linux Açısından SCHED_NORMAL Nedir?
Açıklaması şöyle
The scheduler implementing SCHED_NORMAL scheduling policy is Completely Fair Scheduler (or CFS) . It is a timeshare scheduler in the sense that all process it schedules get a time slice from a time quantum in round robin fashion. This is the scheduler that is used by default to schedule normal Linux processes.
POSIX Scheduler API'si
POSIX hem uygulama, hem de thread'ler için Scheduler API'si sağlıyor. Çünkü çoğu sistemde thread, aslında process gibi düşünülüyor.



perf komutu

Giriş
Açıklaması şöyle
perf is a powerful Linux profiling tool, refined and upgraded by Linux kernel developers. In addition to common features such as analyzing Performance Monitoring Unit (PMU) hardware events and kernel events, perf has the following subcomponents:

- sched: Analyzes scheduler actions and latencies.
- timechart: Visualizes system behaviors based on the workload.
- c2c: Detects the potential for false sharing. Red Hat once tested the c2c prototype on a number of Linux applications and found many cases of false sharing and cache lines on hotspots.
- trace: Traces system calls with acceptable overheads. It performs only 1.36 times slower with workloads specified in the dd command.
Kurulum
Şöyle yaparız
sudo apt install linux-kernel-tools
perf.conf Dosyası
kernel.perf_event_paranoid Alanı
Açıklaması şöyle
By default, Perf uses an event level of 4 which is fine for any system as it is not too invasive on the host. Therefore, only a minority of all important events can be detected by Perf. We need to get as much information as possible for development purposes by sacrificing security considerations. Consequently, we want to set the ‘perf_event_paranoia’ to -1
Şöyle yaparız
sudo /etc/sysctl.d/perf.conf > kernel.perf_event_paranoid = -1
trace seçeneği
Örnek
200 milisaniyeden daha fazla süren sistem çağrılarını görmek için şöyle yaparız
perf trace --duration 200 

21 Ocak 2021 Perşembe

bash kodlama - shift built-in komutu

Giriş
Açıklaması şöyle. Script'i çalıştırırken verilen parametreleri - yani positional parameters dizisini - sola kaydırır
$ help shift
shift: shift [n]
    Shift positional parameters.

    Rename the positional parameters $N+1,$N+2 ... to $1,$2 ...  If N is
    not given, it is assumed to be 1.

    Exit Status:
    Returns success unless N is negative or greater than $#.
Örnek
Elimizde şöyle bir scrip olsun.
$ cat argtest.bash 
#!/bin/bash

shift 2

echo "$*"
Çalıştıralım. Çıktı olarak şunu alırız. Positional parameters 2 defa sola kaydırıldığı için "$*" da etkilenir.
$ ./argtest.bash foo bar baz bam boo
baz bam boo
Örnek
Elimizde şöyle bir script olsun

- $# number of positional parameters anlamına gelir. 
- while döngüsü ile positional parameters olduğu müddetçe dönülür.
- $1 ile ilk positional parametre alınır. 
- shift ile positional parameters bir kere sola kaydırılır.
Yani aslında bu script her positional parametre ile bir iş yapar ve hepsini işleyince sonlanır
#!/bin/bash
#
while $# -gt 0 ; do
    file="$1"
    shift
    year="$( echo "$file" | cut -c 14-17)"
    mnth="$( echo "$file" | cut -c 18-19)"
    [[ -d $year/$mnth ]] || mkdir -p $year/$mnth
    echo mv "$file" $year/$mnth
done
Bu script'i çağırmak için şöyle yaparız. Böylece find ile bulunan her dosya, xargs'ın izin verdiği ölçüde topluca yukarıdaki script'e geçilir.
find . -maxdepth 1 -type f -name '*201*' -printf | \
    xargs -r the_script

18 Ocak 2021 Pazartesi

mtools

Giriş
mtools paketi bir dosyayı FAT32 olarak kullanabilmeyi sağlar. Bu paketi kurunca mformat, mcopy, mdir, gibi komutlar kurulur

Örnek
Şöyle yaparız
# Create a 2 MB file
dd if=/dev/zero of=disk.img bs=1M count=2

# Put a FAT filesystem on it (use -F for FAT32, otherwise it's automatic)
mformat -i disk.img ::

# Add a file to it
mcopy -i disk.img example.txt ::

# List files
mdir -i disk.img ::

# Extract a file
mcopy -i disk.img ::/example.txt extracted.txt

14 Ocak 2021 Perşembe

helm komutu

Giriş
values.yaml
Açıklaması şöyle
This file declares variables to be passed into the templates. Modify the file to include your Docker image, tag, and service name, ports, type, and database values
Templates Dosyaları
Açıklaması şöyle
The most important piece of the puzzle is the templates/ directory. This is where Helm finds the YAML definitions for your Services, Deployments and other Kubernetes objects. If you already have definitions for your application, all you need to do is replace the generated YAML files for your own. What you end up with is a working chart that can be deployed using the helm install command.

It's worth noting however, that the directory is named templates, and Helm runs each file in this directory through a Go template rendering engine. Helm extends the template language, adding a number of utility functions for writing charts.
templates/service.yaml file
Örnek
Şöyle yaparız
apiVersion: v1
kind: Service
metadata:
name: {{ template "fullname" . }}
labels:
    chart: "{{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}"
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.externalPort }}
    targetPort: {{ .Values.service.internalPort }}
    protocol: TCP
    name: {{ .Values.service.name }}
selector:
    app: {{ template "fullname" . }}
Eğer dry run yaparsak çıktı olarak şunu alırız
helm install --dry-run --debug ./mychart
...
# Source: mychart/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
name: pouring-puma-mychart
labels:
    chart: "mychart-0.1.0"
spec:
type: ClusterIP
ports:
- port: 80
    targetPort: 80
    protocol: TCP
    name: nginx
selector:
    app: pouring-puma-mychart
...
templates/deployment.yaml file
Açıklaması şöyle
This file contains the instructions to launch the application container.



10 Ocak 2021 Pazar

pthread_cond_timedwait metodu

Giriş
Belirtilen pthread_cond_t kullanılarak pthread_mutex_t üzerinde beklenir

Örnek 
Elimizde şöyle yardımcı metodlar olsun
void addNanos(struct timespec *base, struct timespec *deadline, int deltaNanos) {
  deadline->tv_sec = base->tv_sec;
  deadline->tv_nsec = (base->tv_nsec) + deltaNanos;
  //todo: deal with nanos overflow
}

bool isDeadlineReached(struct timespec* deadline) {
  struct timespec currentTime;
  clock_gettime(CLOCK_TYPE, &currentTime);

  return currentTime.tv_sec >= deadline->tv_sec &&
currentTime.tv_nsec >= deadline->tv_nsec;
}

int initializeCond(pthread_cond_t *cond) {
  pthread_condattr_t cond_attr;
  if (pthread_condattr_init (&cond_attr)) {
    return -1;
  }
  if (pthread_condattr_setclock (&cond_attr, CLOCK_MONOTONIC)) {
    return -1;
  }
  if (pthread_cond_init (cond, &cond_attr)) {
    return -1;
  }
  return 0;
}
Şöyle yaparız
int main() {
    
  int deltaNanos = 2000;
  pthread_cond_t cond;
  pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

  if (initializeCond(&cond)) {
    return -1;
  }

  struct timespec start, end, deadline;
  if (pthread_mutex_lock(&lock)) {
    return -1;
  }
  clock_gettime(CLOCK_TYPE, &start);
  addNanos(&start, &deadline, deltaNanos);

  while (!isDeadlineReached(&deadline)) {
    pthread_cond_timedwait(&cond, &lock, &deadline);
  }

  return 0;
}

8 Ocak 2021 Cuma

dump-gnash komutu

Giriş
gnash SWF dosyalarını oynatır. dumpg_gnash SWL dosyasındaki veriyi ham olarak dışarı çıkarır

-r seçeneği
Açıklaması şöyle
0 disables rendering and sound (good for batch tests).
1 enables rendering, disable sound.
2 disables rendering, enable sound.
3 enables rendering and sound (default setting).
Örnek
Açıklaması şöyle
Gnash can read a SWF file with passed flashvars and output it as a RAW file for later conversion.
Şöyle yaparız -1 ile "play once" yapılıyor. -r 1 ile sadece video dışarı çıkarılıyor
dump-gnash -1 -r 1 -D $TMPFILE $SWFFILE

Örnek
Şöyle yaparız
dump-gnash -1 \
           -D /tmp/out.raw@30 \
           -A /tmp/out.wav \                      
           -P "FlashVars=myURL=http://example.com/blah&online=true" \
           http://example.com/blah/some.swf
Açıklaması şöyle
This will write out /tmp/out.raw (which is bgra aka rgb32 video) at 30fps (the @30 bit) and /tmp/out.wav (the audio track).

These need re-combining into e.g. mp4 using:
Şöyle yaparız
ffmpeg -i /tmp/out.wav \
       -f rawvideo \
       -pix_fmt rgb32 \
       -s:v 800x550 \
       -r 30 \
       -i /tmp/out \
       -c:v libx264 \
       -r 30 \
       -b 160k \
       /tmp/out.mp4
Açıklaması şöyle
because it's raw video, ffmpeg needs to know the colourspace (rgb32), dimensions and input fps. We tell it to combine the audio (160kbps mp3), render the video back out at 30fps.