aboutsummaryrefslogtreecommitdiffstats
path: root/elisp/cmk.el
blob: 98ea8d04065b33e3c2810faefcd0ce55be85c792 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
;;; cmk.el --- CMK livestatus -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2022 Óscar Nájera
;;
;; Author: Óscar Nájera <hi@oscarnajera.com>
;; Maintainer: Óscar Nájera <hi@oscarnajera.com>
;; 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 "29.1"))
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;;  CMK livestatus
;;
;;; Code:

(require 'cl-lib)
;; (require 'company)
(require 'map)
(require 'csv-mode)
(require 'dash)
(require 'subr-x)
(require 'vtable)

(defun cmk-state-coloring (state)
  "Font color for numeric STATE input as string."
  (pcase 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 column :column)
                 (plist-get column :name)))
           spec
           " ")))

(defconst cmk-problem-col-spec
  `((:name "STATE"        :column "service_state" :formatter cmk-state-coloring :min-width 6)
    (:name "Host"         :column "host_name")
    (:name "Service"      :column "service_description")
    (:name "Since"        :column "service_last_state_change" :formatter cmk-timestamp-to-date :min-width 18)
    (:name "Check output" :column "service_plugin_output" :formatter cmk-purge-bangs)))

(defconst cmk-log-col-spec
  '(;("host_state" :column "host_state" :parser cmk-state-coloring)
    (:name "STATE" :min-width 6 :column "log_state" :formatter cmk-state-coloring)
    ;; ("lsttype" :column "log_state_type")
    (:name "Host" :column "host_name")
    (:name "Service" :column "service_description")
    (:name "log_time" :min-width 18 :column "log_time" :formatter cmk-timestamp-to-date)
    ;; ("log_command_name" :column "log_command_name")
    ;; ("log_comment" :column "log_comment")
    ;; ("lineno" :column "log_lineno")
    (:name "log_type" :column "log_type")
    ;; ("host_scheduled_downtime_depth" :column "host_scheduled_downtime_depth")
    ;; ("host_has_been_checked" :column "host_has_been_checked")
    (:name "log_plugin_output" :column "log_plugin_output")))

(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-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 ()
  "Open buffer to write a 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))
                           (csv-set-separator ?\;)
                           (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-livestatus->json (query)
  "Send QUERY to livestatus then parse the result assuming is JSON."
  (let ((cmks (cmk-livestatus-query query)))
    (accept-process-output cmks 0.1)
    (with-current-buffer (process-buffer cmks)
      (goto-char (point-min))
      (json-parse-buffer :array-type 'list))))

(defun cmk-vtable-revert (livestatus-query)
  "Regenerate the table under point with the updated LIVESTATUS-QUERY."
  (let ((table (vtable-current-table))
        (object (vtable-current-object))
        (column (vtable-current-column))
        (inhibit-read-only t))
    (unless table
      (user-error "No table under point"))
    (setf (vtable-objects table) (cmk-livestatus->json livestatus-query))
    (vtable--clear-cache table)
    (delete-region (progn (text-property-search-backward 'vtable) (point))
                   (progn (text-property-search-forward 'vtable) (point)))
    (vtable-insert table)
    (cmk-add-text-properties-to-table (list 'livestatus-query livestatus-query))
    (when object
      (vtable-goto-object object))
    (when column
      (vtable-goto-column column))))

(defun cmk-add-text-properties-to-table (properties)
  "Add PROPERTIES a plist to the current table under point."
  (add-text-properties (progn (text-property-search-backward 'vtable) (point))
                       (progn (text-property-search-forward 'vtable) (point))
                       properties))

(cl-defun cmk-edit-lq ()
  "Open window to edit the livestatus query of current BUFFER."
  (interactive)
  (let ((buffer (current-buffer))
        (edit-buffer (get-buffer-create "*LQ*"))
        (query (get-text-property (point) 'livestatus-query)))
    (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)
                         (cmk-vtable-revert new-query)))))
    (switch-to-buffer edit-buffer)))

(defun cmk-vtable (table spec filters)
  "Render a tabular view for livestatus TABLE with SPEC columns using FILTERS."
  (let ((livestatus-query
         (format "GET %s\n%s\n%s\n%s\n\n"
                 table
                 (cmk-colums-from-spec spec)
                 filters
                 "OutputFormat: json")))
    (make-vtable
     :columns (mapcar (lambda (li) (map-delete (map-copy li) :column)) spec)
     :use-header-line nil
     :objects (cmk-livestatus->json livestatus-query)
     :keymap (define-keymap
               "Q" #'cmk-edit-lq
               "q" #'kill-current-buffer))
    (cmk-add-text-properties-to-table (list 'livestatus-query livestatus-query))))

(defun cmk-problems ()
  "Render default problems view."
  (interactive)
  (let ((inhibit-read-only t))
    (with-current-buffer (get-buffer-create "*CMK View*")
      (special-mode)
      (erase-buffer)
      (cmk-vtable "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:")
      (goto-char (point-max))
      (insert "\n")
      (cmk-vtable "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)))))
      (display-buffer (current-buffer)))))

(provide 'cmk)
;;; cmk.el ends here