-
Notifications
You must be signed in to change notification settings - Fork 917
/
Copy pathgovc.el
1660 lines (1441 loc) · 60.5 KB
/
govc.el
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; govc.el --- Interface to govc for managing VMware ESXi and vCenter
;; Author: The govc developers
;; URL: https://github.com/vmware/govmomi/tree/main/govc/emacs
;; Keywords: convenience
;; Version: 0.31.0
;; Package-Requires: ((emacs "24.3") (dash "1.5.0") (s "1.9.0") (magit-popup "2.0.50") (json-mode "1.6.0"))
;; This file is NOT part of GNU Emacs.
;; Copyright (c) 2016 VMware, Inc. All Rights Reserved.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;; Commentary:
;; The goal of this package is to provide a simple interface for commonly used
;; govc commands within Emacs. This includes table based inventory/state modes
;; for vms, hosts, datastores and pools. The keymap for each mode provides
;; shortcuts for easily feeding the data in view to other govc commands.
;;
;; Within the various govc modes, press `?' to see a popup menu of options.
;; A menu bar is enabled for certain modes, such as `govc-vm-mode' and `govc-host-mode'.
;; There is also a `govc' menu at all times under the `Tools' menu.
;;
;; The recommended way to install govc.el is via MELPA (http://melpa.org/).
;;; Code:
(eval-when-compile
(require 'cl))
(require 'dash)
(require 'diff)
(require 'dired)
(require 'json-mode)
(require 'magit-popup)
(require 'url-parse)
(require 's)
(autoload 'auth-source-search "auth-source")
(defgroup govc nil
"Emacs customization group for govc."
:group 'convenience)
(defcustom govc-keymap-prefix "C-c ;"
"Prefix for `govc-mode'."
:group 'govc)
(defcustom govc-command "govc"
"Executable path to the govc utility."
:type 'string
:group 'govc)
(defvar govc-command-map
(let ((map (make-sparse-keymap)))
(define-key map "h" 'govc-host)
(define-key map "p" 'govc-pool)
(define-key map "v" 'govc-vm)
(define-key map "s" 'govc-datastore)
(define-key map "?" 'govc-popup)
map)
"Keymap for `govc-mode' after `govc-keymap-prefix' was pressed.")
(defvar govc-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd govc-keymap-prefix) govc-command-map)
map)
"Keymap for `govc-mode'.")
;;;###autoload
(define-minor-mode govc-mode
"Running `govc-global-mode' creates key bindings to the various govc modes.
The default prefix is `C-c ;' and can be changed by setting `govc-keymap-prefix'.
\\{govc-mode-map\}"
nil govc-mode-line govc-mode-map
:group 'govc)
;;;###autoload
(define-globalized-minor-mode govc-global-mode govc-mode govc-mode)
(defcustom govc-mode-line
'(:eval (format " govc[%s]" (or (govc-session-name) "-")))
"Mode line lighter for govc."
:group 'govc
:type 'sexp
:risky t)
;;; Tabulated list mode extensions (derived from https://github.com/Silex/docker.el tabulated-list-ext.el)
(defun govc-tabulated-list-mark ()
"Mark and move to the next line."
(interactive)
(tabulated-list-put-tag (char-to-string dired-marker-char) t))
(defun govc-tabulated-list-unmark ()
"Unmark and move to the next line."
(interactive)
(tabulated-list-put-tag "" t))
(defun govc-tabulated-list-toggle-marks ()
"Toggle mark."
(interactive)
(save-excursion
(goto-char (point-min))
(let ((cmd))
(while (not (eobp))
(setq cmd (char-after))
(tabulated-list-put-tag
(if (eq cmd dired-marker-char)
""
(char-to-string dired-marker-char)) t)))))
(defun govc-tabulated-list-unmark-all ()
"Unmark all."
(interactive)
(save-excursion
(goto-char (point-min))
(while (not (eobp))
(tabulated-list-put-tag "" t))))
(defun govc-selection ()
"Get the current selection as a list of names."
(let ((selection))
(save-excursion
(goto-char (point-min))
(while (not (eobp))
(when (eq (char-after) ?*)
(add-to-list 'selection (tabulated-list-get-id)))
(forward-line)))
(or selection (let ((id (tabulated-list-get-id)))
(if id
(list id))))))
(defun govc-do-selection (fn action)
"Call FN with `govc-selection' confirming ACTION."
(let* ((selection (govc-selection))
(count (length selection))
(prompt (if (= count 1)
(car selection)
(format "* [%d] marked" count))))
(if (yes-or-no-p (format "%s %s ?" action prompt))
(funcall fn selection))))
(defun govc-copy-selection ()
"Copy current selection or region to the kill ring."
(interactive)
(if (region-active-p)
(copy-region-as-kill (mark) (point) 'region)
(kill-new (message "%s" (s-join " " (--map (format "\"%s\"" it) (govc-selection)))))))
(defvar govc-font-lock-keywords
`((,(let ((host-expression "\\b[-a-z0-9]+\\b")) ;; Hostname
(concat
(mapconcat 'identity (make-list 3 host-expression) "\\.")
"\\(\\." host-expression "\\)*")) .
(0 font-lock-variable-name-face))
(,(mapconcat 'identity (make-list 4 "[0-9]+") "\\.") ;; IP address
. (0 font-lock-variable-name-face))
("\"[^\"]*\"" . (0 font-lock-string-face))
("'[^']*'" . (0 font-lock-string-face))
("[.0-9]+%" . (0 font-lock-type-face))
("\\<\\(success\\|poweredOn\\)\\>" . (1 font-lock-doc-face))
("\\<\\(error\\|poweredOff\\)\\>" . (1 font-lock-warning-face))
("\\<\\(running\\|info\\)\\>" . (1 font-lock-variable-name-face))
("\\<\\(warning\\|suspended\\)\\>" . (1 font-lock-keyword-face))
("\\<\\(verbose\\|trivia\\)\\>" . (1 whitespace-line))
(,dired-re-maybe-mark . (0 dired-mark-face))
("types.ManagedObjectReference\\(.*\\)" . (1 dired-directory-face))
("[^ ]*/$" . (0 dired-directory-face))
("\\.\\.\\.$" . (0 dired-symlink-face))
("^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][A-Z][0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9][A-Z]|" . (0 font-lock-comment-face))
("^\\([ A-Za-z0-9_]+: \\).*" . (1 font-lock-comment-face))
("<[^>]*>" . (0 font-lock-comment-face))
("\\[[^]]*\\]" . (0 font-lock-comment-face))
("([^)]*)" . (0 font-lock-comment-face))))
(defvar govc-tabulated-list-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "m" 'govc-tabulated-list-mark)
(define-key map "u" 'govc-tabulated-list-unmark)
(define-key map "t" 'govc-tabulated-list-toggle-marks)
(define-key map "U" 'govc-tabulated-list-unmark-all)
(define-key map (kbd "M-&") 'govc-shell-command)
(define-key map (kbd "M-w") 'govc-copy-selection)
(define-key map (kbd "M-E") 'govc-copy-environment)
map)
"Keymap for `govc-tabulated-list-mode'.")
(define-derived-mode govc-tabulated-list-mode tabulated-list-mode "Tabulated govc"
"Generic table bindings to mark/unmark rows."
(setq-local font-lock-defaults
'(govc-font-lock-keywords t nil nil beginning-of-line)))
;;; Keymap helpers for generating menus and popups
(defun govc-keymap-list (keymap)
"Return a list of (key name function) for govc bindings in the given KEYMAP.
The name returned is the first word of the function `documentation'."
(let ((map))
(map-keymap
(lambda (k f)
(when (keymapp f)
(setq map (append map
(--map (and (setcar it (kbd (format "M-%s" (char-to-string (car it))))) it)
(govc-keymap-list f)))))
(when (and (symbolp f)
(s-starts-with? "govc-" (symbol-name f)))
(if (not (eq ?? k))
(add-to-list 'map (list k (car (split-string (documentation f))) f))))) keymap)
map))
(defun govc-keymap-menu (keymap)
"Return a list of [key function t] for govc bindings in the given KEYMAP.
For use with `easy-menu-define'."
(-map (lambda (item)
(vector (nth 1 item) (nth 2 item) t))
(govc-keymap-list keymap)))
(defun govc-key-description (key)
"Call `key-description' ensuring KEY is a sequence."
(key-description (if (integerp key) (list key) key)))
(defun govc-keymap-list-to-help (keymap)
"Convert KEYMAP to list of help text."
(--map (list (govc-key-description (car it))
(car (split-string (documentation (nth 2 it)) "\\.")))
keymap))
(defun govc-keymap-popup-help ()
"Default keymap help for `govc-keymap-popup'."
(append (govc-keymap-list-to-help (govc-keymap-list govc-tabulated-list-mode-map))
'(("g" "Refresh current buffer")
("C-h m" "Show all key bindings"))))
(defun govc-keymap-popup (keymap)
"Convert a `govc-keymap-list' using KEYMAP for use with `magit-define-popup'.
Keys in the ASCII range of 32-97 are mapped to popup commands, all others are listed as help text."
(let* ((maps (--separate (and (integerp (car it))
(>= (car it) 32)
(<= (car it) 97))
(govc-keymap-list keymap)))
(help (govc-keymap-list-to-help (cadr maps))))
(append
'("Commands")
(car maps)
(list (s-join "\n" (--map (format " %-6s %s" (car it) (cadr it))
(append help (govc-keymap-popup-help))))
nil))))
;;; govc process helpers
(defcustom govc-urls nil
"List of URLs for use with `govc-session'.
The `govc-session-name' displayed by `govc-mode-line' uses `url-target' (anchor)
if set, otherwise `url-host' is used.
Example:
```
(setq govc-urls '(\"root:vagrant@localhost:18443#Vagrant-ESXi\"
\"root:[email protected]#Intel-NUC\"
\"[email protected]:password!@vcva-clovervm\"))
```
To enter a URL that is not in the list, prefix `universal-argument', for example:
`\\[universal-argument] \\[govc-vm]'
To avoid putting your credentials in a variable, you can use the
auth-source search integration.
```
(setq govc-urls '(\"myserver-vmware-2\"))
```
And then put this line in your `auth-sources' (e.g. `~/.authinfo.gpg'):
```
machine myserver-vmware-2 login tzz password mypass url \"myserver-vmware-2.some.domain.here:443?insecure=true\"
```
Which will result in the URL \"tzz:[email protected]:443?insecure=true\".
For more details on `auth-sources', see Info node `(auth) Help for users'.
When in `govc-vm' or `govc-host' mode, a default URL is composed with the
current session credentials and the IP address of the current vm/host and
the vm/host name as the session name. This makes it easier to connect to
nested ESX/vCenter VMs or directly to an ESX host."
:group 'govc
:type '(repeat (string :tag "vcenter URL or auth-source machine reference")))
(defvar-local govc-session-url nil
"ESX or vCenter URL set by `govc-session' via `govc-urls' selection.")
(defvar-local govc-session-path nil)
(defvar-local govc-session-insecure nil
"Skip verification of server certificate when true.
This variable is set to the value of the `GOVC_INSECURE' env var by default.
It can also be set per-url via the query string (insecure=true). For example:
```
(setq govc-urls '(\"root:password@hostname?insecure=true\"))
```")
(defvar-local govc-session-datacenter nil
"Datacenter to use for the current `govc-session'.
If the endpoint has a single Datacenter it will be used by default, otherwise
`govc-session' will prompt for selection. It can also be set per-url via the
query string. For example:
```
(setq govc-urls '(\"root:password@hostname?datacenter=dc1\"))
```")
(defvar-local govc-session-datastore nil
"Datastore to use for the current `govc-session'.
If the endpoint has a single Datastore it will be used by default, otherwise
`govc-session' will prompt for selection. It can also be set per-url via the
query string. For example:
```
(setq govc-urls '(\"root:password@hostname?datastore=vsanDatastore\"))
```")
(defvar-local govc-session-network nil
"Network to use for the current `govc-session'.")
(defvar-local govc-filter nil
"Resource path filter.")
(defvar-local govc-args nil
"Additional govc arguments.")
(defun govc-session-name ()
"Return a name for the current session.
Derived from `govc-session-url' if set, otherwise from the 'GOVC_URL' env var.
Return value is the url anchor if set, otherwise the hostname is returned."
(let* ((u (or govc-session-url (getenv "GOVC_URL")))
(url (if u (govc-url-parse u))))
(if url
(concat (or (url-target url) (url-host url)) govc-session-path))))
(defun govc-format-command (command &rest args)
"Format govc COMMAND ARGS."
(format "%s %s %s" govc-command command
(s-join " " (--map (format "\"%s\"" it)
(-flatten (-non-nil args))))))
(defconst govc-environment-map (--map (cons (concat "GOVC_" (upcase it))
(intern (concat "govc-session-" it)))
'("url" "insecure" "datacenter" "datastore" "network"))
"Map of `GOVC_*' environment variable names to `govc-session-*' symbol names.")
(defun govc-environment (&optional unset)
"Return `process-environment' for govc.
Optionally clear govc env if UNSET is non-nil."
(let ((process-environment (copy-sequence process-environment)))
(dolist (e govc-environment-map)
(setenv (car e) (unless unset (symbol-value (cdr e)))))
process-environment))
(defun govc-export-environment (arg)
"Set if ARG is \\[universal-argument], unset if ARG is \\[negative-argument]."
(if (equal arg '-)
(progn (setq process-environment (govc-environment t))
(cons "unset" (--map (car it)
govc-environment-map)))
(progn (setq process-environment (govc-environment))
(cons "export" (--map (format "%s='%s'" (car it) (or (symbol-value (cdr it)) ""))
govc-environment-map)))))
(defun govc-copy-environment (&optional arg)
"Export session to `process-environment' and `kill-ring'.
Optionally set `GOVC_*' vars in `process-environment' using prefix
\\[universal-argument] ARG or unset with prefix \\[negative-argument] ARG."
(interactive "P")
(message (kill-new (if arg (s-join " " (govc-export-environment arg)) govc-session-url))))
(defun govc-process (command handler)
"Run COMMAND, calling HANDLER upon successful exit of the process."
(message "%s" command)
(let ((process-environment (govc-environment))
(exit-code))
(add-to-list 'govc-command-history command)
(with-temp-buffer
(setq exit-code (call-process-shell-command command nil (current-buffer)))
(if (zerop exit-code)
(funcall handler)
(error (buffer-string))))))
(defun govc (command &rest args)
"Execute govc COMMAND with ARGS.
Return value is `buffer-string' split on newlines."
(govc-process (govc-format-command command args)
(lambda ()
(split-string (buffer-string) "\n" t))))
(defun govc-json (command &rest args)
"Execute govc COMMAND passing arguments ARGS.
Return value is `json-read'."
(govc-process (govc-format-command command (cons "-json" args))
(lambda ()
(goto-char (point-min))
(let ((json-object-type 'plist))
(json-read)))))
(defun govc-ls-datacenter ()
"List datacenters."
(govc "ls" "-t" "Datacenter" "./..."))
(defun govc-object-prompt (prompt ls)
"PROMPT for object name via LS function. Return object without PROMPT if there is just one instance."
(let ((objs (if (listp ls) ls (funcall ls))))
(if (eq 1 (length objs))
(car objs)
(completing-read prompt objs))))
(defun govc-url-parse (url)
"A `url-generic-parse-url' wrapper to handle URL with password, but no scheme.
Also fixes the case where user contains an '@'."
(let* ((full (s-contains? "://" url))
(u (url-generic-parse-url (concat (unless full "https://") url))))
(unless full
(setf (url-type u) nil)
(setf (url-fullness u) nil))
(if (s-contains? "@" (url-host u))
(let* ((h (split-string (url-host u) "@"))
(p (split-string (car h) ":")))
(setf (url-host u) (cadr h))
(setf (url-user u) (concat (url-user u) "@" (car p)))
(setf (url-password u) (cadr p))))
u))
(defun govc-url-default ()
"Default URL when creating a new session."
(if govc-session-url
(let ((url (govc-url-parse govc-session-url)))
(if (equal major-mode 'govc-host-mode)
(progn (setf (url-host url) (govc-table-column-value "Name"))
(setf (url-target url) nil))
(progn (setf (url-host url) (govc-table-column-value "IP address"))
(setf (url-target url) (govc-table-column-value "Name"))
;; default url-user to Administrator@$domain when connecting to a vCenter VM
(let ((sts (ignore-errors (govc "sso.service.ls" "-t" "cs.identity" "-P" "wsTrust" "-U" "-u" (url-host url)))))
(if sts (setf (url-user url) (concat "Administrator@" (file-name-nondirectory (car sts))))))))
(setf (url-filename url) "") ; erase query string
(if (string-empty-p (url-user url))
(setf (url-user url) "root")) ; local workstation url has no user set
(url-recreate-url url))))
(defun govc-urls-completing-read ()
"A wrapper for `completing-read' to mask credentials in `govc-urls'."
(let ((alist))
(dolist (ent govc-urls)
(let ((u (govc-url-parse ent)))
(setf (url-password u) nil)
(add-to-list 'alist `(,(url-recreate-url u) . ,ent) t)))
(let ((u (completing-read "govc url: " (-map 'car alist))))
(cdr (assoc u alist)))))
(defun govc-session-url-lookup-auth-source (url-or-address)
"Check if URL-OR-ADDRESS is a logical name in the authinfo file.
Given URL-OR-ADDRESS `myserver-vmware-2' this function will find
a line like
machine myserver-vmware-2 login tzz password mypass url \"myserver-vmware-2.some.domain.here:443?insecure=true\"
and will return the URL \"tzz:[email protected]:443?insecure=true\".
If the line is not found, the original URL-OR-ADDRESS is
returned, assuming that's what the user wanted."
(let ((found (nth 0 (auth-source-search :max 1
:host url-or-address
:require '(:user :secret :url)
:create nil))))
(if found
(format "%s:%s@%s"
(plist-get found :user)
(let ((secret (plist-get found :secret)))
(if (functionp secret)
(funcall secret)
secret))
(plist-get found :url))
url-or-address)))
(defun govc-session-set-url (url)
"Set `govc-session-url' to URL and optionally set other govc-session-* variables via URL query."
;; Replace the original URL with the auth-source lookup if there is no user.
(unless (url-user (govc-url-parse url))
(setq url (govc-session-url-lookup-auth-source url)))
(let ((q (cdr (url-path-and-query (govc-url-parse url)))))
(dolist (opt (if q (url-parse-query-string q)))
(let ((var (intern (concat "govc-session-" (car opt)))))
(if (boundp var)
(set var (cadr opt))))))
(setq govc-session-url url))
(defun govc-session ()
"Initialize a govc session."
(interactive)
(let ((url (if (or current-prefix-arg (eq 0 (length govc-urls)))
(read-string "govc url: " (govc-url-default))
(if (eq 1 (length govc-urls))
(car govc-urls)
(govc-urls-completing-read)))))
;; Wait until this point to clear so current session is preserved in the
;; event of `keyboard-quit' in `read-string'.
(setq govc-session-datacenter nil
govc-session-datastore nil
govc-session-network nil
govc-filter nil)
(govc-session-set-url url))
(unless govc-session-insecure
(setq govc-session-insecure (or (getenv "GOVC_INSECURE")
(completing-read "govc insecure: " '("true" "false")))))
(unless govc-session-datacenter
(setq govc-session-datacenter (govc-object-prompt "govc datacenter: " 'govc-ls-datacenter)))
(add-to-list 'govc-urls govc-session-url))
(defalias 'govc-current-session 'buffer-local-variables)
(defun govc-session-clone (session)
"Clone a session from SESSION buffer locals."
(dolist (v session)
(let ((s (car v)))
(when (s-starts-with? "govc-session-" (symbol-name s))
(set s (assoc-default s session))))))
(defvar govc-command-history nil
"History list for govc commands used by `govc-shell-command'.")
(defvar govc-shell--revert-cmd nil)
(defun govc-shell--revert-function (&optional _ _)
"Re-run the buffer's most recent govc-shell-run command."
(apply (car govc-shell--revert-cmd) (cdr govc-shell--revert-cmd)))
(defun govc-shell-filter (proc string)
"Process filter for govc-shell PROC, append STRING."
(when (buffer-live-p (process-buffer proc))
(with-current-buffer (process-buffer proc)
(let ((moving (= (point) (process-mark proc))))
(save-excursion
(let ((inhibit-read-only t))
(goto-char (process-mark proc))
(insert string)
(set-marker (process-mark proc) (point))))
(display-buffer (process-buffer proc))
(if moving
(with-selected-window (get-buffer-window (current-buffer))
(goto-char (point-max))))))))
(defun govc-shell-run (name args buffer)
"Run NAME command with ARGS in BUFFER."
(with-current-buffer (if (stringp buffer) (get-buffer-create buffer) buffer)
(let ((proc (get-buffer-process (current-buffer)))
(process-environment (govc-environment))
(session (govc-current-session))
(inhibit-read-only t))
(when proc
(set-process-filter proc nil)
(delete-process proc))
(erase-buffer)
(if (--any? (member (file-name-extension it) '("vmx" "vmdk")) args)
(conf-mode)
(govc-shell-mode))
(govc-session-clone session)
(setq-local govc-shell--revert-cmd `(govc-shell-run ,name ,args ,(current-buffer)))
(setq mode-line-process '(:propertize ":run" face compilation-mode-line-run))
(setq proc (apply 'start-process name (current-buffer) name args))
(set-process-sentinel proc 'govc-shell-process-sentinel)
(set-process-filter proc 'govc-shell-filter))))
(defun govc-shell-kill ()
"Kill the process started by \\[govc-shell-command]."
(interactive)
(let ((buffer (current-buffer)))
(if (get-buffer-process buffer)
(interrupt-process (get-buffer-process buffer))
(error "The %s process is not running" (downcase mode-name)))))
(defun govc-shell-process-sentinel (process event)
"Process sentinel used by `govc-shell-run'. When PROCESS exits EVENT is logged."
(when (memq (process-status process) '(exit signal))
(with-current-buffer (process-buffer process)
(setq mode-line-process nil)
(message "%s %s" (process-name process) (substring event 0 -1)))))
(defvar govc-shell-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-c C-k") 'govc-shell-kill)
map))
(define-derived-mode govc-shell-mode special-mode "govc-shell"
"Mode for running govc commands."
(setq-local font-lock-defaults '(govc-font-lock-keywords))
(setq-local revert-buffer-function #'govc-shell--revert-function))
(defun govc-shell-command (&optional cmd buffer)
"Shell CMD in BUFFER with current `govc-session' exported as GOVC_ env vars."
(interactive)
(let* ((session (govc-current-session))
(args (if cmd (--map (format "%s" it) (-flatten (-non-nil (list govc-command cmd))))
(split-string-and-unquote (read-shell-command "command: " nil 'govc-command-history)))))
(with-current-buffer (get-buffer-create (or buffer "*govc*"))
(govc-session-clone session)
(govc-shell-run (car args) (cdr args) (current-buffer)))))
(defcustom govc-max-events 100
"Limit events output to the last N events."
:type 'integer
:group 'govc)
(defun govc-events ()
"Events via govc events -n `govc-max-events'."
(interactive)
(govc-shell-command
(list "events" "-l" "-n" govc-max-events (if current-prefix-arg "-f") (govc-selection)) "*govc-event*"))
(defun govc-tasks ()
"Tasks via govc tasks."
(interactive)
(govc-shell-command
(list "tasks" "-l" "-n" govc-max-events (if current-prefix-arg "-f") (govc-selection)) "*govc-task*"))
(defun govc-logs ()
"Logs via govc logs -n `govc-max-events'."
(interactive)
(govc-shell-command
(let ((host (govc-selection)))
(list "logs" "-n" govc-max-events (if current-prefix-arg "-f") (if host (list "-host" host)))) "*govc-log*"))
(defun govc-parse-info (output)
"Parse govc info command OUTPUT."
(let* ((entries)
(entry)
(entry-key))
(-each output
(lambda (line)
(let* ((ix (s-index-of ":" line))
(key (s-trim (substring line 0 ix)))
(val (s-trim (substring line (+ ix 1)))))
(unless entry-key
(setq entry-key key))
(when (s-equals? key entry-key)
(setq entry (make-hash-table :test 'equal))
(add-to-list 'entries entry))
(puthash key val entry))))
entries))
(defun govc-table-column-names ()
"Return a list of column names from `tabulated-list-format'."
(--map (car (aref tabulated-list-format it))
(number-sequence 0 (- (length tabulated-list-format) 1))))
(defun govc-table-column-value (key)
"Return current column value for given KEY."
(let ((names (govc-table-column-names))
(entry (tabulated-list-get-entry))
(value))
(dotimes (ix (- (length names) 1))
(if (s-equals? key (nth ix names))
(setq value (elt entry ix))))
value))
(defun govc-table-info (command &optional args)
"Convert `govc-parse-info' COMMAND ARGS output to `tabulated-list-entries' format."
(let ((names (govc-table-column-names)))
(-map (lambda (info)
(let ((id (or (gethash "Path" info)
(gethash (car names) info))))
(list id (vconcat
(--map (or (gethash it info) "-")
names)))))
(govc-parse-info (govc command args)))))
(defun govc-map-info (command &optional args)
"Populate key=val map table with govc COMMAND ARGS output."
(-map (lambda (line)
(let* ((ix (s-index-of ":" line))
(key (s-trim (substring line 0 ix)))
(val (s-trim (substring line (+ ix 1)))))
(list key (vector key val))))
(govc command args)))
(defun govc-map-info-table (entries)
"Tabulated `govc-map-info' data via ENTRIES."
(let ((session (govc-current-session))
(args (append govc-args (govc-selection)))
(buffer (get-buffer-create "*govc-info*")))
(pop-to-buffer buffer)
(tabulated-list-mode)
(setq govc-args args)
(govc-session-clone session)
(setq tabulated-list-format [("Name" 50)
("Value" 50)]
tabulated-list-padding 2
tabulated-list-entries entries)
(tabulated-list-print)))
(defun govc-type-list-entries (command)
"Convert govc COMMAND type table output to `tabulated-list-entries'."
(-map (lambda (line)
(let* ((entry (s-split-up-to " " (s-collapse-whitespace line) 2))
(name (car entry))
(type (nth 1 entry))
(value (car (last entry))))
(list name (vector name type value))))
(govc command govc-args)))
(defun govc-json-info-selection (command)
"Run govc COMMAND -json on `govc-selection'."
(if current-prefix-arg
(--each (govc-selection) (govc-json-info command it))
(govc-json-info command (govc-selection))))
(defun govc-json-diff ()
"Diff two *govc-json* buffers in view."
(let ((buffers))
(-each (window-list-1)
(lambda (w)
(with-current-buffer (window-buffer w)
(if (and (eq major-mode 'json-mode)
(s-starts-with? "*govc-json*" (buffer-name)))
(push (current-buffer) buffers)))) )
(if (= (length buffers) 2)
(pop-to-buffer
(diff-no-select (car buffers) (cadr buffers))))))
(defun govc-json-info (command selection)
"Run govc COMMAND -json on SELECTION."
(govc-process (govc-format-command command "-json" govc-args selection)
(lambda ()
(let ((buffer (get-buffer-create (concat "*govc-json*" (if current-prefix-arg selection)))))
(copy-to-buffer buffer (point-min) (point-max))
(with-current-buffer buffer
(json-mode)
(json-pretty-print-buffer))
(display-buffer buffer))))
(if current-prefix-arg
(govc-json-diff)))
(defun govc-mode-new-session ()
"Connect new session for the current govc mode."
(interactive)
(call-interactively 'govc-session)
(revert-buffer))
(defun govc-host-with-session ()
"Host-mode with current session."
(interactive)
(govc-host nil (govc-current-session)))
(defun govc-vm-with-session ()
"VM-mode with current session."
(interactive)
(govc-vm nil (govc-current-session)))
(defun govc-datastore-with-session ()
"Datastore-mode with current session."
(interactive)
(govc-datastore nil (govc-current-session)))
(defun govc-pool-with-session ()
"Pool-mode with current session."
(interactive)
(govc-pool nil (govc-current-session)))
;;; govc object mode
(defvar-local govc-object-history '("-")
"History list of visited objects.")
(defun govc-object-collect ()
"Wrapper for govc object.collect."
(interactive)
(let ((id (car govc-args)))
(add-to-list 'govc-object-history id)
(setq govc-session-path id))
(govc-type-list-entries "object.collect"))
(defun govc-object-collect-selection (&optional json)
"Expand object selection via govc object.collect.
Optionally specify JSON encoding."
(interactive)
(let* ((entry (or (tabulated-list-get-entry) (error "No entry")))
(name (elt entry 0))
(type (elt entry 1))
(val (elt entry 2)))
(setq govc-args (list (car govc-args) name))
(cond
((s-blank? val))
((and (not json) (s-ends-with? "types.ManagedObjectReference" type))
(let ((ids (govc "ls" "-L" (split-string val ","))))
(setq govc-args (list (govc-object-prompt "moid: " ids)))))
((string= val "...")
(if (s-starts-with? "[]" type) (setq json t))))
(if json
(govc-json-info "object.collect" nil)
(tabulated-list-revert))))
(defun govc-object-collect-selection-json ()
"JSON object selection via govc object.collect."
(interactive)
(govc-object-collect-selection t))
(defun govc-object-next ()
"Next managed object reference."
(interactive)
(if (search-forward "types.ManagedObjectReference" nil t)
(progn (govc-tabulated-list-unmark-all)
(tabulated-list-put-tag (char-to-string dired-marker-char)))
(goto-char (point-min))))
(defun govc-object-collect-parent ()
"Parent object selection if reachable, otherwise prompt with `govc-object-history'."
(interactive)
(if (cadr govc-args)
(let ((prop (butlast (split-string (cadr govc-args) "\\."))))
(setq govc-args (list (car govc-args) (if prop (s-join "." prop)))))
(save-excursion
(goto-char (point-min))
(if (re-search-forward "^[[:space:]]*parent" nil t)
(govc-object-collect-selection)
(let ((id (govc-object-prompt "moid: " govc-object-history)))
(setq govc-args (list id (if (string= id "-") "content")))))))
(tabulated-list-revert))
(defun govc-object (&optional moid property session)
"Object browser aka MOB (Managed Object Browser).
Optionally starting at MOID and PROPERTY if given.
Inherit SESSION if given."
(interactive)
(let ((buffer (get-buffer-create "*govc-object*")))
(if (called-interactively-p 'interactive)
(switch-to-buffer buffer)
(pop-to-buffer buffer))
(govc-object-mode)
(if session
(govc-session-clone session)
(call-interactively 'govc-session))
(setq govc-args (list (or moid "-") property))
(tabulated-list-print)))
(defun govc-object-info ()
"Object browser via govc object.collect on `govc-selection'."
(interactive)
(if (equal major-mode 'govc-object-mode)
(progn
(setq govc-args (list (govc-object-prompt "moid: " govc-object-history)))
(tabulated-list-revert))
(govc-object (tabulated-list-get-id) nil (govc-current-session))))
(defvar govc-object-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "J" 'govc-object-collect-selection-json)
(define-key map "N" 'govc-object-next)
(define-key map "O" 'govc-object-info)
(define-key map (kbd "DEL") 'govc-object-collect-parent)
(define-key map (kbd "RET") 'govc-object-collect-selection)
(define-key map "?" 'govc-object-popup)
map)
"Keymap for `govc-object-mode'.")
(define-derived-mode govc-object-mode govc-tabulated-list-mode "Object"
"Major mode for handling a govc object."
(setq tabulated-list-format [("Name" 40 t)
("Type" 40 t)
("Value" 40 t)]
tabulated-list-padding 2
tabulated-list-entries #'govc-object-collect)
(tabulated-list-init-header))
(magit-define-popup govc-object-popup
"Object popup."
:actions (govc-keymap-popup govc-object-mode-map))
;;; govc metric mode
(defun govc-metric-sample ()
"Sample metrics."
(interactive)
(govc-shell-command (list "metric.sample" govc-args govc-filter (govc-selection))))
(defun govc-metric-sample-plot ()
"Plot metric sample."
(interactive)
(let* ((type (if (and (display-images-p) (not (eq current-prefix-arg '-))) 'png 'dumb))
(max (if (member "-i" govc-args) "60" "180"))
(args (append govc-args (list "-n" max "-plot" type govc-filter)))
(session (govc-current-session))
(metrics (govc-selection))
(inhibit-read-only t))
(with-current-buffer (get-buffer-create "*govc*")
(govc-session-clone session)
(erase-buffer)
(delete-other-windows)
(if (eq type 'dumb)
(split-window-right)
(split-window-below))
(display-buffer-use-some-window (current-buffer) '((inhibit-same-window . t)))
(--each metrics
(let* ((cmd (govc-format-command "metric.sample" args it))
(data (govc-process cmd 'buffer-string)))
(if (eq type 'dumb)
(insert data)
(insert-image (create-image (string-as-unibyte data) type t))))))))
(defun govc-metric-select (metrics)
"Select metric names. METRICS is a regexp."
(interactive (list (read-regexp "Select metrics" (regexp-quote ".usage."))))
(save-excursion
(goto-char (point-min))
(while (not (eobp))
(if (string-match-p metrics (tabulated-list-get-id))
(govc-tabulated-list-mark)
(govc-tabulated-list-unmark)))))
(defun govc-metric-info ()
"Wrapper for govc metric.info."
(govc-table-info "metric.info" (list govc-args (car govc-filter))))
(defvar govc-metric-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "RET") 'govc-metric-sample)
(define-key map (kbd "P") 'govc-metric-sample-plot)
(define-key map (kbd "s") 'govc-metric-select)
map)
"Keymap for `govc-metric-mode'.")
(defun govc-metric ()
"Metrics info."
(interactive)
(let ((session (govc-current-session))
(filter (or (govc-selection) (list govc-session-path)))
(buffer (get-buffer-create "*govc-metric*")))
(pop-to-buffer buffer)
(govc-metric-mode)
(govc-session-clone session)
(if current-prefix-arg (setq govc-args '("-i" "300")))
(setq govc-filter filter)
(tabulated-list-print)))
(define-derived-mode govc-metric-mode govc-tabulated-list-mode "Metric"
"Major mode for handling a govc metric."
(setq tabulated-list-format [("Name" 35 t)
("Group" 15 t)
("Unit" 4 t)
("Level" 5 t)
("Summary" 50)]
tabulated-list-sort-key (cons "Name" nil)
tabulated-list-padding 2
tabulated-list-entries #'govc-metric-info)
(tabulated-list-init-header))
;;; govc host mode
(defun govc-ls-host ()
"List hosts."
(govc "ls" "-t" "HostSystem" "./..."))
(defun govc-esxcli-netstat-info ()
"Wrapper for govc host.esxcli network ip connection list."
(govc-table-info "host.esxcli"
(append govc-args '("-hints=false" "--" "network" "ip" "connection" "list"))))
(defun govc-esxcli-netstat (host)
"Tabulated `govc-esxcli-netstat-info' HOST."
(interactive (list (govc-object-prompt "Host: " 'govc-ls-host)))
(let ((session (govc-current-session))
(buffer (get-buffer-create "*govc-esxcli*")))
(pop-to-buffer buffer)
(tabulated-list-mode)
(setq govc-args (list "-host" host))
(govc-session-clone session)
(setq tabulated-list-format [("CCAlgo" 10 t)
("ForeignAddress" 20 t)
("LocalAddress" 20 t)
("Proto" 5 t)
("RecvQ" 5 t)
("SendQ" 5 t)
("State" 15 t)
("WorldID" 7 t)
("WorldName" 10 t)]
tabulated-list-padding 2
tabulated-list-entries #'govc-esxcli-netstat-info)
(tabulated-list-init-header)
(tabulated-list-print)))