Compare commits

..

2 Commits

Author SHA1 Message Date
3576135011 ... 2025-04-08 11:11:53 +02:00
f6aac26bbb Work in progress... 2025-04-08 10:31:29 +02:00
12 changed files with 504 additions and 0 deletions

9
Containerfile Normal file
View File

@ -0,0 +1,9 @@
FROM registry.opensuse.org/opensuse/tumbleweed:latest
RUN zypper --non-interactive install --no-recommends \
python3-kubernetes \
python3-pyudev \
&& zypper clean -a \
&& rm /var/log/zypper.log
ENV TZ="Europe/Stockholm"

124
app/alarm.py Normal file
View File

@ -0,0 +1,124 @@
# encoding: utf-8
'''
Created on 12/09/2012
@author: dnmellen
'''
__author__ = "Diego Navarro Mellén"
__email__ = "dnmellen@gmail.com"
__version__ = 0.5
import usb
from usb.core import USBError
import time
### Some auxiliary functions ###
def _clean_str(s):
'''
Filter string to allow only alphanumeric chars and spaces
@param s: string
@return: string
'''
return ''.join([c for c in s if c.isalnum() or c in {' '}])
def _get_dev_string_info(device):
'''
Human readable device's info
@return: string
'''
try:
str_info = _clean_str(usb.util.get_string(device, 256, 2))
str_info += ' ' + _clean_str(usb.util.get_string(device, 256, 3))
return str_info
except USBError:
return str_info
def get_usb_devices():
'''
Get USB devices
@return: list of tuples (dev_idVendor, dev_idProduct, dev_name)
'''
return [(device.idVendor, device.idProduct, _get_dev_string_info(device))
for device in usb.core.find(find_all=True)
if device.idProduct > 2]
class USBAlarm(object):
'''
USB Alarm Class
'''
def __init__(self, devices=None, payload=None, check_interval=0.5):
'''
Constructor
@param devices: list of tuples (dev_idVendor, dev_idProduct, dev_name)
@param payload: function to call if any device is disconnected
@param check_interval: number of secs to wait in each check
'''
self.devices = devices or []
self.payload = payload
self.check_interval = check_interval
def is_any_disconnected(self):
'''
Check if any device has been disconnected.
@return: True if found any device unplugged
'''
return not all([usb.core.find(idVendor=device[0], idProduct=device[1])
for device in self.devices])
def run(self):
'''
Make sure every device is plugged in an infinite loop
'''
while True:
if self.is_any_disconnected() and self.payload:
self.payload()
time.sleep(self.check_interval)
def dummy_payload():
print("kallekalas")
if __name__ == '__main__':
# Catch signal CTRL+C to exit test
import signal
import sys
def signal_handler(signal, frame):
print( 'You Pressed CTRL+C')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
# Dummy test
#from payloads import play_sound
print ("* Exploring devices")
devices = get_usb_devices()
for d in devices:
print (d[2])
print ("===================")
print ("Monitoring USB devices... (Press CTRL+C for exit)")
a = USBAlarm(devices=devices, payload=dummy_payload)
# a = USBAlarm(devices=devices, payload=play_sound.payload)
a.run()

40
app/check_usb.py Normal file
View File

@ -0,0 +1,40 @@
import usb
from usb.core import USBError
### Some auxiliary functions ###
def _clean_str(s):
'''
Filter string to allow only alphanumeric chars and spaces
@param s: string
@return: string
'''
return ''.join([c for c in s if c.isalnum() or c in {' '}])
def _get_dev_string_info(device):
'''
Human readable device's info
@return: string
'''
try:
str_info = _clean_str(usb.util.get_string(device, 256, 2))
str_info += ' ' + _clean_str(usb.util.get_string(device, 256, 3))
return str_info
except USBError:
return str_info
def get_usb_devices():
'''
Get USB devices
@return: list of tuples (dev_idVendor, dev_idProduct, dev_name)
'''
return [(device.idVendor, device.idProduct, _get_dev_string_info(device))
for device in usb.core.find(find_all=True)
if device.idProduct > 2]

49
app/monitor.py Normal file
View File

@ -0,0 +1,49 @@
import pyudev
import signal
import logging
import sys
import os
def on_usb_attached(device):
print(f"USB device attached: {device.device_node or device.sys_name}")
def on_usb_detached(device):
print(f"USB device detached: {device.device_node or device.sys_name}")
def list_current_usb_devices():
print("Currently attached USB devices:")
context = pyudev.Context()
for device in context.list_devices(subsystem='usb', DEVTYPE='usb_device'):
print(f"- {device.device_node or device.sys_name} ({device.get('ID_MODEL', 'Unknown Device')})")
print()
def monitor_usb():
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb') # Only USB devices
for device in iter(monitor.poll, None):
if device.action == 'add':
on_usb_attached(device)
elif device.action == 'remove':
on_usb_detached(device)
def signal_handler(sig, frame):
print("\nStopping USB monitor...")
sys.exit(0)
if __name__ == "__main__":
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
try:
CURRENT_NODE_NAME=os.environ['CURRENT_NODE_NAME']
logging.info(f"Starging USB-watch on {CURRENT_NODE_NAME}")
except KeyError:
logging.error('Environment variabel CURRENT_NODE_NAME is not set')
sys.exit(1)
signal.signal(signal.SIGINT, signal_handler)
list_current_usb_devices()
logging.info("Monitoring USB device changes......")
monitor_usb()

