How to start a bash shell in Docker

Tagged bash, docker, shell  Languages bash

To start a bash shell in an already running container:

docker exec -it <container id/name> bash

To start a bash shell using an image of a container that is not running:

docker run -i -t --entrypoint /bin/bash <image id>

How read process exit code in Golang

Tagged code, exit, status  Languages go

This function returns true if the nz command returns exit code 0:

package main

import (
    "os/exec"
    "strconv"
)

// IsPortOpen returns a boolean that indicates if a port is open or closed.
func IsPortOpen(host string, port int) bool {
    args := []string{"-z", host, strconv.Itoa(port), "-G", "5"}
    cmd := exec.Command("/usr/bin/nc", args...)
    _, err := cmd.Output()
    if werr, ok := err.(*exec.ExitError); ok {
        if s := werr.Error(); s != "0" {
            return false
        }
    }
    return true
}

bcrypt example in Golang

Tagged bcrypt, golang  Languages go
package main

import (
    "golang.org/x/crypto/bcrypt"
    "log"
    "os"
)

// NOTE: You need to escape the dollar signs in the hash with \
// HASH="xxx" PASSWORD=xxx go run main.go
func main() {
    hash, ok := os.LookupEnv("HASH")
    if !ok {
        log.Fatal("The HASH environment variable is not set")
    }
    password, ok := os.LookupEnv("PASSWORD")
    if !ok {
        log.Fatal("The PASSWORD environment variable is not set")
    }
    if isMatch(password, hash) {
        log.Printf("Match '%s' == '%s'", hash, password)
    } else {
        log.Printf("Mismatch '%s' != '%s'", hash, password)
    }
}

func isMatch(password string, hash string) bool {
    err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    return err == nil
}

For loop in Postgres

Tagged for, loop, postgres  Languages sql
DO
$$
DECLARE
    row record;
BEGIN
    FOR row IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
    LOOP
        EXECUTE 'ALTER TABLE public.' || quote_ident(row.tablename) || ' SET SCHEMA <new schema>;';
    END LOOP;
END;
$$;

How to read barcodes with ZXing and ZBar

Tagged barcode, code 39, data matrix, qr code, zbar, zxing  Languages bash

How to read barcodes

$ java -cp javase.jar:core.jar com.google.zxing.client.j2se.CommandLineRunner barcode.png --try_harder --format=DATA_MATRIX
$ zbarimg barcode.png

Note that cropping might improve detection accuracy. For example, crop image to show only the top-right corner using imagemagick’s convert (width 1500, height 500):

$ convert example.png -gravity northeast -crop 1500x500+0+0 cropped.png

NOTE

  • if you need data correction (reliability) use a Data Matrix (used on e.g. products), Aztec (used on e.g. tickets), or QR code. These allow up to 30% of the image to be unreadable.
  • do not use a barcode that uses code 39 or 128. There is no error correction in code 39 and 128.
  • SimpleCV can also be used to detect barcodes.

Log shipping with rsyslog

Tagged logging, logs, remote, rsyslog, shipping  Languages 

Server

/etc/rsyslog.conf

$ModLoad imtcp
 
#
# Disable rate-limiting
#
# "interval = 1 AND burst = 1000" means rsyslog starts dropping messages if more than 1000 messages are received within 1 seconds. 
$SystemLogRateLimitInterval 0
$SystemLogRateLimitBurst 0

/etc/rsyslog.d/35-remote-logs.conf

input(type="imtcp" port="514" ruleset="remote")
template(name="PerRemoteHostLogFileName" type="list") {
   constant(value="/var/log/hosts/")
   property(name="$year")
   constant(value="/")
   property(name="$month")
   constant(value="/")
   property(name="hostname" securepath="replace")
   constant(value="/")
   property(name="programname" securepath="replace")
   constant(value=".log")
}
ruleset(name="remote") {
   $FileCreateMode 0640
   $DirCreateMode 0755
   ?PerRemoteHostLogFileName
}

Client

/etc/rsyslog.conf

# Disable rate-limiting
$SystemLogRateLimitInterval 0
$SystemLogRateLimitBurst 0

#
# Send all logs to centralized log server over TCP
#
*.*       @@{{log_server_ip_addr}}

How to deploy an app on a specific node/server in a kubernetes cluster using labels

Tagged kubernetes, label, node  Languages yaml

This is an example of how to deploy an app on a specific node/server in a kubernetes cluster using labels:

# # Label one node in k8s cluster
#
# $ kubectl label nodes 48.234.16.45 country=finland name=node1
#
# # Deploy 1 nginx pod in k8s cluster on node1 in Finland
#
# $ kubectl apply -f nginx.yml
#
# # View deployment
#
# $ kubectl describe deployment nginx-app
#
# # View pods
#
# $ kubectl get pods -l app=nginx
#
# # Find port the service is listening on
#
# $ kubectl describe service nginx-app | grep NodePort
# > NodePort:                 http   31796/TCP
# > NodePort:                 https  31797/TCP
#
# # Find the node the pod is deployed to
#
# $ kubectl describe pods nginx-app | grep Node
# > Node:           48.234.16.45/10.0.0.2
#
# # Access deployment using node ip and port
#
# http://<node ip>:<node port>
#
# # Export service to YAML
#
# $ kubectl get service nginx-app -o yaml --export
#
# # Delete
#
# $ kubectl delete deployments,services -l country=finland
#
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-app
  labels:
    run: nginx-app
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 1 # tells deployment to run 1 pods matching the template
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.13.12
        ports:
        - containerPort: 80
        - containerPort: 443
      nodeSelector:
        country: finland
        server: node1
---
#
# Expose deployment on <node ip>:<node port>. Node and a random port is assigned by k8s.
#
apiVersion: v1
kind: Service
metadata:
  labels:
    run: nginx-app
  name: nginx-app
spec:
  ports:
  - name: http
    port: 80
    protocol: TCP
    targetPort: 80
  - name: https
    port: 443
    protocol: TCP
    targetPort: 443
  selector:
    app: nginx
  type: NodePort

Kill OSX disk warning notification

Tagged kill, notification, osx  Languages bash

Kill OSX disk warning notification:

$ defaults write com.apple.diskspaced minFreeSpace 1

This prevents it from showing up every second, if free disk space is above 1 Gb.