;;; cmk.el --- CMK livestatus -*- lexical-binding: t; -*- ;; ;; Copyright (C) 2022 Óscar Nájera ;; ;; Author: Óscar Nájera ;; Maintainer: Óscar Nájera ;; Created: July 08, 2022 ;; Modified: July 08, 2022 ;; Version: 0.0.1 ;; Keywords: abbrev bib c calendar comm convenience data docs emulations extensions faces files frames games hardware help hypermedia i18n internal languages lisp local maint mail matching mouse multimedia news outlines processes terminals tex tools unix vc wp ;; Homepage: https://github.com/titan/cmk ;; Package-Requires: ((emacs "27.1")) ;; ;; This file is not part of GNU Emacs. ;; ;;; Commentary: ;; ;; CMK livestatus ;; ;;; Code: (require 'subr-x) (require 'cl-lib) (require 'dash) (require 'company) (require 'csv-mode) (defun cmk-state-coloring (state) "Font color for numeric STATE input as string." (cl-check-type state string) (pcase (string-to-number state) (0 (propertize "OK" 'face 'font-lock-string-face)) (1 (propertize "WARN" 'face 'font-lock-warning-face)) (2 (propertize "CRIT" 'face 'font-lock-keyword-face)) (3 (propertize "UNKN" 'face 'font-lock-builtin-face)) (_ state))) (defun cmk-timestamp-to-date (timestamp &optional fmt-str) "TIMESTAMP to human readable date follownig FMT-STR. Default is \"%Y-%m-%d %H:%M\"." (thread-last (if (stringp timestamp) (string-to-number timestamp) timestamp) (seconds-to-time) (format-time-string (or fmt-str "%Y-%m-%d %H:%M")))) (defun cmk-purge-bangs (str) "Remove cmk status output bangs from STR." (replace-regexp-in-string (rx "(" (+ "!") ")") "" str)) (defun cmk-oneshot (&optional keep-buffer) "One shot socket connection. non-nil KEEP-BUFFER after socket closes." (make-network-process :name "Checkmk" :host 'local :service 6565 :buffer "CMK" :sentinel (lambda (process event) (message "Process: %s had the event '%s'" process (string-trim event)) (unless keep-buffer (kill-buffer (process-buffer process)))))) (defun cmk-colums-from-spec (spec) "Extract the column names from SPEC and return a livestatus column command." (concat "Columns: " (mapconcat (lambda (column) (or (plist-get (cdddr column) :column) (car column))) spec " "))) (defconst cmk-problem-col-spec `(("STATE" 5 t :column "service_state" :parser cmk-state-coloring ) ("Host" 9 t :column "host_name") ("Service" 20 t :column "service_description") ("Since" 16 ,(lambda (a b) (time-less-p (encode-time (parse-time-string (elt (cadr a) 3))) (encode-time (parse-time-string (elt (cadr b) 3))))) :column "service_last_state_change" :parser cmk-timestamp-to-date) ("Check output" 18 t :column "service_plugin_output" :parser cmk-purge-bangs))) (defconst cmk-log-col-spec '(;("host_state" 5 t :column "host_state" :parser cmk-state-coloring) ("STATE" 5 t :column "log_state" :parser cmk-state-coloring) ;; ("lsttype" 8 t :column "log_state_type") ("Host" 9 t :column "host_name") ("Service" 12 t :column "service_description") ("log_time" 16 t :column "log_time" :parser cmk-timestamp-to-date) ;; ("log_command_name" 10 t :column "log_command_name") ;; ("log_comment" 15 t :column "log_comment") ;; ("lineno" 8 t :column "log_lineno") ("log_type" 16 t :column "log_type") ;; ("host_scheduled_downtime_depth" 5 t :column "host_scheduled_downtime_depth") ;; ("host_has_been_checked" 5 t :column "host_has_been_checked") ("log_plugin_output" 5 t :column "log_plugin_output"))) (defun cmk-parse-rows (buffer column-spec) "Return tabulated entries from BUFFER according to COLUMN-SPEC." (with-current-buffer buffer (goto-char (point-min)) (let (rows (parsers (mapcar (lambda (spec) (or (plist-get (cdddr spec) :parser) #'identity)) column-spec))) (while (not (eobp)) (thread-first (list (count-lines 1 (point)) (cl-map 'vector (lambda (parser entry) (funcall parser entry)) parsers (split-string (thing-at-point 'line t) ";" nil "\n"))) (push rows)) (forward-line)) (nreverse rows)))) (defun cmk-livestatus-query (query) "One shot livestatus QUERY, return network process." (let ((cmks (cmk-oneshot 'keep))) (with-current-buffer (process-buffer cmks) (erase-buffer)) (process-send-string cmks query) cmks)) (defvar-local cmk-livestatus-query "" "Livestatus query in buffer.") (defun cmk-table--refresh () "Query and reprint the Livestatus query result table." (let ((cmks (cmk-livestatus-query cmk-livestatus-query))) (accept-process-output cmks 0.1) (setq tabulated-list-entries (cmk-parse-rows (process-buffer cmks) tabulated-list-format)) (tabulated-list-print 'remember))) (defun cmk-timestamp-eldoc-documentation () (when-let ((number (thing-at-point 'number))) (format-time-string "%Y-%m-%d %H:%M" (seconds-to-time number)))) (defconst cmk-livestatus-headers '("Filter" "Columns" "Stats" "Limit" "ColumnHeaders" "OutputFormat")) (define-derived-mode cmk-livestatus-mode prog-mode "livestatus" "Major mode for viewing journalctl output." (add-function :before-until (local 'eldoc-documentation-function) #'cmk-timestamp-eldoc-documentation) ;; (setq-local company-backends (cons 'company-cmk-lq company-backends)) ;; (setq-local completion-at-point-functions '(cmk-lq-capf)) (add-hook 'completion-at-point-functions 'cmk-lq-capf nil 'local) ;; code for syntax highlighting (setq font-lock-defaults `(((,(rx bol "GET" eow) . font-lock-keyword-face) (,(rx word-start (or "hosts" "services") word-end) . font-lock-constant-face) (,(concat "^" (regexp-opt cmk-livestatus-headers 'words) ":[[:space:]]") . font-lock-function-name-face) (,(rx bol (or "And" "Or" "Negate") ":" whitespace) . font-lock-keyword-face) (,(rx whitespace (or "~" "=" "=~" "~~" "<" ">" "<=" ">=") whitespace) . font-lock-keyword-face))))) (defun cmk-custom-livestatus-query () (interactive) (let ((query cmk-livestatus-query) (edit-buffer (get-buffer-create "*LQ*"))) (with-current-buffer edit-buffer (cmk-livestatus-mode) (if (string-blank-p query) (insert "GET ") (insert query)) (local-set-key "\C-c\C-c" (lambda () (interactive) (let ((new-query (-> (buffer-string) (string-trim) (concat "\n\n")))) (kill-buffer) (let ((cmk (cmk-livestatus-query new-query))) (switch-to-buffer (process-buffer cmk)) (setq csv-separators '(";") csv-separator-regexp "[;]" csv-separator-chars '(59)) (csv-align-mode) (setq-local cmk-livestatus-query new-query)))))) (switch-to-buffer edit-buffer))) (defun company-cmk-lq (command &optional arg &rest ignored) (interactive (list 'interactive)) (cl-case command (interactive (company-begin-backend 'company-cmk-lq)) (prefix (company-grab-word)) (candidates (cl-loop for header in cmk-livestatus-headers when (string-prefix-p arg header t) collect header)) (meta (format "This value is named %s" arg)))) (defun cmk-lq-capf () (when (looking-back (rx bol (+ alpha)) 1) (list (match-beginning 0) (match-end 0) (cl-loop for header in cmk-livestatus-headers when (string-prefix-p (match-string-no-properties 0) header t) collect (concat header ": "))))) (defun cmk-edit-lq (buffer) "Open window to edit the livestatus query of current BUFFER." (interactive (list (current-buffer))) (let ((query cmk-livestatus-query) (edit-buffer (get-buffer-create "*LQ*"))) (with-current-buffer edit-buffer (cmk-livestatus-mode) (insert query) (local-set-key "\C-c\C-c" (lambda () (interactive) (let ((new-query (-> (buffer-string) (string-trim) (concat "\n\n")))) (kill-buffer) (switch-to-buffer buffer) (setq-local cmk-livestatus-query new-query) (cmk-table--refresh))))) (switch-to-buffer edit-buffer))) (defun cmk-view (table spec filters) "Render a tabular view for livestatus TABLE with SPEC columns using FILTERS." (with-current-buffer (get-buffer-create "*CMK View*") (tabulated-list-mode) (setq-local cmk-livestatus-query (format "GET %s\n%s\n%s\n\n" table (cmk-colums-from-spec spec) filters)) (setq tabulated-list-format (vconcat spec)) (add-hook 'tabulated-list-revert-hook #'cmk-table--refresh nil t) (local-set-key "Q" #'cmk-edit-lq) (tabulated-list-init-header) (cmk-table--refresh) (switch-to-buffer (current-buffer)))) (defun cmk-problems () "Render default problems view." (interactive) (cmk-view "services" cmk-problem-col-spec "Filter: service_state = 0 Filter: service_has_been_checked = 1 And: 2 Negate: Filter: service_has_been_checked = 1 Filter: service_scheduled_downtime_depth = 0 Filter: host_scheduled_downtime_depth = 0 And: 2 Filter: service_acknowledged = 0 Filter: host_state = 1 Filter: host_has_been_checked = 1 And: 2 Negate: Filter: host_state = 2 Filter: host_has_been_checked = 1 And: 2 Negate:")) (defun cmk-log-prob () "Render default event log view." (interactive) (cmk-view "log" cmk-log-col-spec (format "Filter: log_time >= %d Filter: class = 1 Filter: class = 3 Filter: class = 8 Or: 3 Filter: log_state_type = HARD" (floor (- (time-to-seconds (current-time)) (* 24 3600)))))) ;;; Get a different csv ;; (let* ((cmks (cmk-oneshot t))) ;; (with-current-buffer (process-buffer cmks) (erase-buffer)) ;; (process-send-string cmks "GET services ;; Columns: service_description host_name service_perf_data ;; Filter: service_description ~ CPU utilization ;; OutputFormat: csv ;; Separators: 10 9 44 124\n\n") ;; (accept-process-output cmks 0.1) ;; (display-buffer (process-buffer cmks))) ;;; Get some metric data ;; (let* ((now (time-convert nil 'integer)) ;; (start (- now 7200)) ;; (cmks (cmk-oneshot t))) ;; (with-current-buffer (process-buffer cmks) (erase-buffer)) ;; (process-send-string cmks (format "GET services ;; Columns: host_name rrddata:1:user:%d:%d:1 ;; Filter: service_description ~ CPU utilization ;; OutputFormat: json\n\n" start now)) ;; (accept-process-output cmks 0.1) ;; (with-current-buffer (process-buffer cmks) ;; (goto-char (point-min)) ;; (display-buffer (current-buffer)) ;; (json-parse-buffer))) (provide 'cmk) ;;; cmk.el ends here