forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
observe.go
1055 lines (914 loc) · 31.2 KB
/
observe.go
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
package observe
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"text/template"
"time"
"github.com/golang/glog"
"github.com/prometheus/client_golang/prometheus"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/apiserver/pkg/server/healthz"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/jsonpath"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions/resource"
"github.com/openshift/origin/pkg/util/proc"
)
var (
observeCounts = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "observe_counts",
Help: "Number of changes observed to the underlying resource.",
},
[]string{"type"},
)
execDurations = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "observe_exec_durations_milliseconds",
Help: "Item execution latency distributions.",
},
[]string{"type", "exit_code"},
)
nameExecDurations = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "observe_name_exec_durations_milliseconds",
Help: "Name list execution latency distributions.",
},
[]string{"exit_code"},
)
)
var (
observeLong = templates.LongDesc(`
Observe changes to resources and take action on them
This command assists in building scripted reactions to changes that occur in
Kubernetes or OpenShift resources. This is frequently referred to as a
'controller' in Kubernetes and acts to ensure particular conditions are
maintained. On startup, observe will list all of the resources of a
particular type and execute the provided script on each one. Observe watches
the server for changes, and will reexecute the script for each update.
Observe works best for problems of the form "for every resource X, make sure
Y is true". Some examples of ways observe can be used include:
* Ensure every namespace has a quota or limit range object
* Ensure every service is registered in DNS by making calls to a DNS API
* Send an email alert whenever a node reports 'NotReady'
* Watch for the 'FailedScheduling' event and write an IRC message
* Dynamically provision persistent volumes when a new PVC is created
* Delete pods that have reached successful completion after a period of time.
The simplest pattern is maintaining an invariant on an object - for instance,
"every namespace should have an annotation that indicates its owner". If the
object is deleted no reaction is necessary. A variation on that pattern is
creating another object: "every namespace should have a quota object based
on the resources allowed for an owner".
$ cat set_owner.sh
#!/bin/sh
if [[ "$(%[1]s get namespace "$1" --template='{{ .metadata.annotations.owner }}')" == "" ]]; then
%[1]s annotate namespace "$1" owner=bob
fi
$ %[1]s observe namespaces -- ./set_owner.sh
The set_owner.sh script is invoked with a single argument (the namespace name)
for each namespace. This simple script ensures that any user without the
"owner" annotation gets one set, but preserves any existing value.
The next common of controller pattern is provisioning - making changes in an
external system to match the state of a Kubernetes resource. These scripts need
to account for deletions that may take place while the observe command is not
running. You can provide the list of known objects via the --names command,
which should return a newline-delimited list of names or namespace/name pairs.
Your command will be invoked whenever observe checks the latest state on the
server - any resources returned by --names that are not found on the server
will be passed to your --delete command.
For example, you may wish to ensure that every node that is added to Kubernetes
is added to your cluster inventory along with its IP:
$ cat add_to_inventory.sh
#!/bin/sh
echo "$1 $2" >> inventory
sort -u inventory -o inventory
$ cat remove_from_inventory.sh
#!/bin/sh
grep -vE "^$1 " inventory > /tmp/newinventory
mv -f /tmp/newinventory inventory
$ cat known_nodes.sh
#!/bin/sh
touch inventory
cut -f 1-1 -d ' ' inventory
$ %[1]s observe nodes -a '{ .status.addresses[0].address }' \
--names ./known_nodes.sh \
--delete ./remove_from_inventory.sh \
-- ./add_to_inventory.sh
If you stop the observe command and then delete a node, when you launch observe
again the contents of inventory will be compared to the list of nodes from the
server, and any node in the inventory file that no longer exists will trigger
a call to remove_from_inventory.sh with the name of the node.
Important: when handling deletes, the previous state of the object may not be
available and only the name/namespace of the object will be passed to your
--delete command as arguments (all custom arguments are omitted).
More complicated interactions build on the two examples above - your inventory
script could make a call to allocate storage on your infrastructure as a
service, or register node names in DNS, or set complex firewalls. The more
complex your integration, the more important it is to record enough data in the
remote system that you can identify when resources on either side are deleted.`)
observeExample = templates.Examples(`
# Observe changes to services
%[1]s observe services
# Observe changes to services, including the clusterIP and invoke a script for each
%[1]s observe services -a '{ .spec.clusterIP }' -- register_dns.sh`)
)
type ObserveOptions struct {
debugOut io.Writer
noHeaders bool
client resource.RESTClient
mapping *meta.RESTMapping
includeNamespace bool
// which resources to select
namespace string
allNamespaces bool
// additional debugging information
listenAddr string
// actions to take on each object
eachCommand []string
objectEnvVar string
typeEnvVar string
deleteCommand stringSliceFlag
// controls whether deletes are included
nameSyncCommand stringSliceFlag
// error handling logic
observedErrors int
maximumErrors int
retryCount int
retryExitStatus int
// when to exit or reprocess the list of items
once bool
exitAfterPeriod time.Duration
resyncPeriod time.Duration
printMetricsOnExit bool
// control the output of the command
templateType string
templates stringSliceFlag
printer ColumnPrinter
strictTemplates bool
argumentStore *objectArgumentsStore
// knownObjects is nil if we do not need to track deletions
knownObjects knownObjects
genericclioptions.IOStreams
}
func NewObserveOptions(streams genericclioptions.IOStreams) *ObserveOptions {
return &ObserveOptions{
IOStreams: streams,
retryCount: 2,
templateType: "jsonpath",
maximumErrors: 20,
listenAddr: ":11251",
}
}
// NewCmdObserve creates the observe command.
func NewCmdObserve(fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := NewObserveOptions(streams)
cmd := &cobra.Command{
Use: "observe RESOURCE [-- COMMAND ...]",
Short: "Observe changes to resources and react to them (experimental)",
Long: fmt.Sprintf(observeLong, fullName),
Example: fmt.Sprintf(observeExample, fullName),
Run: func(cmd *cobra.Command, args []string) {
if err := o.Complete(f, cmd, args); err != nil {
cmdutil.CheckErr(err)
}
if err := o.Validate(args); err != nil {
cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, err.Error()))
}
if err := o.Run(); err != nil {
cmdutil.CheckErr(err)
}
},
}
// flags controlling what to select
cmd.Flags().BoolVar(&o.allNamespaces, "all-namespaces", false, "If true, list the requested object(s) across all projects. Project in current context is ignored.")
// to perform deletion synchronization
cmd.Flags().VarP(&o.deleteCommand, "delete", "d", "A command to run when resources are deleted. Specify multiple times to add arguments.")
cmd.Flags().Var(&o.nameSyncCommand, "names", "A command that will list all of the currently known names, optional. Specify multiple times to add arguments. Use to get notifications when objects are deleted.")
// add additional arguments / info to the server
cmd.Flags().StringVar(&o.templateType, "output", o.templateType, "Controls the template type used for the --argument flags. Supported values are gotemplate and jsonpath.")
cmd.Flags().BoolVar(&o.strictTemplates, "strict-templates", false, "If true return an error on any field or map key that is not missing in a template.")
cmd.Flags().VarP(&o.templates, "argument", "a", "Template for the arguments to be passed to each command in the format defined by --output.")
cmd.Flags().StringVar(&o.typeEnvVar, "type-env-var", "", "The name of an env var to set with the type of event received ('Sync', 'Updated', 'Deleted', 'Added') to the reaction command or --delete.")
cmd.Flags().StringVar(&o.objectEnvVar, "object-env-var", "", "The name of an env var to serialize the object to when calling the command, optional.")
// control retries of individual commands
cmd.Flags().IntVar(&o.maximumErrors, "maximum-errors", o.maximumErrors, "Exit after this many errors have been detected with. May be set to -1 for no maximum.")
cmd.Flags().IntVar(&o.retryExitStatus, "retry-on-exit-code", 0, "If any command returns this exit code, retry up to --retry-count times.")
cmd.Flags().IntVar(&o.retryCount, "retry-count", o.retryCount, "The number of times to retry a failing command before continuing.")
// control observe program behavior
cmd.Flags().BoolVar(&o.once, "once", false, "If true, exit with a status code 0 after all current objects have been processed.")
cmd.Flags().DurationVar(&o.exitAfterPeriod, "exit-after", 0, "Exit with status code 0 after the provided duration, optional.")
cmd.Flags().DurationVar(&o.resyncPeriod, "resync-period", 0, "When non-zero, periodically reprocess every item from the server as a Sync event. Use to ensure external systems are kept up to date.")
cmd.Flags().BoolVar(&o.printMetricsOnExit, "print-metrics-on-exit", false, "If true, on exit write all metrics to stdout.")
cmd.Flags().StringVar(&o.listenAddr, "listen-addr", o.listenAddr, "The name of an interface to listen on to expose metrics and health checking.")
// additional debug output
cmd.Flags().BoolVar(&o.noHeaders, "no-headers", false, "If true, skip printing information about each event prior to executing the command.")
return cmd
}
func (o *ObserveOptions) Complete(f kcmdutil.Factory, cmd *cobra.Command, args []string) error {
var err error
var command []string
if i := cmd.ArgsLenAtDash(); i != -1 {
command = args[i:]
args = args[:i]
}
o.eachCommand = command
switch len(args) {
case 0:
return fmt.Errorf("you must specify at least one argument containing the resource to observe")
case 1:
default:
return fmt.Errorf("you may only specify one argument containing the resource to observe (use '--' to separate your resource and your command)")
}
gr := schema.ParseGroupResource(args[0])
if gr.Empty() {
return fmt.Errorf("unknown resource argument")
}
mapper, err := f.ToRESTMapper()
if err != nil {
return err
}
version, err := mapper.KindFor(gr.WithVersion(""))
if err != nil {
return err
}
mapping, err := mapper.RESTMapping(version.GroupKind())
if err != nil {
return err
}
o.mapping = mapping
o.includeNamespace = mapping.Scope.Name() == meta.RESTScopeNamespace.Name()
o.client, err = f.ClientForMapping(mapping)
if err != nil {
return err
}
o.namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
switch o.templateType {
case "jsonpath":
p, err := NewJSONPathArgumentPrinter(o.includeNamespace, o.strictTemplates, o.templates...)
if err != nil {
return err
}
o.printer = p
case "gotemplate":
p, err := NewGoTemplateArgumentPrinter(o.includeNamespace, o.strictTemplates, o.templates...)
if err != nil {
return err
}
o.printer = p
default:
return fmt.Errorf("template type %q not recognized - valid values are jsonpath and gotemplate", o.templateType)
}
o.printer = NewVersionedColumnPrinter(o.printer, legacyscheme.Scheme, version.GroupVersion())
if o.noHeaders {
o.debugOut = ioutil.Discard
} else {
o.debugOut = o.Out
}
o.argumentStore = &objectArgumentsStore{}
switch {
case len(o.nameSyncCommand) > 0:
o.argumentStore.keyFn = func() ([]string, error) {
var out []byte
err := retryCommandError(o.retryExitStatus, o.retryCount, func() error {
c := exec.Command(o.nameSyncCommand[0], o.nameSyncCommand[1:]...)
var err error
return measureCommandDuration(nameExecDurations, func() error {
out, err = c.Output()
return err
})
})
if err != nil {
if exit, ok := err.(*exec.ExitError); ok {
if len(exit.Stderr) > 0 {
err = fmt.Errorf("%v\n%s", err, string(exit.Stderr))
}
}
return nil, err
}
names := strings.Split(string(out), "\n")
sort.Sort(sort.StringSlice(names))
var outputNames []string
for i, s := range names {
if len(s) != 0 {
outputNames = names[i:]
break
}
}
glog.V(4).Infof("Found existing keys: %v", outputNames)
return outputNames, nil
}
o.knownObjects = o.argumentStore
case len(o.deleteCommand) > 0, o.resyncPeriod > 0:
o.knownObjects = o.argumentStore
}
return nil
}
func (o *ObserveOptions) Validate(args []string) error {
if len(o.nameSyncCommand) > 0 && len(o.deleteCommand) == 0 {
return fmt.Errorf("--delete and --names must both be specified")
}
return nil
}
func (o *ObserveOptions) Run() error {
if len(o.deleteCommand) > 0 && len(o.nameSyncCommand) == 0 {
fmt.Fprintf(o.ErrOut, "warning: If you are modifying resources outside of %q, you should use the --names command to ensure you don't miss deletions that occur while the command is not running.\n", o.mapping.Resource)
}
// watch the given resource for changes
store := cache.NewDeltaFIFO(objectArgumentsKeyFunc, o.knownObjects)
lw := restListWatcher{Helper: resource.NewHelper(o.client, o.mapping)}
if !o.allNamespaces {
lw.namespace = o.namespace
}
// ensure any child processes are reaped if we are running as PID 1
proc.StartReaper()
// listen on the provided address for metrics
if len(o.listenAddr) > 0 {
prometheus.MustRegister(observeCounts)
prometheus.MustRegister(execDurations)
prometheus.MustRegister(nameExecDurations)
errWaitingForSync := fmt.Errorf("waiting for initial sync")
healthz.InstallHandler(http.DefaultServeMux, healthz.NamedCheck("ready", func(r *http.Request) error {
if !store.HasSynced() {
return errWaitingForSync
}
return nil
}))
http.Handle("/metrics", prometheus.Handler())
go func() {
glog.Fatalf("Unable to listen on %q: %v", o.listenAddr, http.ListenAndServe(o.listenAddr, nil))
}()
glog.V(2).Infof("Listening on %s at /metrics and /healthz", o.listenAddr)
}
// exit cleanly after a certain period
// lock guards the loop to ensure no child processes are running
var lock sync.Mutex
if o.exitAfterPeriod > 0 {
go func() {
<-time.After(o.exitAfterPeriod)
lock.Lock()
defer lock.Unlock()
o.dumpMetrics()
fmt.Fprintf(o.ErrOut, "Shutting down after %s ...\n", o.exitAfterPeriod)
os.Exit(0)
}()
}
defer o.dumpMetrics()
stopCh := make(chan struct{})
defer close(stopCh)
// start the reflector
reflector := cache.NewNamedReflector("observer", lw, nil, store, o.resyncPeriod)
go func() {
observedListErrors := 0
wait.Until(func() {
if err := reflector.ListAndWatch(stopCh); err != nil {
utilruntime.HandleError(err)
observedListErrors++
if o.maximumErrors != -1 && observedListErrors > o.maximumErrors {
glog.Fatalf("Maximum list errors of %d reached, exiting", o.maximumErrors)
}
}
}, time.Second, stopCh)
}()
if o.once {
// wait until the reflector reports it has completed the initial list and the
// fifo has been populated
for len(reflector.LastSyncResourceVersion()) == 0 {
time.Sleep(50 * time.Millisecond)
}
// if the store is empty, there is nothing to sync
if store.HasSynced() && len(store.ListKeys()) == 0 {
fmt.Fprintf(o.ErrOut, "Nothing to sync, exiting immediately\n")
return nil
}
}
// process all changes that occur in the resource
syncing := false
for {
_, err := store.Pop(func(obj interface{}) error {
// if we failed to retrieve the list of keys, exit
if err := o.argumentStore.ListKeysError(); err != nil {
return fmt.Errorf("unable to list known keys: %v", err)
}
deltas := obj.(cache.Deltas)
for _, delta := range deltas {
if err := func() error {
lock.Lock()
defer lock.Unlock()
// handle before and after observe notification
switch {
case !syncing && delta.Type == cache.Sync:
if err := o.startSync(); err != nil {
return err
}
syncing = true
case syncing && delta.Type != cache.Sync:
if err := o.finishSync(); err != nil {
return err
}
syncing = false
}
// require the user to provide a name function in order to get events beyond added / updated
if !syncing && o.knownObjects == nil && !(delta.Type == cache.Added || delta.Type == cache.Updated) {
return nil
}
observeCounts.WithLabelValues(string(delta.Type)).Inc()
// calculate the arguments for the delta and then invoke any command
object, arguments, output, err := o.calculateArguments(delta)
if err != nil {
return err
}
if err := o.next(delta.Type, object, output, arguments); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
// if we only want to run once, exit here
if o.once && store.HasSynced() {
if syncing {
if err := o.finishSync(); err != nil {
return err
}
}
return nil
}
}
}
// calculateArguments determines the arguments for a give delta and updates the argument store, or returns
// an error. If the object can be transformed into a full JSON object, that is also returned.
func (o *ObserveOptions) calculateArguments(delta cache.Delta) (runtime.Object, []string, []byte, error) {
var arguments []string
var object runtime.Object
var key string
var output []byte
switch t := delta.Object.(type) {
case cache.DeletedFinalStateUnknown:
key = t.Key
if obj, ok := t.Obj.(runtime.Object); ok {
object = obj
args, data, err := o.printer.Print(obj)
if err != nil {
return nil, nil, nil, fmt.Errorf("unable to write arguments: %v", err)
}
arguments = args
output = data
} else {
value, _, err := o.argumentStore.GetByKey(key)
if err != nil {
return nil, nil, nil, err
}
if value != nil {
args, ok := value.(objectArguments)
if !ok {
return nil, nil, nil, fmt.Errorf("unexpected cache value %T", value)
}
arguments = args.arguments
output = args.output
}
}
o.argumentStore.Remove(key)
case runtime.Object:
object = t
args, data, err := o.printer.Print(t)
if err != nil {
return nil, nil, nil, fmt.Errorf("unable to write arguments: %v", err)
}
arguments = args
output = data
key, _ = cache.MetaNamespaceKeyFunc(t)
if delta.Type == cache.Deleted {
o.argumentStore.Remove(key)
} else {
saved := objectArguments{key: key, arguments: arguments}
// only cache the object data if the commands will be using it.
if len(o.objectEnvVar) > 0 {
saved.output = output
}
o.argumentStore.Put(key, saved)
}
case objectArguments:
key = t.key
arguments = t.arguments
output = t.output
default:
return nil, nil, nil, fmt.Errorf("unrecognized object %T from cache store", delta.Object)
}
if object == nil {
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return nil, nil, nil, err
}
unstructured := &unstructured.Unstructured{}
unstructured.SetNamespace(namespace)
unstructured.SetName(name)
object = unstructured
}
return object, arguments, output, nil
}
func (o *ObserveOptions) startSync() error {
fmt.Fprintf(o.debugOut, "# %s Sync started\n", time.Now().Format(time.RFC3339))
return nil
}
func (o *ObserveOptions) finishSync() error {
fmt.Fprintf(o.debugOut, "# %s Sync ended\n", time.Now().Format(time.RFC3339))
return nil
}
func (o *ObserveOptions) next(deltaType cache.DeltaType, obj runtime.Object, output []byte, arguments []string) error {
glog.V(4).Infof("Processing %s %v: %#v", deltaType, arguments, obj)
m, err := meta.Accessor(obj)
if err != nil {
return fmt.Errorf("unable to handle %T: %v", obj, err)
}
resourceVersion := m.GetResourceVersion()
outType := string(deltaType)
var args []string
if o.includeNamespace {
args = append(args, m.GetNamespace())
}
args = append(args, m.GetName())
var command string
switch {
case deltaType == cache.Deleted:
if len(o.deleteCommand) > 0 {
command = o.deleteCommand[0]
args = append(append([]string{}, o.deleteCommand[1:]...), args...)
}
case len(o.eachCommand) > 0:
command = o.eachCommand[0]
args = append(append([]string{}, o.eachCommand[1:]...), args...)
}
args = append(args, arguments...)
if len(command) == 0 {
fmt.Fprintf(o.debugOut, "# %s %s %s\t%s\n", time.Now().Format(time.RFC3339), outType, resourceVersion, printCommandLine(command, args...))
return nil
}
fmt.Fprintf(o.debugOut, "# %s %s %s\t%s\n", time.Now().Format(time.RFC3339), outType, resourceVersion, printCommandLine(command, args...))
out, errOut := &newlineTrailingWriter{w: o.Out}, &newlineTrailingWriter{w: o.ErrOut}
err = retryCommandError(o.retryExitStatus, o.retryCount, func() error {
cmd := exec.Command(command, args...)
cmd.Stdout = out
cmd.Stderr = errOut
cmd.Env = os.Environ()
if len(o.objectEnvVar) > 0 {
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", o.objectEnvVar, string(output)))
}
if len(o.typeEnvVar) > 0 {
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", o.typeEnvVar, string(outType)))
}
err := measureCommandDuration(execDurations, cmd.Run, outType)
out.Flush()
errOut.Flush()
return err
})
if err != nil {
if code, ok := exitCodeForCommandError(err); ok && code != 0 {
err = fmt.Errorf("command %q exited with status code %d", command, code)
}
return o.handleCommandError(err)
}
return nil
}
func (o *ObserveOptions) handleCommandError(err error) error {
if err == nil {
return nil
}
o.observedErrors++
fmt.Fprintf(o.ErrOut, "error: %v\n", err)
if o.maximumErrors == -1 || o.observedErrors < o.maximumErrors {
return nil
}
return fmt.Errorf("reached maximum error limit of %d, exiting", o.maximumErrors)
}
func (o *ObserveOptions) dumpMetrics() {
if !o.printMetricsOnExit {
return
}
w := httptest.NewRecorder()
prometheus.UninstrumentedHandler().ServeHTTP(w, &http.Request{})
if w.Code == http.StatusOK {
fmt.Fprintf(o.Out, w.Body.String())
}
}
func measureCommandDuration(m *prometheus.SummaryVec, fn func() error, labels ...string) error {
n := time.Now()
err := fn()
duration := time.Now().Sub(n)
statusCode, ok := exitCodeForCommandError(err)
if !ok {
statusCode = -1
}
m.WithLabelValues(append(labels, strconv.Itoa(statusCode))...).Observe(float64(duration / time.Millisecond))
if errnoError(err) == syscall.ECHILD {
// ignore wait4 syscall errno as it means
// that the subprocess has started and ended
// before the wait call was made.
return nil
}
return err
}
func errnoError(err error) syscall.Errno {
if se, ok := err.(*os.SyscallError); ok {
if errno, ok := se.Err.(syscall.Errno); ok {
return errno
}
}
return 0
}
func exitCodeForCommandError(err error) (int, bool) {
if err == nil {
return 0, true
}
if exit, ok := err.(*exec.ExitError); ok {
if ws, ok := exit.ProcessState.Sys().(syscall.WaitStatus); ok {
return ws.ExitStatus(), true
}
}
return 0, false
}
func retryCommandError(onExitStatus, times int, fn func() error) error {
err := fn()
if err != nil && onExitStatus != 0 && times > 0 {
if status, ok := exitCodeForCommandError(err); ok {
if status == onExitStatus {
glog.V(4).Infof("retrying command: %v", err)
return retryCommandError(onExitStatus, times-1, fn)
}
}
}
return err
}
func printCommandLine(cmd string, args ...string) string {
outCmd := cmd
if strings.ContainsAny(outCmd, "\"\\ ") {
outCmd = strconv.Quote(outCmd)
}
if len(outCmd) == 0 {
outCmd = "\"\""
}
outArgs := make([]string, 0, len(args))
for _, s := range args {
if strings.ContainsAny(s, "\"\\ ") {
s = strconv.Quote(s)
}
if len(s) == 0 {
s = "\"\""
}
outArgs = append(outArgs, s)
}
if len(outArgs) == 0 {
return outCmd
}
return fmt.Sprintf("%s %s", outCmd, strings.Join(outArgs, " "))
}
type restListWatcher struct {
*resource.Helper
namespace string
}
func (lw restListWatcher) List(opt metav1.ListOptions) (runtime.Object, error) {
return lw.Helper.List(lw.namespace, "", false, &opt)
}
func (lw restListWatcher) Watch(opt metav1.ListOptions) (watch.Interface, error) {
return lw.Helper.Watch(lw.namespace, opt.ResourceVersion, &opt)
}
type JSONPathColumnPrinter struct {
includeNamespace bool
rawTemplates []string
templates []*jsonpath.JSONPath
buf *bytes.Buffer
}
func NewJSONPathArgumentPrinter(includeNamespace, strict bool, templates ...string) (*JSONPathColumnPrinter, error) {
p := &JSONPathColumnPrinter{
includeNamespace: includeNamespace,
rawTemplates: templates,
buf: &bytes.Buffer{},
}
for _, s := range templates {
t := jsonpath.New("template").AllowMissingKeys(!strict)
if err := t.Parse(s); err != nil {
return nil, err
}
p.templates = append(p.templates, t)
}
return p, nil
}
func (p *JSONPathColumnPrinter) Print(obj interface{}) ([]string, []byte, error) {
var columns []string
for i, t := range p.templates {
p.buf.Reset()
if err := t.Execute(p.buf, obj); err != nil {
return nil, nil, fmt.Errorf("error executing template '%v': '%v'\n----data----\n%+v\n", p.rawTemplates[i], err, obj)
}
columns = append(columns, p.buf.String())
}
return columns, nil, nil
}
type GoTemplateColumnPrinter struct {
includeNamespace bool
strict bool
rawTemplates []string
templates []*template.Template
buf *bytes.Buffer
}
func NewGoTemplateArgumentPrinter(includeNamespace, strict bool, templates ...string) (*GoTemplateColumnPrinter, error) {
p := &GoTemplateColumnPrinter{
includeNamespace: includeNamespace,
strict: strict,
rawTemplates: templates,
buf: &bytes.Buffer{},
}
for _, s := range templates {
t := template.New("template")
child, err := t.Parse(s)
if err != nil {
return nil, err
}
if !strict {
child.Option("missingkey=zero")
}
p.templates = append(p.templates, child)
}
return p, nil
}
func (p *GoTemplateColumnPrinter) Print(obj interface{}) ([]string, []byte, error) {
var columns []string
for i, t := range p.templates {
p.buf.Reset()
if err := t.Execute(p.buf, obj); err != nil {
return nil, nil, fmt.Errorf("error executing template '%v': '%v'\n----data----\n%+v\n", p.rawTemplates[i], err, obj)
}
// if the template resolves to the special <no value> result, return it as an empty string
// most arguments will prefer empty vs an arbitrary constant, and we are making gotemplates consistent with
// jsonpath
if p.buf.String() == "<no value>" {
if p.strict {
return nil, nil, fmt.Errorf("error executing template '%v': <no value>", p.rawTemplates[i])
}
columns = append(columns, "")
} else {
columns = append(columns, p.buf.String())
}
}
return columns, nil, nil
}
type ColumnPrinter interface {
Print(obj interface{}) ([]string, []byte, error)
}
// VersionedPrinter takes runtime objects and ensures they are converted to a given API version
// prior to being passed to a nested printer.
type VersionedColumnPrinter struct {
printer ColumnPrinter
convertor runtime.ObjectConvertor
version runtime.GroupVersioner
}
// NewVersionedHumanReadablePrinter wraps a printer to convert objects to a known API version prior to printing.
func NewVersionedColumnPrinter(printer ColumnPrinter, convertor runtime.ObjectConvertor, version runtime.GroupVersioner) ColumnPrinter {
return &VersionedColumnPrinter{
printer: printer,
convertor: convertor,
version: version,
}
}
// Print converts the object to a map[string]interface{} in the target version before calling the nested printer.
func (p *VersionedColumnPrinter) Print(out interface{}) ([]string, []byte, error) {
var output []byte
if obj, ok := out.(runtime.Object); ok {
converted, err := p.convertor.ConvertToVersion(obj, p.version)
if err != nil {
if !runtime.IsNotRegisteredError(err) {
return nil, nil, err
}
converted = obj
}
data, err := json.Marshal(converted)
if err != nil {
return nil, nil, err
}
output = data
out = map[string]interface{}{}
if err := json.Unmarshal(data, &out); err != nil {
return nil, nil, err
}
}
args, _, err := p.printer.Print(out)
return args, output, err
}
type knownObjects interface {
cache.KeyListerGetter
ListKeysError() error
Put(key string, value interface{})
Remove(key string)
}
type objectArguments struct {
key string
arguments []string
output []byte
}
func objectArgumentsKeyFunc(obj interface{}) (string, error) {
if args, ok := obj.(objectArguments); ok {
return args.key, nil
}
return cache.MetaNamespaceKeyFunc(obj)
}
type objectArgumentsStore struct {
keyFn func() ([]string, error)
lock sync.Mutex
arguments map[string]interface{}
err error
}
func (r *objectArgumentsStore) ListKeysError() error {
r.lock.Lock()
defer r.lock.Unlock()
return r.err
}
func (r *objectArgumentsStore) ListKeys() []string {
r.lock.Lock()
defer r.lock.Unlock()
if r.keyFn != nil {
var keys []string
keys, r.err = r.keyFn()
return keys
}
keys := make([]string, 0, len(r.arguments))
for k := range r.arguments {
keys = append(keys, k)
}