28
daemonset.yaml Normal file
View File

@ -0,0 +1,28 @@
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: dongle-watch
namespace: dongle-watch
spec:
selector:
matchLabels:
name: dongle-watch
template:
metadata:
labels:
name: dongle-watch
spec:
containers:
- name: dongle-watch
image: repo.rre.nu/library/dongle-watch:latest
env:
- name: RUNNIN_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
resources:
limits:
cpu: 200Mi
requests:
cpu: 100m
memory: 200Mi

23
helm/.helmignore Normal file
View File

@ -0,0 +1,23 @@
# Patterns to ignore when building packages.
# This supports shell glob matching, relative path matching, and
# negation (prefixed with !). Only one pattern per line.
.DS_Store
# Common VCS dirs
.git/
.gitignore
.bzr/
.bzrignore
.hg/
.hgignore
.svn/
# Common backup files
*.swp
*.bak
*.tmp
*.orig
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/

24
helm/Chart.yaml Normal file
View File

@ -0,0 +1,24 @@
apiVersion: v2
name: usb-watch
description: A daemonset to watch for USB-dongles to be added or removed and adds/removes annotations
# A chart can be either an 'application' or a 'library' chart.
#
# Application charts are a collection of templates that can be packaged into versioned archives
# to be deployed.
#
# Library charts provide useful utilities or functions for the chart developer. They're included as
# a dependency of application charts to inject those utilities and functions into the rendering
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
type: application
# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 0.1.0
# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
# It is recommended to use it with quotes.
appVersion: "0.1.0"

22
helm/templates/NOTES.txt Normal file
View File

@ -0,0 +1,22 @@
1. Get the application URL by running these commands:
{{- if .Values.ingress.enabled }}
{{- range $host := .Values.ingress.hosts }}
{{- range .paths }}
http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }}
{{- end }}
{{- end }}
{{- else if contains "NodePort" .Values.service.type }}
export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "usb-watch.fullname" . }})
export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
echo http://$NODE_IP:$NODE_PORT
{{- else if contains "LoadBalancer" .Values.service.type }}
NOTE: It may take a few minutes for the LoadBalancer IP to be available.
You can watch its status by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "usb-watch.fullname" . }}'
export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "usb-watch.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}")
echo http://$SERVICE_IP:{{ .Values.service.port }}
{{- else if contains "ClusterIP" .Values.service.type }}
export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "usb-watch.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}")
echo "Visit http://127.0.0.1:8080 to use your application"
kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT
{{- end }}

View File

@ -0,0 +1,62 @@
{{/*
Expand the name of the chart.
*/}}
{{- define "usb-watch.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "usb-watch.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "usb-watch.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Common labels
*/}}
{{- define "usb-watch.labels" -}}
helm.sh/chart: {{ include "usb-watch.chart" . }}
{{ include "usb-watch.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/*
Selector labels
*/}}
{{- define "usb-watch.selectorLabels" -}}
app.kubernetes.io/name: {{ include "usb-watch.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{/*
Create the name of the service account to use
*/}}
{{- define "usb-watch.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "usb-watch.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}

View File

@ -0,0 +1,49 @@
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: {{ include "usb-watch.fullname" . }}
labels:
{{- include "usb-watch.labels" . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount }}
{{- end }}
selector:
matchLabels:
{{- include "usb-watch.selectorLabels" . | nindent 6 }}
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "usb-watch.labels" . | nindent 8 }}
{{- with .Values.podLabels }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include "usb-watch.serviceAccountName" . }}
containers:
- name: {{ .Chart.Name }}
securityContext:
privileged: true
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
livenessProbe:
{{- toYaml .Values.livenessProbe | nindent 12 }}
readinessProbe:
{{- toYaml .Values.readinessProbe | nindent 12 }}
resources:
{{- toYaml .Values.resources | nindent 12 }}
volumeMounts:
- mountPath: /dev/bus/usb
name: usb
volumes:
- name: usb
hostPath:
path: /dev/bus/usb

View File

@ -0,0 +1,13 @@
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ include "usb-watch.serviceAccountName" . }}
labels:
{{- include "usb-watch.labels" . | nindent 4 }}
{{- with .Values.serviceAccount.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
automountServiceAccountToken: {{ .Values.serviceAccount.automount }}
{{- end }}

61
helm/values.yaml Normal file
View File

@ -0,0 +1,61 @@
# Default values for usb-watch.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
# This will set the replicaset count more information can be found here: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/
replicaCount: 1
# This sets the container image more information can be found here: https://kubernetes.io/docs/concepts/containers/images/
image:
repository: repo.rre.nu/library/usb-watch
# This sets the pull policy for images.
pullPolicy: IfNotPresent
# Overrides the image tag whose default is the chart appVersion.
tag: ""
# This is for the secretes for pulling an image from a private repository more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
imagePullSecrets: []
# This is to override the chart name.
nameOverride: ""
fullnameOverride: ""
#This section builds out the service account more information can be found here: https://kubernetes.io/docs/concepts/security/service-accounts/
serviceAccount:
# Specifies whether a service account should be created
create: true
# Automatically mount a ServiceAccount's API credentials?
automount: true
# Annotations to add to the service account
annotations: {}
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template
name: ""
# This is for setting Kubernetes Annotations to a Pod.
# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/
podAnnotations: {}
# This is for setting Kubernetes Labels to a Pod.
# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
podLabels: {}
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi
# This is to setup the liveness and readiness probes more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http