diff --git a/CHANGELOG.asciidoc b/CHANGELOG.asciidoc index 6c9a3c4513a..d320d43ceaa 100644 --- a/CHANGELOG.asciidoc +++ b/CHANGELOG.asciidoc @@ -56,6 +56,7 @@ https://github.com/elastic/beats/compare/v6.0.0-alpha1...master[Check the HEAD d - Add macOS implementation of the system diskio metricset. {issue}4144[4144] - Add process_summary metricset that records high level metrics about processes. {pull}4231[4231] +- Add `kube-state-metrics` based metrics to `kubernetes` module {pull}4253[4253] *Packetbeat* diff --git a/NOTICE b/NOTICE index 2027b2a6f4d..9ca73907d23 100644 --- a/NOTICE +++ b/NOTICE @@ -1181,6 +1181,73 @@ github.com/ericchiang/k8s Apache License +-------------------------------------------------------------------- +github.com/golang/protobuf +-------------------------------------------------------------------- +Go support for Protocol Buffers - Google's data interchange format + +Copyright 2010 The Go Authors. All rights reserved. +https://github.com/golang/protobuf + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +-------------------------------------------------------------------- +github.com/matttproud/golang_protobuf_extensions +-------------------------------------------------------------------- +Apache License + +-------NOTICE----- +Copyright 2012 Matt T. Proud (matt.proud@gmail.com) + +-------------------------------------------------------------------- +github.com/prometheus/client_model +-------------------------------------------------------------------- +Apache License + +-------NOTICE----- +Data model artifacts for Prometheus. +Copyright 2012-2015 The Prometheus Authors + +This product includes software developed at +SoundCloud Ltd. (http://soundcloud.com/). + +-------------------------------------------------------------------- +github.com/prometheus/common +-------------------------------------------------------------------- +Apache License + +-------NOTICE----- +Common libraries shared by Prometheus Go components. +Copyright 2015 The Prometheus Authors + +This product includes software developed at +SoundCloud Ltd. (http://soundcloud.com/). + -------------------------------------------------------------------- github.com/Microsoft/go-winio -------------------------------------------------------------------- @@ -2138,38 +2205,6 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------------------------------------------------------------- -github.com/matttproud/golang_protobuf_extensions --------------------------------------------------------------------- -Apache License - --------NOTICE----- -Copyright 2012 Matt T. Proud (matt.proud@gmail.com) - --------------------------------------------------------------------- -github.com/prometheus/client_model --------------------------------------------------------------------- -Apache License - --------NOTICE----- -Data model artifacts for Prometheus. -Copyright 2012-2015 The Prometheus Authors - -This product includes software developed at -SoundCloud Ltd. (http://soundcloud.com/). - --------------------------------------------------------------------- -github.com/prometheus/common --------------------------------------------------------------------- -Apache License - --------NOTICE----- -Common libraries shared by Prometheus Go components. -Copyright 2015 The Prometheus Authors - -This product includes software developed at -SoundCloud Ltd. (http://soundcloud.com/). - -------------------------------------------------------------------- github.com/google/uuid -------------------------------------------------------------------- diff --git a/filebeat/docs/fields.asciidoc b/filebeat/docs/fields.asciidoc index d8b6c07bf7d..aacdf062713 100644 --- a/filebeat/docs/fields.asciidoc +++ b/filebeat/docs/fields.asciidoc @@ -684,12 +684,14 @@ The logged message. [[exported-fields-kubernetes-processor]] -== Kubernetes info Fields +== kubernetes Fields +beta[] Kubernetes metadata added by the kubernetes processor + [float] === kubernetes.pod.name @@ -730,6 +732,14 @@ type: keyword Kubernetes container name +[float] +=== kubernetes.container.image + +type: keyword + +Kubernetes container image + + [[exported-fields-log]] == Log File Content Fields diff --git a/heartbeat/docs/fields.asciidoc b/heartbeat/docs/fields.asciidoc index c5b8affd042..5e3cbd4ab2a 100644 --- a/heartbeat/docs/fields.asciidoc +++ b/heartbeat/docs/fields.asciidoc @@ -411,12 +411,14 @@ type: long Duration in microseconds [[exported-fields-kubernetes-processor]] -== Kubernetes info Fields +== kubernetes Fields +beta[] Kubernetes metadata added by the kubernetes processor + [float] === kubernetes.pod.name @@ -457,6 +459,14 @@ type: keyword Kubernetes container name +[float] +=== kubernetes.container.image + +type: keyword + +Kubernetes container image + + [[exported-fields-resolve]] == Host Lookup Fields diff --git a/libbeat/processors/kubernetes/_meta/fields.yml b/libbeat/processors/kubernetes/_meta/fields.yml index 09ba9d646be..c3a9113b485 100644 --- a/libbeat/processors/kubernetes/_meta/fields.yml +++ b/libbeat/processors/kubernetes/_meta/fields.yml @@ -1,30 +1,41 @@ - key: kubernetes - title: Kubernetes info + title: kubernetes description: > + beta[] + Kubernetes metadata added by the kubernetes processor + short_config: false anchor: kubernetes-processor fields: - - name: kubernetes.pod.name - type: keyword - description: > - Kubernetes pod name + - name: kubernetes + type: group + fields: + - name: pod.name + type: keyword + description: > + Kubernetes pod name + + - name: namespace + type: keyword + description: > + Kubernetes namespace - - name: kubernetes.namespace - type: keyword - description: > - Kubernetes namespace + - name: labels + type: object + description: > + Kubernetes labels map - - name: kubernetes.labels - type: object - description: > - Kubernetes labels map + - name: annotations + type: object + description: > + Kubernetes annotations map - - name: kubernetes.annotations - type: object - description: > - Kubernetes annotations map + - name: container.name + type: keyword + description: > + Kubernetes container name - - name: kubernetes.container.name - type: keyword - description: > - Kubernetes container name + - name: container.image + type: keyword + description: > + Kubernetes container image diff --git a/libbeat/tests/system/beat/beat.py b/libbeat/tests/system/beat/beat.py index a6148313775..61d43dd0a1e 100644 --- a/libbeat/tests/system/beat/beat.py +++ b/libbeat/tests/system/beat/beat.py @@ -426,7 +426,9 @@ def extract_fields(doc_list, name): # TODO: Make fields_doc path more generic to work with beat-generator with open(fields_doc, "r") as f: - path = os.path.abspath(os.path.dirname(__file__) + "../../../../_meta/fields.common.yml") + path = os.path.abspath(os.path.dirname(__file__) + "../../../../_meta/fields.generated.yml") + if not os.path.isfile(path): + path = os.path.abspath(os.path.dirname(__file__) + "../../../../_meta/fields.common.yml") with open(path) as f2: content = f2.read() diff --git a/metricbeat/docker-compose.yml b/metricbeat/docker-compose.yml index 467c066e617..a951792fe9f 100644 --- a/metricbeat/docker-compose.yml +++ b/metricbeat/docker-compose.yml @@ -26,6 +26,7 @@ services: - ${PWD}/module/jolokia/_meta/env - ${PWD}/module/kafka/_meta/env - ${PWD}/module/kibana/_meta/env + - ${PWD}/module/kubernetes/_meta/env - ${PWD}/module/memcached/_meta/env - ${PWD}/module/mongodb/_meta/env - ${PWD}/module/mysql/_meta/env @@ -51,6 +52,8 @@ services: jolokia: { condition: service_healthy } kafka: { condition: service_healthy } kibana: { condition: service_healthy } + kubernetes: { condition: service_healthy } + kube-state: { condition: service_started } memcached: { condition: service_healthy } mongodb: { condition: service_healthy } mysql: { condition: service_healthy } @@ -96,6 +99,22 @@ services: file: ${ES_BEATS}/testing/environments/${TESTING_ENVIRONMENT}.yml service: kibana + kubernetes: + build: ${PWD}/module/kubernetes/_meta + network_mode: host + pid: host + privileged: true + volumes: + - /:/rootfs:ro + - /sys:/sys + - /var/lib/docker:/var/lib/docker + - /var/run:/var/run + + kube-state: + build: + context: ${PWD}/module/kubernetes/_meta/ + dockerfile: Dockerfile.kube-state + memcached: build: ${PWD}/module/memcached/_meta diff --git a/metricbeat/docs/fields.asciidoc b/metricbeat/docs/fields.asciidoc index 713929ab3e7..1dc65a348af 100644 --- a/metricbeat/docs/fields.asciidoc +++ b/metricbeat/docs/fields.asciidoc @@ -5777,12 +5777,14 @@ Total number of connections. [[exported-fields-kubernetes-processor]] -== Kubernetes info Fields +== kubernetes Fields +beta[] Kubernetes metadata added by the kubernetes processor + [float] === kubernetes.pod.name @@ -5823,6 +5825,14 @@ type: keyword Kubernetes container name +[float] +=== kubernetes.container.image + +type: keyword + +Kubernetes container image + + [[exported-fields-kubernetes]] == kubernetes Fields @@ -5845,6 +5855,14 @@ kubernetes container metrics +[float] +=== kubernetes.container.start_time + +type: date + +Start time + + [float] == cpu Fields @@ -6054,6 +6072,14 @@ type: keyword Node name +[float] +=== kubernetes.node.start_time + +type: date + +Start time + + [float] == cpu Fields @@ -6214,6 +6240,31 @@ Filesystem total used in bytes +[float] +=== kubernetes.node.fs.inodes.used + +type: long + +Number of used inodes + + +[float] +=== kubernetes.node.fs.inodes.count + +type: long + +Number of inodes + + +[float] +=== kubernetes.node.fs.inodes.free + +type: long + +Number of free inodes + + + [float] @@ -6255,6 +6306,14 @@ kubernetes pod metrics +[float] +=== kubernetes.pod.start_time + +type: date + +Start time + + [float] @@ -6294,6 +6353,340 @@ type: long Tx errors +[float] +== container Fields + +kubernetes container metrics + + + +[float] +=== kubernetes.container.id + +type: keyword + +Container id + + +[float] +=== kubernetes.container.status.phase + +type: keyword + +Container phase (running, waiting, terminated) + + +[float] +=== kubernetes.container.status.ready + +type: boolean + +Container ready status + + +[float] +=== kubernetes.container.status.restarts + +type: integer + +Container restarts count + + + +[float] +=== kubernetes.container.cpu.limit.nanocores + +type: long + +Container CPU nanocores limit + + +[float] +=== kubernetes.container.cpu.request.nanocores + +type: long + +Container CPU requested nanocores + + + +[float] +=== kubernetes.container.memory.limit.bytes + +type: long + +format: bytes + +Container memory limit in bytes + + +[float] +=== kubernetes.container.memory.request.bytes + +type: long + +format: bytes + +Container requested memory in bytes + + +[float] +== deployment Fields + +kubernetes deployment metrics + + + +[float] +=== kubernetes.deployment.name + +type: keyword + +Kubernetes deployment name + + +[float] +=== kubernetes.deployment.paused + +type: boolean + +Kubernetes deployment paused status + + +[float] +== replicas Fields + +Kubernetes deployment replicas info + + + +[float] +=== kubernetes.deployment.replicas.desired + +type: integer + +Deployment number of desired replicas (spec) + + +[float] +=== kubernetes.deployment.replicas.available + +type: integer + +Deployment available replicas + + +[float] +=== kubernetes.deployment.replicas.unavailable + +type: integer + +Deployment unavailable replicas + + +[float] +=== kubernetes.deployment.replicas.updated + +type: integer + +Deployment updated replicas + + +[float] +== node Fields + +kubernetes node metrics + + + + +[float] +=== kubernetes.node.status.ready + +type: keyword + +Node ready status (true, false or unknown) + + +[float] +=== kubernetes.node.status.unschedulable + +type: boolean + +Node unschedulable status + + + +[float] +=== kubernetes.node.cpu.allocatable.cores + +type: long + +Node CPU allocatable cores + + +[float] +=== kubernetes.node.cpu.capacity.cores + +type: long + +Node CPU capacity cores + + + +[float] +=== kubernetes.node.memory.allocatable.bytes + +type: long + +format: bytes + +Node allocatable memory in bytes + + +[float] +=== kubernetes.node.memory.capacity.bytes + +type: long + +format: bytes + +Node memory capacity in bytes + + + +[float] +=== kubernetes.node.pod.allocatable.total + +type: long + +Node allocatable pods + + +[float] +=== kubernetes.node.pod.capacity.total + +type: long + +Node pod capacity + + +[float] +== pod Fields + +kubernetes pod metrics + + + +[float] +=== kubernetes.pod.ip + +type: ip + +Kubernetes pod IP + + +[float] +=== kubernetes.pod.host_ip + +type: ip + +Kubernetes pod host IP + + +[float] +== status Fields + +Kubernetes pod status metrics + + + +[float] +=== kubernetes.pod.status.phase + +type: keyword + +Kubernetes pod phase (Running, Pending...) + + +[float] +=== kubernetes.pod.status.ready + +type: keyword + +Kubernetes pod ready status (true, false or unknown) + + +[float] +=== kubernetes.pod.status.scheduled + +type: keyword + +Kubernetes pod scheduled status (true, false, unknown) + + +[float] +== replicaset Fields + +kubernetes replica set metrics + + + +[float] +=== kubernetes.replicaset.name + +type: keyword + +Kubernetes replica set name + + +[float] +== replicas Fields + +Kubernetes replica set paused status + + + +[float] +=== kubernetes.replicaset.replicas.available + +type: long + +The number of replicas per ReplicaSet + + +[float] +=== kubernetes.replicaset.replicas.desired + +type: long + +The number of replicas per ReplicaSet + + +[float] +=== kubernetes.replicaset.replicas.ready + +type: long + +The number of ready replicas per ReplicaSet + + +[float] +=== kubernetes.replicaset.replicas.observed + +type: long + +The generation observed by the ReplicaSet controller + + +[float] +=== kubernetes.replicaset.replicas.labeled + +type: long + +The number of fully labeled replicas per ReplicaSet + + [float] == system Fields @@ -6309,6 +6702,14 @@ type: keyword Container name +[float] +=== kubernetes.system.start_time + +type: date + +Start time + + [float] == cpu Fields diff --git a/metricbeat/docs/modules/kubernetes.asciidoc b/metricbeat/docs/modules/kubernetes.asciidoc index 0b00b7c85fd..1d729eb3822 100644 --- a/metricbeat/docs/modules/kubernetes.asciidoc +++ b/metricbeat/docs/modules/kubernetes.asciidoc @@ -7,7 +7,12 @@ This file is generated! See scripts/docs_collector.py beta[] -This module fetches metrics from Kubernetes https://kubernetes.io/docs/admin/kubelet/[kubelet] agent. +This module fetches metrics from Kubernetes https://kubernetes.io/docs/admin/kubelet/[kubelet] +agent and https://github.com/kubernetes/kube-state-metrics[kube-state-metrics] service. + +All metricsets with the `state_` prefix require `hosts` field pointing to kube-stat-metrics +service within the cluster, while the rest should be pointed to kubelet service. Check the +example configuration on how to do it. [float] @@ -19,12 +24,29 @@ in <>. Here is an example configuration: [source,yaml] ---- metricbeat.modules: +# Node metrics, from kubelet: - module: kubernetes - metricsets: ["node","container","volume","pod","system"] enabled: false + metricsets: + - node + - system + - pod + - container + - volume period: 10s hosts: ["localhost:10255"] +# State metrics from kube-state-metrics service: +- module: kubernetes + enabled: false + metricsets: + - state_node + - state_deployment + - state_replicaset + - state_pod + - state_container + period: 10s + hosts: ["kube-state-metrics:8080"] ---- [float] @@ -38,6 +60,16 @@ The following metricsets are available: * <> +* <> + +* <> + +* <> + +* <> + +* <> + * <> * <> @@ -48,6 +80,16 @@ include::kubernetes/node.asciidoc[] include::kubernetes/pod.asciidoc[] +include::kubernetes/state_container.asciidoc[] + +include::kubernetes/state_deployment.asciidoc[] + +include::kubernetes/state_node.asciidoc[] + +include::kubernetes/state_pod.asciidoc[] + +include::kubernetes/state_replicaset.asciidoc[] + include::kubernetes/system.asciidoc[] include::kubernetes/volume.asciidoc[] diff --git a/metricbeat/docs/modules/kubernetes/state_container.asciidoc b/metricbeat/docs/modules/kubernetes/state_container.asciidoc new file mode 100644 index 00000000000..b0f97e7c999 --- /dev/null +++ b/metricbeat/docs/modules/kubernetes/state_container.asciidoc @@ -0,0 +1,19 @@ +//// +This file is generated! See scripts/docs_collector.py +//// + +[[metricbeat-metricset-kubernetes-state_container]] +include::../../../module/kubernetes/state_container/_meta/docs.asciidoc[] + + +==== Fields + +For a description of each field in the metricset, see the +<> section. + +Here is an example document generated by this metricset: + +[source,json] +---- +include::../../../module/kubernetes/state_container/_meta/data.json[] +---- diff --git a/metricbeat/docs/modules/kubernetes/state_deployment.asciidoc b/metricbeat/docs/modules/kubernetes/state_deployment.asciidoc new file mode 100644 index 00000000000..ced1707abb6 --- /dev/null +++ b/metricbeat/docs/modules/kubernetes/state_deployment.asciidoc @@ -0,0 +1,19 @@ +//// +This file is generated! See scripts/docs_collector.py +//// + +[[metricbeat-metricset-kubernetes-state_deployment]] +include::../../../module/kubernetes/state_deployment/_meta/docs.asciidoc[] + + +==== Fields + +For a description of each field in the metricset, see the +<> section. + +Here is an example document generated by this metricset: + +[source,json] +---- +include::../../../module/kubernetes/state_deployment/_meta/data.json[] +---- diff --git a/metricbeat/docs/modules/kubernetes/state_node.asciidoc b/metricbeat/docs/modules/kubernetes/state_node.asciidoc new file mode 100644 index 00000000000..2572255ed51 --- /dev/null +++ b/metricbeat/docs/modules/kubernetes/state_node.asciidoc @@ -0,0 +1,19 @@ +//// +This file is generated! See scripts/docs_collector.py +//// + +[[metricbeat-metricset-kubernetes-state_node]] +include::../../../module/kubernetes/state_node/_meta/docs.asciidoc[] + + +==== Fields + +For a description of each field in the metricset, see the +<> section. + +Here is an example document generated by this metricset: + +[source,json] +---- +include::../../../module/kubernetes/state_node/_meta/data.json[] +---- diff --git a/metricbeat/docs/modules/kubernetes/state_pod.asciidoc b/metricbeat/docs/modules/kubernetes/state_pod.asciidoc new file mode 100644 index 00000000000..1c7def9c1a8 --- /dev/null +++ b/metricbeat/docs/modules/kubernetes/state_pod.asciidoc @@ -0,0 +1,19 @@ +//// +This file is generated! See scripts/docs_collector.py +//// + +[[metricbeat-metricset-kubernetes-state_pod]] +include::../../../module/kubernetes/state_pod/_meta/docs.asciidoc[] + + +==== Fields + +For a description of each field in the metricset, see the +<> section. + +Here is an example document generated by this metricset: + +[source,json] +---- +include::../../../module/kubernetes/state_pod/_meta/data.json[] +---- diff --git a/metricbeat/docs/modules/kubernetes/state_replicaset.asciidoc b/metricbeat/docs/modules/kubernetes/state_replicaset.asciidoc new file mode 100644 index 00000000000..49fd627cb30 --- /dev/null +++ b/metricbeat/docs/modules/kubernetes/state_replicaset.asciidoc @@ -0,0 +1,19 @@ +//// +This file is generated! See scripts/docs_collector.py +//// + +[[metricbeat-metricset-kubernetes-state_replicaset]] +include::../../../module/kubernetes/state_replicaset/_meta/docs.asciidoc[] + + +==== Fields + +For a description of each field in the metricset, see the +<> section. + +Here is an example document generated by this metricset: + +[source,json] +---- +include::../../../module/kubernetes/state_replicaset/_meta/data.json[] +---- diff --git a/metricbeat/helper/prometheus.go b/metricbeat/helper/prometheus.go new file mode 100644 index 00000000000..958b9e7ff8b --- /dev/null +++ b/metricbeat/helper/prometheus.go @@ -0,0 +1,51 @@ +package helper + +import ( + "fmt" + + "github.com/elastic/beats/metricbeat/mb" + + dto "github.com/prometheus/client_model/go" + "github.com/prometheus/common/expfmt" +) + +// Prometheus helper retrieves prometheus formatted metrics +type Prometheus struct { + HTTP +} + +// NewPrometheusClient creates new prometheus helper +func NewPrometheusClient(base mb.BaseMetricSet) *Prometheus { + http := NewHTTP(base) + return &Prometheus{*http} +} + +// GetFamilies requests metric families from prometheus endpoint and returns them +func (p *Prometheus) GetFamilies() ([]*dto.MetricFamily, error) { + resp, err := p.FetchResponse() + if err != nil { + return nil, err + } + defer resp.Body.Close() + + format := expfmt.ResponseFormat(resp.Header) + if format == "" { + return nil, fmt.Errorf("Invalid format for response of response") + } + + decoder := expfmt.NewDecoder(resp.Body, format) + if decoder == nil { + return nil, fmt.Errorf("Unable to create decoder to decode response") + } + + families := []*dto.MetricFamily{} + for err == nil { + mf := &dto.MetricFamily{} + err = decoder.Decode(mf) + if err == nil { + families = append(families, mf) + } + } + + return families, nil +} diff --git a/metricbeat/include/list.go b/metricbeat/include/list.go index d05eccac768..4f90654bd85 100644 --- a/metricbeat/include/list.go +++ b/metricbeat/include/list.go @@ -54,7 +54,13 @@ import ( _ "github.com/elastic/beats/metricbeat/module/kubernetes/container" _ "github.com/elastic/beats/metricbeat/module/kubernetes/node" _ "github.com/elastic/beats/metricbeat/module/kubernetes/pod" + _ "github.com/elastic/beats/metricbeat/module/kubernetes/state_container" + _ "github.com/elastic/beats/metricbeat/module/kubernetes/state_deployment" + _ "github.com/elastic/beats/metricbeat/module/kubernetes/state_node" + _ "github.com/elastic/beats/metricbeat/module/kubernetes/state_pod" + _ "github.com/elastic/beats/metricbeat/module/kubernetes/state_replicaset" _ "github.com/elastic/beats/metricbeat/module/kubernetes/system" + _ "github.com/elastic/beats/metricbeat/module/kubernetes/util" _ "github.com/elastic/beats/metricbeat/module/kubernetes/volume" _ "github.com/elastic/beats/metricbeat/module/memcached" _ "github.com/elastic/beats/metricbeat/module/memcached/stats" diff --git a/metricbeat/metricbeat.full.yml b/metricbeat/metricbeat.full.yml index 55e79d6e9d3..d9bbe62d18b 100644 --- a/metricbeat/metricbeat.full.yml +++ b/metricbeat/metricbeat.full.yml @@ -251,12 +251,29 @@ metricbeat.modules: hosts: ["localhost:5601"] #----------------------------- kubernetes Module ----------------------------- +# Node metrics, from kubelet: - module: kubernetes - metricsets: ["node","container","volume","pod","system"] enabled: false + metricsets: + - node + - system + - pod + - container + - volume period: 10s hosts: ["localhost:10255"] +# State metrics from kube-state-metrics service: +- module: kubernetes + enabled: false + metricsets: + - state_node + - state_deployment + - state_replicaset + - state_pod + - state_container + period: 10s + hosts: ["kube-state-metrics:8080"] #------------------------------ memcached Module ----------------------------- - module: memcached diff --git a/metricbeat/module/kubernetes/_meta/Dockerfile b/metricbeat/module/kubernetes/_meta/Dockerfile new file mode 100644 index 00000000000..4afeeb253a2 --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/Dockerfile @@ -0,0 +1,8 @@ +FROM exekias/localkube-image +RUN apt-get update && apt-get install -y curl && apt-get clean +HEALTHCHECK CMD curl -f http://localhost:10255/healthz || exit 1 +CMD exec /localkube start \ + --apiserver-insecure-address=0.0.0.0 \ + --apiserver-insecure-port=8080 \ + --logtostderr=true \ + --containerized diff --git a/metricbeat/module/kubernetes/_meta/Dockerfile.kube-state b/metricbeat/module/kubernetes/_meta/Dockerfile.kube-state new file mode 100644 index 00000000000..e9c086f912d --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/Dockerfile.kube-state @@ -0,0 +1,6 @@ +FROM gcr.io/google_containers/kube-state-metrics:v0.5.0 + +ADD kubeconfig / + +ENTRYPOINT ["/kube-state-metrics"] +CMD ["--port=8080", "--in-cluster=false", "--apiserver=http://172.17.0.1:8080", "--kubeconfig=/kubeconfig"] diff --git a/metricbeat/module/kubernetes/_meta/config.yml b/metricbeat/module/kubernetes/_meta/config.yml index 203d72470a9..25d67b3f6fe 100644 --- a/metricbeat/module/kubernetes/_meta/config.yml +++ b/metricbeat/module/kubernetes/_meta/config.yml @@ -1,6 +1,23 @@ +# Node metrics, from kubelet: - module: kubernetes - metricsets: ["node","container","volume","pod","system"] enabled: false + metricsets: + - node + - system + - pod + - container + - volume period: 10s hosts: ["localhost:10255"] +# State metrics from kube-state-metrics service: +- module: kubernetes + enabled: false + metricsets: + - state_node + - state_deployment + - state_replicaset + - state_pod + - state_container + period: 10s + hosts: ["kube-state-metrics:8080"] diff --git a/metricbeat/module/kubernetes/_meta/docs.asciidoc b/metricbeat/module/kubernetes/_meta/docs.asciidoc index c378d5bbd6c..419dacd76d9 100644 --- a/metricbeat/module/kubernetes/_meta/docs.asciidoc +++ b/metricbeat/module/kubernetes/_meta/docs.asciidoc @@ -2,4 +2,9 @@ beta[] -This module fetches metrics from Kubernetes https://kubernetes.io/docs/admin/kubelet/[kubelet] agent. +This module fetches metrics from Kubernetes https://kubernetes.io/docs/admin/kubelet/[kubelet] +agent and https://github.com/kubernetes/kube-state-metrics[kube-state-metrics] service. + +All metricsets with the `state_` prefix require `hosts` field pointing to kube-stat-metrics +service within the cluster, while the rest should be pointed to kubelet service. Check the +example configuration on how to do it. diff --git a/metricbeat/module/kubernetes/_meta/env b/metricbeat/module/kubernetes/_meta/env new file mode 100644 index 00000000000..b8fa8ca0a05 --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/env @@ -0,0 +1,4 @@ +KUBELET_HOST=172.17.0.1 +KUBELET_PORT=10255 +KUBE_STATE_METRICS_HOST=kube-state +KUBE_STATE_METRICS_PORT=8080 diff --git a/metricbeat/module/kubernetes/_meta/kibana/dashboard/022a54c0-2bf5-11e7-859b-f78b612cde28.json b/metricbeat/module/kubernetes/_meta/kibana/dashboard/022a54c0-2bf5-11e7-859b-f78b612cde28.json new file mode 100644 index 00000000000..a57c4a99873 --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/kibana/dashboard/022a54c0-2bf5-11e7-859b-f78b612cde28.json @@ -0,0 +1,13 @@ +{ + "hits": 0, + "timeRestore": false, + "description": "", + "title": "Kubernetes overview", + "uiStateJSON": "{}", + "panelsJSON": "[{\"col\":7,\"id\":\"022a54c0-2bf5-11e7-859b-f78b612cde28\",\"panelIndex\":1,\"row\":1,\"size_x\":6,\"size_y\":3,\"type\":\"visualization\"},{\"col\":1,\"id\":\"44f12b40-2bf4-11e7-859b-f78b612cde28\",\"panelIndex\":2,\"row\":7,\"size_x\":6,\"size_y\":3,\"type\":\"visualization\"},{\"col\":4,\"id\":\"cd059410-2bfb-11e7-859b-f78b612cde28\",\"panelIndex\":5,\"row\":1,\"size_x\":3,\"size_y\":3,\"type\":\"visualization\"},{\"col\":1,\"id\":\"e1018b90-2bfb-11e7-859b-f78b612cde28\",\"panelIndex\":6,\"row\":4,\"size_x\":2,\"size_y\":3,\"type\":\"visualization\"},{\"col\":7,\"id\":\"d6564360-2bfc-11e7-859b-f78b612cde28\",\"panelIndex\":7,\"row\":7,\"size_x\":6,\"size_y\":3,\"type\":\"visualization\"},{\"col\":7,\"id\":\"16fa4470-2bfd-11e7-859b-f78b612cde28\",\"panelIndex\":8,\"row\":10,\"size_x\":6,\"size_y\":3,\"type\":\"visualization\"},{\"col\":1,\"id\":\"294546b0-30d6-11e7-8df8-6d3604a72912\",\"panelIndex\":9,\"row\":10,\"size_x\":6,\"size_y\":3,\"type\":\"visualization\"},{\"col\":1,\"id\":\"408fccf0-30d6-11e7-8df8-6d3604a72912\",\"panelIndex\":10,\"row\":1,\"size_x\":3,\"size_y\":3,\"type\":\"visualization\"},{\"col\":1,\"id\":\"58e644f0-30d6-11e7-8df8-6d3604a72912\",\"panelIndex\":11,\"row\":13,\"size_x\":6,\"size_y\":3,\"type\":\"visualization\"},{\"col\":7,\"id\":\"a4c9d360-30df-11e7-8df8-6d3604a72912\",\"panelIndex\":12,\"row\":13,\"size_x\":6,\"size_y\":3,\"type\":\"visualization\"},{\"col\":5,\"id\":\"174a6ad0-30e0-11e7-8df8-6d3604a72912\",\"panelIndex\":13,\"row\":4,\"size_x\":2,\"size_y\":3,\"type\":\"visualization\"},{\"col\":7,\"id\":\"7aac4fd0-30e0-11e7-8df8-6d3604a72912\",\"panelIndex\":14,\"row\":4,\"size_x\":6,\"size_y\":3,\"type\":\"visualization\"},{\"col\":3,\"id\":\"da1ff7c0-30ed-11e7-b9e5-2b5b07213ab3\",\"panelIndex\":15,\"row\":4,\"size_x\":2,\"size_y\":3,\"type\":\"visualization\"}]", + "optionsJSON": "{\"darkTheme\":false}", + "version": 1, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"filter\":[{\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"*\"}}}],\"highlightAll\":true,\"version\":true}" + } +} \ No newline at end of file diff --git a/metricbeat/module/kubernetes/_meta/kibana/dashboard/a6515dc0-2bfd-11e7-b842-61c225fba0d6.json b/metricbeat/module/kubernetes/_meta/kibana/dashboard/a6515dc0-2bfd-11e7-b842-61c225fba0d6.json deleted file mode 100644 index 7a4d71830e3..00000000000 --- a/metricbeat/module/kubernetes/_meta/kibana/dashboard/a6515dc0-2bfd-11e7-b842-61c225fba0d6.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "hits": 0, - "timeRestore": false, - "description": "", - "title": "Kubernetes overview", - "uiStateJSON": "{}", - "panelsJSON": "[{\"size_x\":6,\"size_y\":3,\"panelIndex\":1,\"type\":\"visualization\",\"id\":\"022a54c0-2bf5-11e7-859b-f78b612cde28\",\"col\":1,\"row\":1},{\"size_x\":6,\"size_y\":3,\"panelIndex\":2,\"type\":\"visualization\",\"id\":\"44f12b40-2bf4-11e7-859b-f78b612cde28\",\"col\":7,\"row\":1},{\"size_x\":6,\"size_y\":3,\"panelIndex\":5,\"type\":\"visualization\",\"id\":\"cd059410-2bfb-11e7-859b-f78b612cde28\",\"col\":1,\"row\":4},{\"size_x\":6,\"size_y\":3,\"panelIndex\":6,\"type\":\"visualization\",\"id\":\"e1018b90-2bfb-11e7-859b-f78b612cde28\",\"col\":7,\"row\":4},{\"size_x\":6,\"size_y\":3,\"panelIndex\":7,\"type\":\"visualization\",\"id\":\"d6564360-2bfc-11e7-859b-f78b612cde28\",\"col\":1,\"row\":7},{\"size_x\":6,\"size_y\":3,\"panelIndex\":8,\"type\":\"visualization\",\"id\":\"16fa4470-2bfd-11e7-859b-f78b612cde28\",\"col\":7,\"row\":7}]", - "optionsJSON": "{\"darkTheme\":false}", - "version": 1, - "kibanaSavedObjectMeta": { - "searchSourceJSON": "{\"filter\":[{\"query\":{\"query_string\":{\"query\":\"*\"}}}],\"highlightAll\":true,\"version\":true}" - } -} \ No newline at end of file diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/022a54c0-2bf5-11e7-859b-f78b612cde28.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/022a54c0-2bf5-11e7-859b-f78b612cde28.json index 894a42a3c58..fd611f8377d 100644 --- a/metricbeat/module/kubernetes/_meta/kibana/visualization/022a54c0-2bf5-11e7-859b-f78b612cde28.json +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/022a54c0-2bf5-11e7-859b-f78b612cde28.json @@ -1,7 +1,7 @@ { - "visState": "{\"title\":\"Kubernetes - CPU usage by namespace\",\"type\":\"metrics\",\"params\":{\"id\":\"0d5c6b10-2bf2-11e7-859b-f78b612cde28\",\"type\":\"timeseries\",\"series\":[{\"id\":\"0d5c9220-2bf2-11e7-859b-f78b612cde28\",\"color\":\"#68BC00\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.container.cpu.usage.core.ns\"},{\"unit\":\"\",\"id\":\"cce16e70-2bf4-11e7-859b-f78b612cde28\",\"type\":\"derivative\",\"field\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"0.0 a\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":\"0.5\",\"stacked\":\"stacked\",\"terms_field\":\"kubernetes.namespace\",\"terms_size\":\"100000\",\"terms_order_by\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"value_template\":\"{{value}} ns\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"12c1f2f0-2bf2-11e7-859b-f78b612cde28\"}],\"bar_color_rules\":[{\"id\":\"1373ddd0-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_color_rules\":[{\"id\":\"140e4910-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\",\"filter\":\"metricset.module:kubernetes AND metricset.name:container\"},\"aggs\":[],\"listeners\":{}}", + "visState": "{\"title\":\"Kubernetes - Available pods per deployment\",\"type\":\"metrics\",\"params\":{\"axis_formatter\":\"number\",\"axis_position\":\"left\",\"filter\":\"metricset.module:kubernetes AND metricset.name:state_deployment\",\"id\":\"117fadf0-30df-11e7-8df8-6d3604a72912\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"series\":[{\"axis_position\":\"right\",\"chart_type\":\"line\",\"color\":\"rgba(104,188,0,1)\",\"fill\":0.5,\"formatter\":\"number\",\"id\":\"64456840-30df-11e7-8df8-6d3604a72912\",\"label\":\"Available pods\",\"line_width\":1,\"metrics\":[{\"field\":\"kubernetes.deployment.replicas.available\",\"id\":\"64456841-30df-11e7-8df8-6d3604a72912\",\"type\":\"sum\"}],\"point_size\":1,\"seperate_axis\":0,\"split_filters\":[{\"color\":\"#68BC00\",\"id\":\"53d35ad0-30df-11e7-8df8-6d3604a72912\"}],\"split_mode\":\"terms\",\"stacked\":\"stacked\",\"terms_field\":\"kubernetes.deployment.name\",\"terms_size\":\"10000\"}],\"show_legend\":1,\"time_field\":\"@timestamp\",\"type\":\"timeseries\"},\"aggs\":[],\"listeners\":{}}", "description": "", - "title": "Kubernetes - CPU usage by namespace", + "title": "Kubernetes - Available pods per deployment", "uiStateJSON": "{}", "version": 1, "kibanaSavedObjectMeta": { diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/16fa4470-2bfd-11e7-859b-f78b612cde28.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/16fa4470-2bfd-11e7-859b-f78b612cde28.json index 1559f5cda6f..b2d42ee9228 100644 --- a/metricbeat/module/kubernetes/_meta/kibana/visualization/16fa4470-2bfd-11e7-859b-f78b612cde28.json +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/16fa4470-2bfd-11e7-859b-f78b612cde28.json @@ -1,7 +1,7 @@ { - "visState": "{\"title\":\"Top memory intensive pods\",\"type\":\"metrics\",\"params\":{\"id\":\"5d3692a0-2bfc-11e7-859b-f78b612cde28\",\"type\":\"top_n\",\"series\":[{\"id\":\"5d3692a1-2bfc-11e7-859b-f78b612cde28\",\"color\":\"#68BC00\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.container.memory.usage.bytes\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"bytes\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"terms_field\":\"kubernetes.pod.name\",\"terms_order_by\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\",\"value_template\":\"\",\"offset_time\":\"\",\"override_index_pattern\":0}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"bar_color_rules\":[{\"id\":\"802104d0-2bfc-11e7-859b-f78b612cde28\"}],\"filter\":\"metricset.module:kubernetes AND metricset.name:container\"},\"aggs\":[],\"listeners\":{}}", + "visState": "{\"title\":\"Kubernetes - Network in by node\",\"type\":\"metrics\",\"params\":{\"id\":\"0d5c6b10-2bf2-11e7-859b-f78b612cde28\",\"type\":\"timeseries\",\"series\":[{\"id\":\"0d5c9220-2bf2-11e7-859b-f78b612cde28\",\"color\":\"rgba(104,188,0,1)\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.pod.network.rx.bytes\"},{\"unit\":\"\",\"id\":\"494fc310-2bf7-11e7-859b-f78b612cde28\",\"type\":\"derivative\",\"field\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\"},{\"unit\":\"\",\"id\":\"37c72a70-3598-11e7-aa4a-8313a0c92a88\",\"type\":\"positive_only\",\"field\":\"494fc310-2bf7-11e7-859b-f78b612cde28\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"bytes\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"stacked\",\"terms_field\":\"kubernetes.node.name\",\"terms_size\":\"100000\",\"terms_order_by\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"label\":\"\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"12c1f2f0-2bf2-11e7-859b-f78b612cde28\"}],\"bar_color_rules\":[{\"id\":\"1373ddd0-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_color_rules\":[{\"id\":\"140e4910-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\",\"filter\":\"metricset.module:kubernetes AND metricset.name:pod\"},\"aggs\":[],\"listeners\":{}}", "description": "", - "title": "Top memory intensive pods", + "title": "Kubernetes - Network in by node", "uiStateJSON": "{}", "version": 1, "kibanaSavedObjectMeta": { diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/174a6ad0-30e0-11e7-8df8-6d3604a72912.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/174a6ad0-30e0-11e7-8df8-6d3604a72912.json new file mode 100644 index 00000000000..21f0e5eb0c3 --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/174a6ad0-30e0-11e7-8df8-6d3604a72912.json @@ -0,0 +1,10 @@ +{ + "visState": "{\"title\":\"Kubernetes - Unavailable pods\",\"type\":\"metrics\",\"params\":{\"id\":\"2fe9d3b0-30d5-11e7-8df8-6d3604a72912\",\"type\":\"metric\",\"series\":[{\"id\":\"2fe9d3b1-30d5-11e7-8df8-6d3604a72912\",\"color\":\"#68BC00\",\"split_mode\":\"everything\",\"metrics\":[{\"id\":\"54cf79a0-30d5-11e7-8df8-6d3604a72912\",\"type\":\"sum\",\"field\":\"kubernetes.deployment.replicas.unavailable\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"number\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"label\":\"Unavailable Pods\",\"override_index_pattern\":1,\"series_interval\":\"10s\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"508ffb30-30d5-11e7-8df8-6d3604a72912\"}],\"gauge_color_rules\":[{\"id\":\"50f9b980-30d5-11e7-8df8-6d3604a72912\"}],\"gauge_width\":\"10\",\"gauge_inner_width\":\"10\",\"gauge_style\":\"half\",\"bar_color_rules\":[{\"id\":\"674d83b0-30d5-11e7-8df8-6d3604a72912\"}],\"gauge_max\":\"\",\"filter\":\"metricset.module:kubernetes AND metricset.name:state_deployment\"},\"aggs\":[],\"listeners\":{}}", + "description": "", + "title": "Kubernetes - Unavailable pods", + "uiStateJSON": "{}", + "version": 1, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"query\":{\"query_string\":{\"query\":\"*\"}},\"filter\":[]}" + } +} \ No newline at end of file diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/294546b0-30d6-11e7-8df8-6d3604a72912.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/294546b0-30d6-11e7-8df8-6d3604a72912.json new file mode 100644 index 00000000000..3795050d125 --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/294546b0-30d6-11e7-8df8-6d3604a72912.json @@ -0,0 +1,10 @@ +{ + "visState": "{\"title\":\"Kubernetes - Network out by node\",\"type\":\"metrics\",\"params\":{\"id\":\"0d5c6b10-2bf2-11e7-859b-f78b612cde28\",\"type\":\"timeseries\",\"series\":[{\"id\":\"0d5c9220-2bf2-11e7-859b-f78b612cde28\",\"color\":\"rgba(104,188,0,1)\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.pod.network.tx.bytes\"},{\"unit\":\"\",\"id\":\"494fc310-2bf7-11e7-859b-f78b612cde28\",\"type\":\"derivative\",\"field\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\"},{\"unit\":\"\",\"id\":\"244c70e0-3598-11e7-aa4a-8313a0c92a88\",\"type\":\"positive_only\",\"field\":\"494fc310-2bf7-11e7-859b-f78b612cde28\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"bytes\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"stacked\",\"terms_field\":\"kubernetes.node.name\",\"terms_size\":\"10000\",\"terms_order_by\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"label\":\"\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"12c1f2f0-2bf2-11e7-859b-f78b612cde28\"}],\"bar_color_rules\":[{\"id\":\"1373ddd0-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_color_rules\":[{\"id\":\"140e4910-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\",\"filter\":\"metricset.module:kubernetes AND metricset.name:pod\"},\"aggs\":[],\"listeners\":{}}", + "description": "", + "title": "Kubernetes - Network out by node", + "uiStateJSON": "{}", + "version": 1, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"query\":{\"query_string\":{\"query\":\"*\"}},\"filter\":[]}" + } +} \ No newline at end of file diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/408fccf0-30d6-11e7-8df8-6d3604a72912.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/408fccf0-30d6-11e7-8df8-6d3604a72912.json new file mode 100644 index 00000000000..72e4f0ce2b4 --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/408fccf0-30d6-11e7-8df8-6d3604a72912.json @@ -0,0 +1,10 @@ +{ + "visState": "{\"title\":\"Kubernetes - Nodes\",\"type\":\"metrics\",\"params\":{\"id\":\"4c4690b0-30e0-11e7-8df8-6d3604a72912\",\"type\":\"metric\",\"series\":[{\"id\":\"4c4690b1-30e0-11e7-8df8-6d3604a72912\",\"color\":\"#68BC00\",\"split_mode\":\"everything\",\"metrics\":[{\"id\":\"4c4690b2-30e0-11e7-8df8-6d3604a72912\",\"type\":\"cardinality\",\"field\":\"kubernetes.node.name\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"number\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"terms_field\":\"kubernetes.deployment.name\",\"label\":\"Nodes\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"filter\":\"metricset.module:kubernetes AND metricset.name:state_node\",\"background_color_rules\":[{\"id\":\"67ee7da0-30e0-11e7-8df8-6d3604a72912\"}],\"bar_color_rules\":[{\"id\":\"68cdba10-30e0-11e7-8df8-6d3604a72912\"}],\"gauge_color_rules\":[{\"id\":\"69765620-30e0-11e7-8df8-6d3604a72912\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\"},\"aggs\":[],\"listeners\":{}}", + "description": "", + "title": "Kubernetes - Nodes", + "uiStateJSON": "{}", + "version": 1, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"query\":{\"query_string\":{\"query\":\"*\"}},\"filter\":[]}" + } +} \ No newline at end of file diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/44f12b40-2bf4-11e7-859b-f78b612cde28.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/44f12b40-2bf4-11e7-859b-f78b612cde28.json index 9657c19d01f..78ea87a43f9 100644 --- a/metricbeat/module/kubernetes/_meta/kibana/visualization/44f12b40-2bf4-11e7-859b-f78b612cde28.json +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/44f12b40-2bf4-11e7-859b-f78b612cde28.json @@ -1,7 +1,7 @@ { - "visState": "{\"title\":\"Kubernetes - Memory usage by namespace\",\"type\":\"metrics\",\"params\":{\"id\":\"0d5c6b10-2bf2-11e7-859b-f78b612cde28\",\"type\":\"timeseries\",\"series\":[{\"id\":\"0d5c9220-2bf2-11e7-859b-f78b612cde28\",\"color\":\"#68BC00\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.container.memory.usage.bytes\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"bytes\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"stacked\",\"terms_field\":\"kubernetes.namespace\",\"terms_size\":\"100000\",\"terms_order_by\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"12c1f2f0-2bf2-11e7-859b-f78b612cde28\"}],\"bar_color_rules\":[{\"id\":\"1373ddd0-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_color_rules\":[{\"id\":\"140e4910-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\",\"filter\":\"metricset.module:kubernetes AND metricset.name:container\"},\"aggs\":[],\"listeners\":{}}", + "visState": "{\"title\":\"Kubernetes - CPU usage by node\",\"type\":\"metrics\",\"params\":{\"id\":\"0d5c6b10-2bf2-11e7-859b-f78b612cde28\",\"type\":\"timeseries\",\"series\":[{\"id\":\"0d5c9220-2bf2-11e7-859b-f78b612cde28\",\"color\":\"#68BC00\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.container.cpu.usage.nanocores\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"0.0a\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":\"0.5\",\"stacked\":\"none\",\"terms_field\":\"kubernetes.node.name\",\"terms_size\":\"10000\",\"terms_order_by\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"value_template\":\"{{value}} nanocores\",\"override_index_pattern\":0,\"series_interval\":\"10s\",\"series_time_field\":\"@timestamp\"},{\"id\":\"22f65d40-31a7-11e7-84cc-096d2b38e6e5\",\"color\":\"rgba(211,49,21,1)\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"22f65d41-31a7-11e7-84cc-096d2b38e6e5\",\"type\":\"avg\",\"field\":\"kubernetes.node.cpu.capacity.cores\"},{\"script\":\"params.cores * 1000000000\",\"id\":\"4af4c390-34d6-11e7-be88-cb6a123dc1bb\",\"type\":\"calculation\",\"variables\":[{\"id\":\"4cd32080-34d6-11e7-be88-cb6a123dc1bb\",\"name\":\"cores\",\"field\":\"22f65d41-31a7-11e7-84cc-096d2b38e6e5\"}]}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"0.0a\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":\"0\",\"fill\":\"0\",\"stacked\":\"none\",\"terms_field\":\"kubernetes.node.name\",\"terms_size\":\"10000\",\"terms_order_by\":\"22f65d41-31a7-11e7-84cc-096d2b38e6e5\",\"value_template\":\"{{value}} nanocores\",\"hide_in_legend\":1,\"label\":\"\",\"override_index_pattern\":0,\"series_interval\":\"10s\",\"series_time_field\":\"@timestamp\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"12c1f2f0-2bf2-11e7-859b-f78b612cde28\"}],\"bar_color_rules\":[{\"id\":\"1373ddd0-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_color_rules\":[{\"id\":\"140e4910-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\",\"filter\":\"metricset.module:kubernetes AND (metricset.name:container OR metricset.name:state_node)\"},\"aggs\":[],\"listeners\":{}}", "description": "", - "title": "Kubernetes - Memory usage by namespace", + "title": "Kubernetes - CPU usage by node", "uiStateJSON": "{}", "version": 1, "kibanaSavedObjectMeta": { diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/58e644f0-30d6-11e7-8df8-6d3604a72912.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/58e644f0-30d6-11e7-8df8-6d3604a72912.json new file mode 100644 index 00000000000..8a3b7af66bd --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/58e644f0-30d6-11e7-8df8-6d3604a72912.json @@ -0,0 +1,10 @@ +{ + "visState": "{\"title\":\"Kubernetes - Top CPU intensive pods\",\"type\":\"metrics\",\"params\":{\"id\":\"5d3692a0-2bfc-11e7-859b-f78b612cde28\",\"type\":\"top_n\",\"series\":[{\"id\":\"5d3692a1-2bfc-11e7-859b-f78b612cde28\",\"color\":\"#68BC00\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.container.cpu.usage.core.ns\"},{\"unit\":\"1s\",\"id\":\"6c905240-2bfc-11e7-859b-f78b612cde28\",\"type\":\"derivative\",\"field\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\"},{\"unit\":\"\",\"id\":\"9a51f710-359d-11e7-aa4a-8313a0c92a88\",\"type\":\"positive_only\",\"field\":\"6c905240-2bfc-11e7-859b-f78b612cde28\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"0.0 a\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"terms_field\":\"kubernetes.pod.name\",\"terms_order_by\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\",\"value_template\":\"{{value}} ns\",\"offset_time\":\"\",\"override_index_pattern\":0}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"bar_color_rules\":[{\"id\":\"802104d0-2bfc-11e7-859b-f78b612cde28\"}],\"filter\":\"metricset.module:kubernetes AND metricset.name:container\"},\"aggs\":[],\"listeners\":{}}", + "description": "", + "title": "Kubernetes - Top CPU intensive pods", + "uiStateJSON": "{}", + "version": 1, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"query\":{\"query_string\":{\"query\":\"*\"}},\"filter\":[]}" + } +} \ No newline at end of file diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/7aac4fd0-30e0-11e7-8df8-6d3604a72912.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/7aac4fd0-30e0-11e7-8df8-6d3604a72912.json new file mode 100644 index 00000000000..cfc7db494fd --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/7aac4fd0-30e0-11e7-8df8-6d3604a72912.json @@ -0,0 +1,10 @@ +{ + "visState": "{\"title\":\"Kubernetes - Unavailable pods per deployment\",\"type\":\"metrics\",\"params\":{\"id\":\"117fadf0-30df-11e7-8df8-6d3604a72912\",\"type\":\"timeseries\",\"series\":[{\"id\":\"64456840-30df-11e7-8df8-6d3604a72912\",\"color\":\"rgba(254,146,0,1)\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"64456841-30df-11e7-8df8-6d3604a72912\",\"type\":\"sum\",\"field\":\"kubernetes.deployment.replicas.unavailable\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"number\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"stacked\",\"split_filters\":[{\"color\":\"#68BC00\",\"id\":\"53d35ad0-30df-11e7-8df8-6d3604a72912\"}],\"terms_field\":\"kubernetes.deployment.name\",\"label\":\"Unavailable pods\",\"terms_size\":\"10000\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"filter\":\"metricset.module:kubernetes AND metricset.name:state_deployment\"},\"aggs\":[],\"listeners\":{}}", + "description": "", + "title": "Kubernetes - Unavailable pods per deployment", + "uiStateJSON": "{}", + "version": 1, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"query\":{\"query_string\":{\"query\":\"*\"}},\"filter\":[]}" + } +} \ No newline at end of file diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/a4c9d360-30df-11e7-8df8-6d3604a72912.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/a4c9d360-30df-11e7-8df8-6d3604a72912.json new file mode 100644 index 00000000000..1000a1d7a71 --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/a4c9d360-30df-11e7-8df8-6d3604a72912.json @@ -0,0 +1,10 @@ +{ + "visState": "{\"title\":\"Kubernetes - Top memory intensive pods\",\"type\":\"metrics\",\"params\":{\"id\":\"5d3692a0-2bfc-11e7-859b-f78b612cde28\",\"type\":\"top_n\",\"series\":[{\"id\":\"5d3692a1-2bfc-11e7-859b-f78b612cde28\",\"color\":\"#68BC00\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.container.memory.usage.bytes\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"bytes\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"terms_field\":\"kubernetes.pod.name\",\"terms_order_by\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\",\"value_template\":\"\",\"offset_time\":\"\",\"override_index_pattern\":0,\"terms_size\":\"10\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"bar_color_rules\":[{\"id\":\"802104d0-2bfc-11e7-859b-f78b612cde28\"}],\"filter\":\"metricset.module:kubernetes AND metricset.name:container\"},\"aggs\":[],\"listeners\":{}}", + "description": "", + "title": "Kubernetes - Top memory intensive pods", + "uiStateJSON": "{}", + "version": 1, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"query\":{\"query_string\":{\"query\":\"*\"}},\"filter\":[]}" + } +} \ No newline at end of file diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/cd059410-2bfb-11e7-859b-f78b612cde28.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/cd059410-2bfb-11e7-859b-f78b612cde28.json index e29ffa69848..53335b02fb3 100644 --- a/metricbeat/module/kubernetes/_meta/kibana/visualization/cd059410-2bfb-11e7-859b-f78b612cde28.json +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/cd059410-2bfb-11e7-859b-f78b612cde28.json @@ -1,7 +1,7 @@ { - "visState": "{\"title\":\"Kubernetes - Network in by namespace\",\"type\":\"metrics\",\"params\":{\"id\":\"0d5c6b10-2bf2-11e7-859b-f78b612cde28\",\"type\":\"timeseries\",\"series\":[{\"id\":\"0d5c9220-2bf2-11e7-859b-f78b612cde28\",\"color\":\"rgba(104,188,0,1)\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.pod.network.rx.bytes\"},{\"unit\":\"\",\"id\":\"494fc310-2bf7-11e7-859b-f78b612cde28\",\"type\":\"derivative\",\"field\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"bytes\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"stacked\",\"terms_field\":\"kubernetes.namespace\",\"terms_size\":\"100000\",\"terms_order_by\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"label\":\"\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"12c1f2f0-2bf2-11e7-859b-f78b612cde28\"}],\"bar_color_rules\":[{\"id\":\"1373ddd0-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_color_rules\":[{\"id\":\"140e4910-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\",\"filter\":\"metricset.module:kubernetes AND metricset.name:pod\"},\"aggs\":[],\"listeners\":{}}", + "visState": "{\"title\":\"Kubernetes - Deployments\",\"type\":\"metrics\",\"params\":{\"id\":\"4c4690b0-30e0-11e7-8df8-6d3604a72912\",\"type\":\"metric\",\"series\":[{\"id\":\"4c4690b1-30e0-11e7-8df8-6d3604a72912\",\"color\":\"#68BC00\",\"split_mode\":\"everything\",\"metrics\":[{\"id\":\"4c4690b2-30e0-11e7-8df8-6d3604a72912\",\"type\":\"cardinality\",\"field\":\"kubernetes.deployment.name\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"number\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"terms_field\":\"kubernetes.deployment.name\",\"label\":\"Deployments\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"filter\":\"metricset.module:kubernetes AND metricset.name:state_deployment\",\"background_color_rules\":[{\"id\":\"67ee7da0-30e0-11e7-8df8-6d3604a72912\"}],\"bar_color_rules\":[{\"id\":\"68cdba10-30e0-11e7-8df8-6d3604a72912\"}],\"gauge_color_rules\":[{\"id\":\"69765620-30e0-11e7-8df8-6d3604a72912\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\"},\"aggs\":[],\"listeners\":{}}", "description": "", - "title": "Kubernetes - Network in by namespace", + "title": "Kubernetes - Deployments", "uiStateJSON": "{}", "version": 1, "kibanaSavedObjectMeta": { diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/d6564360-2bfc-11e7-859b-f78b612cde28.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/d6564360-2bfc-11e7-859b-f78b612cde28.json index e8808a434b3..79874a359bd 100644 --- a/metricbeat/module/kubernetes/_meta/kibana/visualization/d6564360-2bfc-11e7-859b-f78b612cde28.json +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/d6564360-2bfc-11e7-859b-f78b612cde28.json @@ -1,7 +1,7 @@ { - "visState": "{\"title\":\"Top CPU intensive pods\",\"type\":\"metrics\",\"params\":{\"id\":\"5d3692a0-2bfc-11e7-859b-f78b612cde28\",\"type\":\"top_n\",\"series\":[{\"id\":\"5d3692a1-2bfc-11e7-859b-f78b612cde28\",\"color\":\"#68BC00\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.container.cpu.usage.core.ns\"},{\"unit\":\"\",\"id\":\"6c905240-2bfc-11e7-859b-f78b612cde28\",\"type\":\"derivative\",\"field\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"0.0 a\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"terms_field\":\"kubernetes.pod.name\",\"terms_order_by\":\"5d3692a2-2bfc-11e7-859b-f78b612cde28\",\"value_template\":\"{{value}} ns\",\"offset_time\":\"\",\"override_index_pattern\":0}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"bar_color_rules\":[{\"id\":\"802104d0-2bfc-11e7-859b-f78b612cde28\"}],\"filter\":\"metricset.module:kubernetes AND metricset.name:container\"},\"aggs\":[],\"listeners\":{}}", + "visState": "{\"title\":\"Kubernetes - Memory usage by node\",\"type\":\"metrics\",\"params\":{\"id\":\"0d5c6b10-2bf2-11e7-859b-f78b612cde28\",\"type\":\"timeseries\",\"series\":[{\"id\":\"0d5c9220-2bf2-11e7-859b-f78b612cde28\",\"color\":\"#68BC00\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.container.memory.usage.bytes\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"bytes\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"terms_field\":\"kubernetes.node.name\",\"terms_size\":\"10000\",\"terms_order_by\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\"},{\"id\":\"8ba3b270-31a7-11e7-84cc-096d2b38e6e5\",\"color\":\"rgba(211,49,21,1)\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"8ba3b271-31a7-11e7-84cc-096d2b38e6e5\",\"type\":\"sum\",\"field\":\"kubernetes.node.memory.capacity.bytes\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"bytes\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":\"0\",\"fill\":\"0\",\"stacked\":\"none\",\"terms_field\":\"kubernetes.node.name\",\"terms_size\":\"10000\",\"terms_order_by\":\"8ba3b271-31a7-11e7-84cc-096d2b38e6e5\",\"hide_in_legend\":1,\"label\":\"Node capacity\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"12c1f2f0-2bf2-11e7-859b-f78b612cde28\"}],\"bar_color_rules\":[{\"id\":\"1373ddd0-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_color_rules\":[{\"id\":\"140e4910-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\",\"filter\":\"metricset.module:kubernetes AND (metricset.name:container OR metricset.name:state_node)\"},\"aggs\":[],\"listeners\":{}}", "description": "", - "title": "Top CPU intensive pods", + "title": "Kubernetes - Memory usage by node", "uiStateJSON": "{}", "version": 1, "kibanaSavedObjectMeta": { diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/da1ff7c0-30ed-11e7-b9e5-2b5b07213ab3.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/da1ff7c0-30ed-11e7-b9e5-2b5b07213ab3.json new file mode 100644 index 00000000000..9e58312a3bb --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/da1ff7c0-30ed-11e7-b9e5-2b5b07213ab3.json @@ -0,0 +1,10 @@ +{ + "visState": "{\"title\":\"Kubernetes - Available pods\",\"type\":\"metrics\",\"params\":{\"id\":\"2fe9d3b0-30d5-11e7-8df8-6d3604a72912\",\"type\":\"metric\",\"series\":[{\"id\":\"2fe9d3b1-30d5-11e7-8df8-6d3604a72912\",\"color\":\"#68BC00\",\"split_mode\":\"everything\",\"metrics\":[{\"id\":\"54cf79a0-30d5-11e7-8df8-6d3604a72912\",\"type\":\"sum\",\"field\":\"kubernetes.deployment.replicas.available\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"number\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"label\":\"Available Pods\",\"override_index_pattern\":1,\"series_time_field\":\"@timestamp\",\"series_index_pattern\":\"*\",\"series_interval\":\"10s\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"508ffb30-30d5-11e7-8df8-6d3604a72912\"}],\"gauge_color_rules\":[{\"id\":\"50f9b980-30d5-11e7-8df8-6d3604a72912\"}],\"gauge_width\":\"10\",\"gauge_inner_width\":\"10\",\"gauge_style\":\"half\",\"bar_color_rules\":[{\"id\":\"674d83b0-30d5-11e7-8df8-6d3604a72912\"}],\"gauge_max\":\"5\",\"filter\":\"metricset.module:kubernetes AND metricset.name:state_deployment\"},\"aggs\":[],\"listeners\":{}}", + "description": "", + "title": "Kubernetes - Available pods", + "uiStateJSON": "{}", + "version": 1, + "kibanaSavedObjectMeta": { + "searchSourceJSON": "{\"query\":{\"query_string\":{\"query\":\"*\"}},\"filter\":[]}" + } +} \ No newline at end of file diff --git a/metricbeat/module/kubernetes/_meta/kibana/visualization/e1018b90-2bfb-11e7-859b-f78b612cde28.json b/metricbeat/module/kubernetes/_meta/kibana/visualization/e1018b90-2bfb-11e7-859b-f78b612cde28.json index 3e59113a739..83e8aefd0e8 100644 --- a/metricbeat/module/kubernetes/_meta/kibana/visualization/e1018b90-2bfb-11e7-859b-f78b612cde28.json +++ b/metricbeat/module/kubernetes/_meta/kibana/visualization/e1018b90-2bfb-11e7-859b-f78b612cde28.json @@ -1,7 +1,7 @@ { - "visState": "{\"title\":\"Kubernetes - Network out by namespace\",\"type\":\"metrics\",\"params\":{\"id\":\"0d5c6b10-2bf2-11e7-859b-f78b612cde28\",\"type\":\"timeseries\",\"series\":[{\"id\":\"0d5c9220-2bf2-11e7-859b-f78b612cde28\",\"color\":\"rgba(104,188,0,1)\",\"split_mode\":\"terms\",\"metrics\":[{\"id\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"type\":\"sum\",\"field\":\"kubernetes.pod.network.tx.bytes\"},{\"unit\":\"\",\"id\":\"494fc310-2bf7-11e7-859b-f78b612cde28\",\"type\":\"derivative\",\"field\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"bytes\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"stacked\",\"terms_field\":\"kubernetes.namespace\",\"terms_size\":\"100000\",\"terms_order_by\":\"0d5c9221-2bf2-11e7-859b-f78b612cde28\",\"label\":\"\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"12c1f2f0-2bf2-11e7-859b-f78b612cde28\"}],\"bar_color_rules\":[{\"id\":\"1373ddd0-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_color_rules\":[{\"id\":\"140e4910-2bf2-11e7-859b-f78b612cde28\"}],\"gauge_width\":10,\"gauge_inner_width\":10,\"gauge_style\":\"half\",\"filter\":\"metricset.module:kubernetes AND metricset.name:pod\"},\"aggs\":[],\"listeners\":{}}", + "visState": "{\"title\":\"Kubernetes - Desired pods\",\"type\":\"metrics\",\"params\":{\"id\":\"2fe9d3b0-30d5-11e7-8df8-6d3604a72912\",\"type\":\"metric\",\"series\":[{\"id\":\"2fe9d3b1-30d5-11e7-8df8-6d3604a72912\",\"color\":\"#68BC00\",\"split_mode\":\"everything\",\"metrics\":[{\"id\":\"54cf79a0-30d5-11e7-8df8-6d3604a72912\",\"type\":\"sum\",\"field\":\"kubernetes.deployment.replicas.desired\"}],\"seperate_axis\":0,\"axis_position\":\"right\",\"formatter\":\"number\",\"chart_type\":\"line\",\"line_width\":1,\"point_size\":1,\"fill\":0.5,\"stacked\":\"none\",\"label\":\"Desired Pods\",\"override_index_pattern\":1,\"series_time_field\":\"@timestamp\",\"series_interval\":\"10s\"}],\"time_field\":\"@timestamp\",\"index_pattern\":\"*\",\"interval\":\"auto\",\"axis_position\":\"left\",\"axis_formatter\":\"number\",\"show_legend\":1,\"background_color_rules\":[{\"id\":\"508ffb30-30d5-11e7-8df8-6d3604a72912\"}],\"gauge_color_rules\":[{\"id\":\"50f9b980-30d5-11e7-8df8-6d3604a72912\"}],\"gauge_width\":\"10\",\"gauge_inner_width\":\"10\",\"gauge_style\":\"half\",\"bar_color_rules\":[{\"id\":\"674d83b0-30d5-11e7-8df8-6d3604a72912\"}],\"gauge_max\":\"5\",\"filter\":\"metricset.module:kubernetes AND metricset.name:state_deployment\"},\"aggs\":[],\"listeners\":{}}", "description": "", - "title": "Kubernetes - Network out by namespace", + "title": "Kubernetes - Desired pods", "uiStateJSON": "{}", "version": 1, "kibanaSavedObjectMeta": { diff --git a/metricbeat/module/kubernetes/_meta/kubeconfig b/metricbeat/module/kubernetes/_meta/kubeconfig new file mode 100644 index 00000000000..cad24101463 --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/kubeconfig @@ -0,0 +1,18 @@ +apiVersion: v1 +clusters: +- cluster: + server: http://172.17.0.1:8080 + name: kubernetes +contexts: +- context: + cluster: kubernetes + user: kubernetes + name: kubernetes +current-context: kubernetes +kind: Config +preferences: {} +users: +- name: kubernetes + user: + client-certificate: + client-key: diff --git a/metricbeat/module/kubernetes/_meta/test/kube-state-metrics b/metricbeat/module/kubernetes/_meta/test/kube-state-metrics new file mode 100644 index 00000000000..c57b44e29bb --- /dev/null +++ b/metricbeat/module/kubernetes/_meta/test/kube-state-metrics @@ -0,0 +1,386 @@ +# HELP go_gc_duration_seconds A summary of the GC invocation durations. +# TYPE go_gc_duration_seconds summary +go_gc_duration_seconds{quantile="0"} 5.4333e-05 +go_gc_duration_seconds{quantile="0.25"} 0.000246606 +go_gc_duration_seconds{quantile="0.5"} 0.0006209060000000001 +go_gc_duration_seconds{quantile="0.75"} 0.001966929 +go_gc_duration_seconds{quantile="1"} 0.09220378600000001 +go_gc_duration_seconds_sum 5.104380396 +go_gc_duration_seconds_count 651 +# HELP go_goroutines Number of goroutines that currently exist. +# TYPE go_goroutines gauge +go_goroutines 64 +# HELP go_memstats_alloc_bytes Number of bytes allocated and still in use. +# TYPE go_memstats_alloc_bytes gauge +go_memstats_alloc_bytes 5.142496e+06 +# HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed. +# TYPE go_memstats_alloc_bytes_total counter +go_memstats_alloc_bytes_total 2.375809288e+09 +# HELP go_memstats_buck_hash_sys_bytes Number of bytes used by the profiling bucket hash table. +# TYPE go_memstats_buck_hash_sys_bytes gauge +go_memstats_buck_hash_sys_bytes 1.516515e+06 +# HELP go_memstats_frees_total Total number of frees. +# TYPE go_memstats_frees_total counter +go_memstats_frees_total 1.7162925e+07 +# HELP go_memstats_gc_sys_bytes Number of bytes used for garbage collection system metadata. +# TYPE go_memstats_gc_sys_bytes gauge +go_memstats_gc_sys_bytes 1.273856e+06 +# HELP go_memstats_heap_alloc_bytes Number of heap bytes allocated and still in use. +# TYPE go_memstats_heap_alloc_bytes gauge +go_memstats_heap_alloc_bytes 5.142496e+06 +# HELP go_memstats_heap_idle_bytes Number of heap bytes waiting to be used. +# TYPE go_memstats_heap_idle_bytes gauge +go_memstats_heap_idle_bytes 1.14688e+07 +# HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use. +# TYPE go_memstats_heap_inuse_bytes gauge +go_memstats_heap_inuse_bytes 7.176192e+06 +# HELP go_memstats_heap_objects Number of allocated objects. +# TYPE go_memstats_heap_objects gauge +go_memstats_heap_objects 32950 +# HELP go_memstats_heap_released_bytes_total Total number of heap bytes released to OS. +# TYPE go_memstats_heap_released_bytes_total counter +go_memstats_heap_released_bytes_total 0 +# HELP go_memstats_heap_sys_bytes Number of heap bytes obtained from system. +# TYPE go_memstats_heap_sys_bytes gauge +go_memstats_heap_sys_bytes 1.8644992e+07 +# HELP go_memstats_last_gc_time_seconds Number of seconds since 1970 of last garbage collection. +# TYPE go_memstats_last_gc_time_seconds gauge +go_memstats_last_gc_time_seconds 1.4939767617562683e+09 +# HELP go_memstats_lookups_total Total number of pointer lookups. +# TYPE go_memstats_lookups_total counter +go_memstats_lookups_total 18621 +# HELP go_memstats_mallocs_total Total number of mallocs. +# TYPE go_memstats_mallocs_total counter +go_memstats_mallocs_total 1.7195875e+07 +# HELP go_memstats_mcache_inuse_bytes Number of bytes in use by mcache structures. +# TYPE go_memstats_mcache_inuse_bytes gauge +go_memstats_mcache_inuse_bytes 2400 +# HELP go_memstats_mcache_sys_bytes Number of bytes used for mcache structures obtained from system. +# TYPE go_memstats_mcache_sys_bytes gauge +go_memstats_mcache_sys_bytes 16384 +# HELP go_memstats_mspan_inuse_bytes Number of bytes in use by mspan structures. +# TYPE go_memstats_mspan_inuse_bytes gauge +go_memstats_mspan_inuse_bytes 98400 +# HELP go_memstats_mspan_sys_bytes Number of bytes used for mspan structures obtained from system. +# TYPE go_memstats_mspan_sys_bytes gauge +go_memstats_mspan_sys_bytes 114688 +# HELP go_memstats_next_gc_bytes Number of heap bytes when next garbage collection will take place. +# TYPE go_memstats_next_gc_bytes gauge +go_memstats_next_gc_bytes 7.698843e+06 +# HELP go_memstats_other_sys_bytes Number of bytes used for other system allocations. +# TYPE go_memstats_other_sys_bytes gauge +go_memstats_other_sys_bytes 574741 +# HELP go_memstats_stack_inuse_bytes Number of bytes in use by the stack allocator. +# TYPE go_memstats_stack_inuse_bytes gauge +go_memstats_stack_inuse_bytes 4.42368e+06 +# HELP go_memstats_stack_sys_bytes Number of bytes obtained from system for stack allocator. +# TYPE go_memstats_stack_sys_bytes gauge +go_memstats_stack_sys_bytes 4.42368e+06 +# HELP go_memstats_sys_bytes Number of bytes obtained by system. Sum of all system allocations. +# TYPE go_memstats_sys_bytes gauge +go_memstats_sys_bytes 2.6564856e+07 +# HELP kube_deployment_metadata_generation Sequence number representing a specific generation of the desired state. +# TYPE kube_deployment_metadata_generation gauge +kube_deployment_metadata_generation{deployment="jumpy-owl-redis",namespace="default"} 1 +kube_deployment_metadata_generation{deployment="kube-state-metrics",namespace="kube-system"} 1 +kube_deployment_metadata_generation{deployment="tiller-deploy",namespace="kube-system"} 1 +kube_deployment_metadata_generation{deployment="wise-lynx-jenkins",namespace="jenkins"} 1 +# HELP kube_deployment_spec_paused Whether the deployment is paused and will not be processed by the deployment controller. +# TYPE kube_deployment_spec_paused gauge +kube_deployment_spec_paused{deployment="jumpy-owl-redis",namespace="default"} 0 +kube_deployment_spec_paused{deployment="kube-state-metrics",namespace="kube-system"} 0 +kube_deployment_spec_paused{deployment="tiller-deploy",namespace="kube-system"} 0 +kube_deployment_spec_paused{deployment="wise-lynx-jenkins",namespace="jenkins"} 0 +# HELP kube_deployment_spec_replicas Number of desired pods for a deployment. +# TYPE kube_deployment_spec_replicas gauge +kube_deployment_spec_replicas{deployment="jumpy-owl-redis",namespace="default"} 1 +kube_deployment_spec_replicas{deployment="kube-state-metrics",namespace="kube-system"} 2 +kube_deployment_spec_replicas{deployment="tiller-deploy",namespace="kube-system"} 1 +kube_deployment_spec_replicas{deployment="wise-lynx-jenkins",namespace="jenkins"} 1 +# HELP kube_deployment_spec_strategy_rollingupdate_max_unavailable Maximum number of unavailable replicas during a rolling update of a deployment. +# TYPE kube_deployment_spec_strategy_rollingupdate_max_unavailable gauge +kube_deployment_spec_strategy_rollingupdate_max_unavailable{deployment="jumpy-owl-redis",namespace="default"} 1 +kube_deployment_spec_strategy_rollingupdate_max_unavailable{deployment="kube-state-metrics",namespace="kube-system"} 1 +kube_deployment_spec_strategy_rollingupdate_max_unavailable{deployment="tiller-deploy",namespace="kube-system"} 1 +kube_deployment_spec_strategy_rollingupdate_max_unavailable{deployment="wise-lynx-jenkins",namespace="jenkins"} 1 +# HELP kube_deployment_status_observed_generation The generation observed by the deployment controller. +# TYPE kube_deployment_status_observed_generation gauge +kube_deployment_status_observed_generation{deployment="jumpy-owl-redis",namespace="default"} 1 +kube_deployment_status_observed_generation{deployment="kube-state-metrics",namespace="kube-system"} 1 +kube_deployment_status_observed_generation{deployment="tiller-deploy",namespace="kube-system"} 1 +kube_deployment_status_observed_generation{deployment="wise-lynx-jenkins",namespace="jenkins"} 1 +# HELP kube_deployment_status_replicas The number of replicas per deployment. +# TYPE kube_deployment_status_replicas gauge +kube_deployment_status_replicas{deployment="jumpy-owl-redis",namespace="default"} 1 +kube_deployment_status_replicas{deployment="kube-state-metrics",namespace="kube-system"} 2 +kube_deployment_status_replicas{deployment="tiller-deploy",namespace="kube-system"} 1 +kube_deployment_status_replicas{deployment="wise-lynx-jenkins",namespace="jenkins"} 1 +# HELP kube_deployment_status_replicas_available The number of available replicas per deployment. +# TYPE kube_deployment_status_replicas_available gauge +kube_deployment_status_replicas_available{deployment="jumpy-owl-redis",namespace="default"} 0 +kube_deployment_status_replicas_available{deployment="kube-state-metrics",namespace="kube-system"} 1 +kube_deployment_status_replicas_available{deployment="tiller-deploy",namespace="kube-system"} 1 +kube_deployment_status_replicas_available{deployment="wise-lynx-jenkins",namespace="jenkins"} 1 +# HELP kube_deployment_status_replicas_unavailable The number of unavailable replicas per deployment. +# TYPE kube_deployment_status_replicas_unavailable gauge +kube_deployment_status_replicas_unavailable{deployment="jumpy-owl-redis",namespace="default"} 1 +kube_deployment_status_replicas_unavailable{deployment="kube-state-metrics",namespace="kube-system"} 1 +kube_deployment_status_replicas_unavailable{deployment="tiller-deploy",namespace="kube-system"} 0 +kube_deployment_status_replicas_unavailable{deployment="wise-lynx-jenkins",namespace="jenkins"} 0 +# HELP kube_deployment_status_replicas_updated The number of updated replicas per deployment. +# TYPE kube_deployment_status_replicas_updated gauge +kube_deployment_status_replicas_updated{deployment="jumpy-owl-redis",namespace="default"} 1 +kube_deployment_status_replicas_updated{deployment="kube-state-metrics",namespace="kube-system"} 2 +kube_deployment_status_replicas_updated{deployment="tiller-deploy",namespace="kube-system"} 1 +kube_deployment_status_replicas_updated{deployment="wise-lynx-jenkins",namespace="jenkins"} 1 +# HELP kube_node_info Information about a cluster node. +# TYPE kube_node_info gauge +kube_node_info{container_runtime_version="docker://1.11.1",kernel_version="4.7.2",kubelet_version="v1.5.3",kubeproxy_version="v1.5.3",node="minikube",os_image="Buildroot 2016.08"} 1 +# HELP kube_node_spec_unschedulable Whether a node can schedule new pods. +# TYPE kube_node_spec_unschedulable gauge +kube_node_spec_unschedulable{node="minikube"} 0 +# HELP kube_node_status_allocatable_cpu_cores The CPU resources of a node that are available for scheduling. +# TYPE kube_node_status_allocatable_cpu_cores gauge +kube_node_status_allocatable_cpu_cores{node="minikube"} 2 +# HELP kube_node_status_allocatable_memory_bytes The memory resources of a node that are available for scheduling. +# TYPE kube_node_status_allocatable_memory_bytes gauge +kube_node_status_allocatable_memory_bytes{node="minikube"} 2.09778688e+09 +# HELP kube_node_status_allocatable_pods The pod resources of a node that are available for scheduling. +# TYPE kube_node_status_allocatable_pods gauge +kube_node_status_allocatable_pods{node="minikube"} 110 +# HELP kube_node_status_capacity_cpu_cores The total CPU resources of the node. +# TYPE kube_node_status_capacity_cpu_cores gauge +kube_node_status_capacity_cpu_cores{node="minikube"} 2 +# HELP kube_node_status_capacity_memory_bytes The total memory resources of the node. +# TYPE kube_node_status_capacity_memory_bytes gauge +kube_node_status_capacity_memory_bytes{node="minikube"} 2.09778688e+09 +# HELP kube_node_status_capacity_pods The total pod resources of the node. +# TYPE kube_node_status_capacity_pods gauge +kube_node_status_capacity_pods{node="minikube"} 110 +# HELP kube_node_status_out_of_disk Whether the node is out of disk space +# TYPE kube_node_status_out_of_disk gauge +kube_node_status_out_of_disk{condition="false",node="minikube"} 1 +kube_node_status_out_of_disk{condition="true",node="minikube"} 0 +kube_node_status_out_of_disk{condition="unknown",node="minikube"} 0 +# HELP kube_node_status_ready The ready status of a cluster node. +# TYPE kube_node_status_ready gauge +kube_node_status_ready{condition="false",node="minikube"} 0 +kube_node_status_ready{condition="true",node="minikube"} 1 +kube_node_status_ready{condition="unknown",node="minikube"} 0 +# HELP kube_pod_container_info Information about a container in a pod. +# TYPE kube_pod_container_info gauge +kube_pod_container_info{container="dnsmasq",container_id="docker://9a4c9462cd078d7be4f0a9b94bcfeb69d5fdd76bff67142df3f58367ac7e8d61",image="gcr.io/google_containers/kube-dnsmasq-amd64:1.4",image_id="docker://sha256:3ec65756a89b70b4095e43a340a6e2d5696cac7a93a29619ff5c4b6be9af2773",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_container_info{container="healthz",container_id="docker://52fa55e051dc5b68e44c027588685b7edd85aaa03b07f7216d399249ff4fc821",image="gcr.io/google_containers/exechealthz-amd64:1.2",image_id="docker://sha256:93a43bfb39bfe9795e76ccd75d7a0e6d40e2ae8563456a2a77c1b4cfc3bbd967",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_container_info{container="jumpy-owl-redis",container_id="docker://4fa227874ee68536bf902394fb662f07b99099798ca9cd5c1506b79075acc065",image="bitnami/redis:3.2.8-r2",image_id="docker://sha256:ab2690be624592578e9fb5a64f134fd395d20f401498a686ca75b6f87b55db3f",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 1 +kube_pod_container_info{container="kube-addon-manager",container_id="docker://91fdd43f6b1b4c3dd133cfca53e0b1210bc557c2ae56006026b5ccdb5f52826f",image="gcr.io/google-containers/kube-addon-manager:v6.3",image_id="docker://sha256:79eb64bc98df10a9af7e39f70df817e1862f8a5ec7657714df68439a617ee9ec",namespace="kube-system",pod="kube-addon-manager-minikube"} 1 +kube_pod_container_info{container="kube-state-metrics",container_id="docker://973cbe45982c5126a5caf8c58d964c0ab1d5bb2c165ccc59715fcc1ebd58ab3d",image="gcr.io/google_containers/kube-state-metrics:v0.4.1",image_id="docker://sha256:be329a05c2e77e7d067b4e1dbefa1567a91d0487d3500d608171489369bfd945",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 1 +kube_pod_container_info{container="kubedns",container_id="docker://fa3d83f648de42492b38fa3e8501d109376f391c50f2bd210c895c8477ae4b62",image="gcr.io/google_containers/kubedns-amd64:1.9",image_id="docker://sha256:26cf1ed9b14486b93acd70c060a17fea13620393d3aa8e76036b773197c47a05",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_container_info{container="kubernetes-dashboard",container_id="docker://3aaee8bdd311c015240e99fa2a5a5f2f26b11b51236a683b39d8c1902e423978",image="gcr.io/google_containers/kubernetes-dashboard-amd64:v1.5.1",image_id="docker://sha256:1180413103fdfd00a7882d3d8653a220d88c6ea4466fb860e98376c45ee1a1d0",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 1 +kube_pod_container_info{container="tiller",container_id="docker://469f5d2b7854eb52e5d13dc0cd3e664c1b682b157aabaf596ffe4984f1516902",image="gcr.io/kubernetes-helm/tiller:v2.3.1",image_id="docker://sha256:38527daf791dbe472c37ecb1e8b13a62e31c00d9ff4c8a1f019d7022a96a43da",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 1 +kube_pod_container_info{container="wise-lynx-jenkins",container_id="docker://e2ee1c2c7b8d4e5fd8c834b83cba8377d6b0e39da18157688ccc1a06b7c53117",image="jenkinsci/jenkins:2.46.1",image_id="docker://sha256:36023b9defd066ee53c03e33ba3add7225aee8447cb3154133012b1e152153c0",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 1 +# HELP kube_pod_container_resource_limits_cpu_cores The limit on cpu cores to be used by a container. +# TYPE kube_pod_container_resource_limits_cpu_cores gauge +kube_pod_container_resource_limits_cpu_cores{container="kube-state-metrics",namespace="kube-system",node="",pod="kube-state-metrics-1303537707-mnzbp"} 0.2 +kube_pod_container_resource_limits_cpu_cores{container="kube-state-metrics",namespace="kube-system",node="minikube",pod="kube-state-metrics-1303537707-7ncd1"} 0.2 +# HELP kube_pod_container_resource_limits_memory_bytes The limit on memory to be used by a container in bytes. +# TYPE kube_pod_container_resource_limits_memory_bytes gauge +kube_pod_container_resource_limits_memory_bytes{container="healthz",namespace="kube-system",node="minikube",pod="kube-dns-v20-5g5cb"} 5.24288e+07 +kube_pod_container_resource_limits_memory_bytes{container="kube-state-metrics",namespace="kube-system",node="",pod="kube-state-metrics-1303537707-mnzbp"} 5.24288e+07 +kube_pod_container_resource_limits_memory_bytes{container="kube-state-metrics",namespace="kube-system",node="minikube",pod="kube-state-metrics-1303537707-7ncd1"} 5.24288e+07 +kube_pod_container_resource_limits_memory_bytes{container="kubedns",namespace="kube-system",node="minikube",pod="kube-dns-v20-5g5cb"} 1.7825792e+08 +# HELP kube_pod_container_resource_requests_cpu_cores The number of requested cpu cores by a container. +# TYPE kube_pod_container_resource_requests_cpu_cores gauge +kube_pod_container_resource_requests_cpu_cores{container="healthz",namespace="kube-system",node="minikube",pod="kube-dns-v20-5g5cb"} 0.01 +kube_pod_container_resource_requests_cpu_cores{container="jumpy-owl-redis",namespace="default",node="minikube",pod="jumpy-owl-redis-3481028193-s78x9"} 0.1 +kube_pod_container_resource_requests_cpu_cores{container="kube-addon-manager",namespace="kube-system",node="minikube",pod="kube-addon-manager-minikube"} 0.005 +kube_pod_container_resource_requests_cpu_cores{container="kube-state-metrics",namespace="kube-system",node="",pod="kube-state-metrics-1303537707-mnzbp"} 0.1 +kube_pod_container_resource_requests_cpu_cores{container="kube-state-metrics",namespace="kube-system",node="minikube",pod="kube-state-metrics-1303537707-7ncd1"} 0.1 +kube_pod_container_resource_requests_cpu_cores{container="kubedns",namespace="kube-system",node="minikube",pod="kube-dns-v20-5g5cb"} 0.1 +kube_pod_container_resource_requests_cpu_cores{container="wise-lynx-jenkins",namespace="jenkins",node="minikube",pod="wise-lynx-jenkins-1616735317-svn6k"} 0.2 +# HELP kube_pod_container_resource_requests_memory_bytes The number of requested memory bytes by a container. +# TYPE kube_pod_container_resource_requests_memory_bytes gauge +kube_pod_container_resource_requests_memory_bytes{container="healthz",namespace="kube-system",node="minikube",pod="kube-dns-v20-5g5cb"} 5.24288e+07 +kube_pod_container_resource_requests_memory_bytes{container="jumpy-owl-redis",namespace="default",node="minikube",pod="jumpy-owl-redis-3481028193-s78x9"} 2.68435456e+08 +kube_pod_container_resource_requests_memory_bytes{container="kube-addon-manager",namespace="kube-system",node="minikube",pod="kube-addon-manager-minikube"} 5.24288e+07 +kube_pod_container_resource_requests_memory_bytes{container="kube-state-metrics",namespace="kube-system",node="",pod="kube-state-metrics-1303537707-mnzbp"} 3.145728e+07 +kube_pod_container_resource_requests_memory_bytes{container="kube-state-metrics",namespace="kube-system",node="minikube",pod="kube-state-metrics-1303537707-7ncd1"} 3.145728e+07 +kube_pod_container_resource_requests_memory_bytes{container="kubedns",namespace="kube-system",node="minikube",pod="kube-dns-v20-5g5cb"} 7.340032e+07 +kube_pod_container_resource_requests_memory_bytes{container="wise-lynx-jenkins",namespace="jenkins",node="minikube",pod="wise-lynx-jenkins-1616735317-svn6k"} 2.68435456e+08 +# HELP kube_pod_container_status_ready Describes whether the containers readiness check succeeded. +# TYPE kube_pod_container_status_ready gauge +kube_pod_container_status_ready{container="dnsmasq",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_container_status_ready{container="healthz",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_container_status_ready{container="jumpy-owl-redis",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 0 +kube_pod_container_status_ready{container="kube-addon-manager",namespace="kube-system",pod="kube-addon-manager-minikube"} 1 +kube_pod_container_status_ready{container="kube-state-metrics",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 1 +kube_pod_container_status_ready{container="kubedns",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_container_status_ready{container="kubernetes-dashboard",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 1 +kube_pod_container_status_ready{container="tiller",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 1 +kube_pod_container_status_ready{container="wise-lynx-jenkins",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 1 +# HELP kube_pod_container_status_restarts The number of container restarts per container. +# TYPE kube_pod_container_status_restarts counter +kube_pod_container_status_restarts{container="dnsmasq",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 2 +kube_pod_container_status_restarts{container="healthz",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 2 +kube_pod_container_status_restarts{container="jumpy-owl-redis",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 270 +kube_pod_container_status_restarts{container="kube-addon-manager",namespace="kube-system",pod="kube-addon-manager-minikube"} 2 +kube_pod_container_status_restarts{container="kube-state-metrics",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 1 +kube_pod_container_status_restarts{container="kubedns",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 2 +kube_pod_container_status_restarts{container="kubernetes-dashboard",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 2 +kube_pod_container_status_restarts{container="tiller",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 1 +kube_pod_container_status_restarts{container="wise-lynx-jenkins",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 1 +# HELP kube_pod_container_status_running Describes whether the container is currently in running state. +# TYPE kube_pod_container_status_running gauge +kube_pod_container_status_running{container="dnsmasq",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_container_status_running{container="healthz",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_container_status_running{container="jumpy-owl-redis",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 0 +kube_pod_container_status_running{container="kube-addon-manager",namespace="kube-system",pod="kube-addon-manager-minikube"} 1 +kube_pod_container_status_running{container="kube-state-metrics",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 1 +kube_pod_container_status_running{container="kubedns",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_container_status_running{container="kubernetes-dashboard",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 1 +kube_pod_container_status_running{container="tiller",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 1 +kube_pod_container_status_running{container="wise-lynx-jenkins",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 1 +# HELP kube_pod_container_status_terminated Describes whether the container is currently in terminated state. +# TYPE kube_pod_container_status_terminated gauge +kube_pod_container_status_terminated{container="dnsmasq",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_container_status_terminated{container="healthz",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_container_status_terminated{container="jumpy-owl-redis",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 0 +kube_pod_container_status_terminated{container="kube-addon-manager",namespace="kube-system",pod="kube-addon-manager-minikube"} 0 +kube_pod_container_status_terminated{container="kube-state-metrics",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 0 +kube_pod_container_status_terminated{container="kubedns",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_container_status_terminated{container="kubernetes-dashboard",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 0 +kube_pod_container_status_terminated{container="tiller",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 0 +kube_pod_container_status_terminated{container="wise-lynx-jenkins",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 0 +# HELP kube_pod_container_status_waiting Describes whether the container is currently in waiting state. +# TYPE kube_pod_container_status_waiting gauge +kube_pod_container_status_waiting{container="dnsmasq",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_container_status_waiting{container="healthz",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_container_status_waiting{container="jumpy-owl-redis",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 1 +kube_pod_container_status_waiting{container="kube-addon-manager",namespace="kube-system",pod="kube-addon-manager-minikube"} 0 +kube_pod_container_status_waiting{container="kube-state-metrics",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 0 +kube_pod_container_status_waiting{container="kubedns",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_container_status_waiting{container="kubernetes-dashboard",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 0 +kube_pod_container_status_waiting{container="tiller",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 0 +kube_pod_container_status_waiting{container="wise-lynx-jenkins",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 0 +# HELP kube_pod_info Information about pod. +# TYPE kube_pod_info gauge +kube_pod_info{host_ip="",namespace="kube-system",node="",pod="kube-state-metrics-1303537707-mnzbp",pod_ip=""} 1 +kube_pod_info{host_ip="192.168.99.100",namespace="default",node="minikube",pod="jumpy-owl-redis-3481028193-s78x9",pod_ip="172.17.0.4"} 1 +kube_pod_info{host_ip="192.168.99.100",namespace="jenkins",node="minikube",pod="wise-lynx-jenkins-1616735317-svn6k",pod_ip="172.17.0.7"} 1 +kube_pod_info{host_ip="192.168.99.100",namespace="kube-system",node="minikube",pod="kube-addon-manager-minikube",pod_ip="192.168.99.100"} 1 +kube_pod_info{host_ip="192.168.99.100",namespace="kube-system",node="minikube",pod="kube-dns-v20-5g5cb",pod_ip="172.17.0.6"} 1 +kube_pod_info{host_ip="192.168.99.100",namespace="kube-system",node="minikube",pod="kube-state-metrics-1303537707-7ncd1",pod_ip="172.17.0.3"} 1 +kube_pod_info{host_ip="192.168.99.100",namespace="kube-system",node="minikube",pod="kubernetes-dashboard-vw0l6",pod_ip="172.17.0.5"} 1 +kube_pod_info{host_ip="192.168.99.100",namespace="kube-system",node="minikube",pod="tiller-deploy-3067024529-9lpmb",pod_ip="172.17.0.2"} 1 +# HELP kube_pod_status_phase The pods current phase. +# TYPE kube_pod_status_phase gauge +kube_pod_status_phase{namespace="default",phase="Running",pod="jumpy-owl-redis-3481028193-s78x9"} 1 +kube_pod_status_phase{namespace="jenkins",phase="Running",pod="wise-lynx-jenkins-1616735317-svn6k"} 1 +kube_pod_status_phase{namespace="kube-system",phase="Pending",pod="kube-state-metrics-1303537707-mnzbp"} 1 +kube_pod_status_phase{namespace="kube-system",phase="Running",pod="kube-addon-manager-minikube"} 1 +kube_pod_status_phase{namespace="kube-system",phase="Running",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_status_phase{namespace="kube-system",phase="Running",pod="kube-state-metrics-1303537707-7ncd1"} 1 +kube_pod_status_phase{namespace="kube-system",phase="Running",pod="kubernetes-dashboard-vw0l6"} 1 +kube_pod_status_phase{namespace="kube-system",phase="Running",pod="tiller-deploy-3067024529-9lpmb"} 1 +# HELP kube_pod_status_ready Describes whether the pod is ready to serve requests. +# TYPE kube_pod_status_ready gauge +kube_pod_status_ready{condition="false",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 1 +kube_pod_status_ready{condition="false",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 0 +kube_pod_status_ready{condition="false",namespace="kube-system",pod="kube-addon-manager-minikube"} 0 +kube_pod_status_ready{condition="false",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_status_ready{condition="false",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 0 +kube_pod_status_ready{condition="false",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 0 +kube_pod_status_ready{condition="false",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 0 +kube_pod_status_ready{condition="true",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 0 +kube_pod_status_ready{condition="true",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 1 +kube_pod_status_ready{condition="true",namespace="kube-system",pod="kube-addon-manager-minikube"} 1 +kube_pod_status_ready{condition="true",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_status_ready{condition="true",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 1 +kube_pod_status_ready{condition="true",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 1 +kube_pod_status_ready{condition="true",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 1 +kube_pod_status_ready{condition="unknown",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 0 +kube_pod_status_ready{condition="unknown",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 0 +kube_pod_status_ready{condition="unknown",namespace="kube-system",pod="kube-addon-manager-minikube"} 0 +kube_pod_status_ready{condition="unknown",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_status_ready{condition="unknown",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 0 +kube_pod_status_ready{condition="unknown",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 0 +kube_pod_status_ready{condition="unknown",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 0 +# HELP kube_pod_status_scheduled Describes the status of the scheduling process for the pod. +# TYPE kube_pod_status_scheduled gauge +kube_pod_status_scheduled{condition="false",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 0 +kube_pod_status_scheduled{condition="false",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 0 +kube_pod_status_scheduled{condition="false",namespace="kube-system",pod="kube-addon-manager-minikube"} 0 +kube_pod_status_scheduled{condition="false",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_status_scheduled{condition="false",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 0 +kube_pod_status_scheduled{condition="false",namespace="kube-system",pod="kube-state-metrics-1303537707-mnzbp"} 1 +kube_pod_status_scheduled{condition="false",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 0 +kube_pod_status_scheduled{condition="false",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 0 +kube_pod_status_scheduled{condition="true",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 1 +kube_pod_status_scheduled{condition="true",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 1 +kube_pod_status_scheduled{condition="true",namespace="kube-system",pod="kube-addon-manager-minikube"} 1 +kube_pod_status_scheduled{condition="true",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 1 +kube_pod_status_scheduled{condition="true",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 1 +kube_pod_status_scheduled{condition="true",namespace="kube-system",pod="kube-state-metrics-1303537707-mnzbp"} 0 +kube_pod_status_scheduled{condition="true",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 1 +kube_pod_status_scheduled{condition="true",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 1 +kube_pod_status_scheduled{condition="unknown",namespace="default",pod="jumpy-owl-redis-3481028193-s78x9"} 0 +kube_pod_status_scheduled{condition="unknown",namespace="jenkins",pod="wise-lynx-jenkins-1616735317-svn6k"} 0 +kube_pod_status_scheduled{condition="unknown",namespace="kube-system",pod="kube-addon-manager-minikube"} 0 +kube_pod_status_scheduled{condition="unknown",namespace="kube-system",pod="kube-dns-v20-5g5cb"} 0 +kube_pod_status_scheduled{condition="unknown",namespace="kube-system",pod="kube-state-metrics-1303537707-7ncd1"} 0 +kube_pod_status_scheduled{condition="unknown",namespace="kube-system",pod="kube-state-metrics-1303537707-mnzbp"} 0 +kube_pod_status_scheduled{condition="unknown",namespace="kube-system",pod="kubernetes-dashboard-vw0l6"} 0 +kube_pod_status_scheduled{condition="unknown",namespace="kube-system",pod="tiller-deploy-3067024529-9lpmb"} 0 +# HELP kube_replicaset_metadata_generation Sequence number representing a specific generation of the desired state. +# TYPE kube_replicaset_metadata_generation gauge +kube_replicaset_metadata_generation{namespace="default",replicaset="jumpy-owl-redis-3481028193"} 1 +kube_replicaset_metadata_generation{namespace="jenkins",replicaset="wise-lynx-jenkins-1616735317"} 1 +kube_replicaset_metadata_generation{namespace="kube-system",replicaset="kube-state-metrics-1303537707"} 1 +kube_replicaset_metadata_generation{namespace="kube-system",replicaset="tiller-deploy-3067024529"} 1 +# HELP kube_replicaset_spec_replicas Number of desired pods for a ReplicaSet. +# TYPE kube_replicaset_spec_replicas gauge +kube_replicaset_spec_replicas{namespace="default",replicaset="jumpy-owl-redis-3481028193"} 1 +kube_replicaset_spec_replicas{namespace="jenkins",replicaset="wise-lynx-jenkins-1616735317"} 1 +kube_replicaset_spec_replicas{namespace="kube-system",replicaset="kube-state-metrics-1303537707"} 2 +kube_replicaset_spec_replicas{namespace="kube-system",replicaset="tiller-deploy-3067024529"} 1 +# HELP kube_replicaset_status_fully_labeled_replicas The number of fully labeled replicas per ReplicaSet. +# TYPE kube_replicaset_status_fully_labeled_replicas gauge +kube_replicaset_status_fully_labeled_replicas{namespace="default",replicaset="jumpy-owl-redis-3481028193"} 1 +kube_replicaset_status_fully_labeled_replicas{namespace="jenkins",replicaset="wise-lynx-jenkins-1616735317"} 1 +kube_replicaset_status_fully_labeled_replicas{namespace="kube-system",replicaset="kube-state-metrics-1303537707"} 2 +kube_replicaset_status_fully_labeled_replicas{namespace="kube-system",replicaset="tiller-deploy-3067024529"} 1 +# HELP kube_replicaset_status_observed_generation The generation observed by the ReplicaSet controller. +# TYPE kube_replicaset_status_observed_generation gauge +kube_replicaset_status_observed_generation{namespace="default",replicaset="jumpy-owl-redis-3481028193"} 1 +kube_replicaset_status_observed_generation{namespace="jenkins",replicaset="wise-lynx-jenkins-1616735317"} 1 +kube_replicaset_status_observed_generation{namespace="kube-system",replicaset="kube-state-metrics-1303537707"} 1 +kube_replicaset_status_observed_generation{namespace="kube-system",replicaset="tiller-deploy-3067024529"} 1 +# HELP kube_replicaset_status_ready_replicas The number of ready replicas per ReplicaSet. +# TYPE kube_replicaset_status_ready_replicas gauge +kube_replicaset_status_ready_replicas{namespace="default",replicaset="jumpy-owl-redis-3481028193"} 0 +kube_replicaset_status_ready_replicas{namespace="jenkins",replicaset="wise-lynx-jenkins-1616735317"} 1 +kube_replicaset_status_ready_replicas{namespace="kube-system",replicaset="kube-state-metrics-1303537707"} 1 +kube_replicaset_status_ready_replicas{namespace="kube-system",replicaset="tiller-deploy-3067024529"} 1 +# HELP kube_replicaset_status_replicas The number of replicas per ReplicaSet. +# TYPE kube_replicaset_status_replicas gauge +kube_replicaset_status_replicas{namespace="default",replicaset="jumpy-owl-redis-3481028193"} 1 +kube_replicaset_status_replicas{namespace="jenkins",replicaset="wise-lynx-jenkins-1616735317"} 1 +kube_replicaset_status_replicas{namespace="kube-system",replicaset="kube-state-metrics-1303537707"} 2 +kube_replicaset_status_replicas{namespace="kube-system",replicaset="tiller-deploy-3067024529"} 1 +# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. +# TYPE process_cpu_seconds_total counter +process_cpu_seconds_total 33.37 +# HELP process_max_fds Maximum number of open file descriptors. +# TYPE process_max_fds gauge +process_max_fds 65536 +# HELP process_open_fds Number of open file descriptors. +# TYPE process_open_fds gauge +process_open_fds 14 +# HELP process_resident_memory_bytes Resident memory size in bytes. +# TYPE process_resident_memory_bytes gauge +process_resident_memory_bytes 4.2102784e+07 +# HELP process_start_time_seconds Start time of the process since unix epoch in seconds. +# TYPE process_start_time_seconds gauge +process_start_time_seconds 1.4939719827e+09 +# HELP process_virtual_memory_bytes Virtual memory size in bytes. +# TYPE process_virtual_memory_bytes gauge +process_virtual_memory_bytes 5.2932608e+07 diff --git a/metricbeat/module/kubernetes/container/_meta/fields.yml b/metricbeat/module/kubernetes/container/_meta/fields.yml index 56a1ebae730..05203841028 100644 --- a/metricbeat/module/kubernetes/container/_meta/fields.yml +++ b/metricbeat/module/kubernetes/container/_meta/fields.yml @@ -3,6 +3,10 @@ description: > kubernetes container metrics fields: + - name: start_time + type: date + description: > + Start time - name: cpu type: group description: > diff --git a/metricbeat/module/kubernetes/node/_meta/fields.yml b/metricbeat/module/kubernetes/node/_meta/fields.yml index e7b904e29d6..c29567b1c1a 100644 --- a/metricbeat/module/kubernetes/node/_meta/fields.yml +++ b/metricbeat/module/kubernetes/node/_meta/fields.yml @@ -7,6 +7,10 @@ type: keyword description: > Node name + - name: start_time + type: date + description: > + Start time - name: cpu type: group description: > @@ -123,6 +127,21 @@ format: bytes description: > Filesystem total used in bytes + - name: inodes + type: group + fields: + - name: used + type: long + description: > + Number of used inodes + - name: count + type: long + description: > + Number of inodes + - name: free + type: long + description: > + Number of free inodes - name: runtime type: group fields: diff --git a/metricbeat/module/kubernetes/pod/_meta/fields.yml b/metricbeat/module/kubernetes/pod/_meta/fields.yml index 8c50082764b..6a57a87bdb2 100644 --- a/metricbeat/module/kubernetes/pod/_meta/fields.yml +++ b/metricbeat/module/kubernetes/pod/_meta/fields.yml @@ -3,6 +3,10 @@ description: > kubernetes pod metrics fields: + - name: start_time + type: date + description: > + Start time - name: network type: group fields: diff --git a/metricbeat/module/kubernetes/state_container/_meta/data.json b/metricbeat/module/kubernetes/state_container/_meta/data.json new file mode 100644 index 00000000000..2496258b7c9 --- /dev/null +++ b/metricbeat/module/kubernetes/state_container/_meta/data.json @@ -0,0 +1,44 @@ +{ + "@timestamp": "2017-05-10T16:42:27.816Z", + "beat": { + "hostname": "X1", + "name": "X1", + "version": "6.0.0-alpha1" + }, + "kubernetes": { + "container": { + "cpu": { + "request": { + "nanocores": 200000000 + } + }, + "id": "docker://39f3267ad1b0c46025e664bfe0b70f3f18a9f172aad00463c8e87e0e93bbf628", + "image": "jenkinsci/jenkins:2.46.1", + "memory": { + "request": { + "bytes": 268435456 + } + }, + "name": "wise-lynx-jenkins", + "status": { + "phase": "running", + "ready": true, + "restarts": 4 + } + }, + "namespace": "jenkins", + "node": { + "name": "minikube" + }, + "pod": { + "name": "wise-lynx-jenkins-1616735317-svn6k" + } + }, + "metricset": { + "host": "192.168.99.100:18080", + "module": "kubernetes", + "name": "state_container", + "namespace": "container", + "rtt": 6219 + } +} diff --git a/metricbeat/module/kubernetes/state_container/_meta/docs.asciidoc b/metricbeat/module/kubernetes/state_container/_meta/docs.asciidoc new file mode 100644 index 00000000000..300c10f0600 --- /dev/null +++ b/metricbeat/module/kubernetes/state_container/_meta/docs.asciidoc @@ -0,0 +1,3 @@ +=== kubernetes state_container MetricSet + +This is the state_container metricset of the module kubernetes. diff --git a/metricbeat/module/kubernetes/state_container/_meta/fields.yml b/metricbeat/module/kubernetes/state_container/_meta/fields.yml new file mode 100644 index 00000000000..2d26be2b360 --- /dev/null +++ b/metricbeat/module/kubernetes/state_container/_meta/fields.yml @@ -0,0 +1,48 @@ +- name: container + type: group + description: > + kubernetes container metrics + fields: + - name: id + type: keyword + description: + Container id + - name: status + type: group + fields: + - name: phase + type: keyword + description: > + Container phase (running, waiting, terminated) + - name: ready + type: boolean + description: > + Container ready status + - name: restarts + type: integer + description: > + Container restarts count + - name: cpu + type: group + fields: + - name: limit.nanocores + type: long + description: > + Container CPU nanocores limit + - name: request.nanocores + type: long + description: > + Container CPU requested nanocores + - name: memory + type: group + fields: + - name: limit.bytes + type: long + format: bytes + description: > + Container memory limit in bytes + - name: request.bytes + type: long + format: bytes + description: > + Container requested memory in bytes diff --git a/metricbeat/module/kubernetes/state_container/data.go b/metricbeat/module/kubernetes/state_container/data.go new file mode 100644 index 00000000000..efc22b2847a --- /dev/null +++ b/metricbeat/module/kubernetes/state_container/data.go @@ -0,0 +1,88 @@ +package state_container + +import ( + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/module/kubernetes/util" + + dto "github.com/prometheus/client_model/go" +) + +const ( + // Nanocores conversion 10^9 + nanocores = 1000000000 +) + +func eventMapping(families []*dto.MetricFamily) ([]common.MapStr, error) { + eventsMap := map[string]common.MapStr{} + for _, family := range families { + for _, metric := range family.GetMetric() { + container := util.GetLabel(metric, "container") + if container == "" { + continue + } + event, ok := eventsMap[container] + if !ok { + event = common.MapStr{} + eventsMap[container] = event + } + switch family.GetName() { + case "kube_pod_container_info": + event.Put(mb.ModuleDataKey+".pod.name", util.GetLabel(metric, "pod")) + event.Put(mb.ModuleDataKey+".namespace", util.GetLabel(metric, "namespace")) + event.Put(mb.NamespaceKey, "container") + + event.Put("name", util.GetLabel(metric, "container")) + event.Put("id", util.GetLabel(metric, "container_id")) + event.Put("image", util.GetLabel(metric, "image")) + + case "kube_pod_container_resource_limits_cpu_cores": + event.Put(mb.ModuleDataKey+".node.name", util.GetLabel(metric, "node")) + event.Put("cpu.limit.nanocores", metric.GetGauge().GetValue()*nanocores) + + case "kube_pod_container_resource_requests_cpu_cores": + event.Put(mb.ModuleDataKey+".node.name", util.GetLabel(metric, "node")) + event.Put("cpu.request.nanocores", metric.GetGauge().GetValue()*nanocores) + + case "kube_pod_container_resource_limits_memory_bytes": + event.Put(mb.ModuleDataKey+".node.name", util.GetLabel(metric, "node")) + event.Put("memory.limit.bytes", metric.GetGauge().GetValue()) + + case "kube_pod_container_resource_requests_memory_bytes": + event.Put(mb.ModuleDataKey+".node.name", util.GetLabel(metric, "node")) + event.Put("memory.request.bytes", metric.GetGauge().GetValue()) + + case "kube_pod_container_status_ready": + event.Put("status.ready", metric.GetGauge().GetValue() == 1) + + case "kube_pod_container_status_restarts": + event.Put("status.restarts", metric.GetCounter().GetValue()) + + case "kube_pod_container_status_running": + if metric.GetGauge().GetValue() == 1 { + event.Put("status.phase", "running") + } + + case "kube_pod_container_status_terminated": + if metric.GetGauge().GetValue() == 1 { + event.Put("status.phase", "terminate") + } + + case "kube_pod_container_status_waiting": + if metric.GetGauge().GetValue() == 1 { + event.Put("status.phase", "waiting") + } + + default: + // Ignore unknown metric + continue + } + } + } + + var events []common.MapStr + for _, event := range eventsMap { + events = append(events, event) + } + return events, nil +} diff --git a/metricbeat/module/kubernetes/state_container/state_container.go b/metricbeat/module/kubernetes/state_container/state_container.go new file mode 100644 index 00000000000..e7e06c1d9c9 --- /dev/null +++ b/metricbeat/module/kubernetes/state_container/state_container.go @@ -0,0 +1,62 @@ +package state_container + +import ( + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/libbeat/logp" + "github.com/elastic/beats/metricbeat/helper" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/mb/parse" +) + +const ( + defaultScheme = "http" + defaultPath = "/metrics" +) + +var ( + hostParser = parse.URLHostParserBuilder{ + DefaultScheme: defaultScheme, + DefaultPath: defaultPath, + }.Build() +) + +// init registers the MetricSet with the central registry. +// The New method will be called after the setup of the module and before starting to fetch data +func init() { + if err := mb.Registry.AddMetricSet("kubernetes", "state_container", New, hostParser); err != nil { + panic(err) + } +} + +// MetricSet type defines all fields of the MetricSet +// As a minimum it must inherit the mb.BaseMetricSet fields, but can be extended with +// additional entries. These variables can be used to persist data or configuration between +// multiple fetch calls. +type MetricSet struct { + mb.BaseMetricSet + prometheus *helper.Prometheus +} + +// New create a new instance of the MetricSet +// Part of new is also setting up the configuration by processing additional +// configuration entries if needed. +func New(base mb.BaseMetricSet) (mb.MetricSet, error) { + logp.Beta("The kubernetes state_container metricset is beta") + + return &MetricSet{ + BaseMetricSet: base, + prometheus: helper.NewPrometheusClient(base), + }, nil +} + +// Fetch methods implements the data gathering and data conversion to the right format +// It returns the event which is then forward to the output. In case of an error, a +// descriptive error must be returned. +func (m *MetricSet) Fetch() ([]common.MapStr, error) { + families, err := m.prometheus.GetFamilies() + if err != nil { + return nil, err + } + + return eventMapping(families) +} diff --git a/metricbeat/module/kubernetes/state_container/state_container_test.go b/metricbeat/module/kubernetes/state_container/state_container_test.go new file mode 100644 index 00000000000..39cbcaae05b --- /dev/null +++ b/metricbeat/module/kubernetes/state_container/state_container_test.go @@ -0,0 +1,82 @@ +// +build !integration + +package state_container + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/elastic/beats/libbeat/common" + mbtest "github.com/elastic/beats/metricbeat/mb/testing" + + "github.com/stretchr/testify/assert" +) + +const testFile = "../_meta/test/kube-state-metrics" + +func TestEventMapping(t *testing.T) { + + file, err := os.Open(testFile) + assert.NoError(t, err, "cannot open test file "+testFile) + + body, err := ioutil.ReadAll(file) + assert.NoError(t, err, "cannot read test file "+testFile) + + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + w.Header().Set("Content-Type", "text/plain; charset=ISO-8859-1") + w.Write([]byte(body)) + })) + + server.Start() + defer server.Close() + + config := map[string]interface{}{ + "module": "kubernetes", + "metricsets": []string{"state_container"}, + "hosts": []string{server.URL}, + } + + f := mbtest.NewEventsFetcher(t, config) + + events, err := f.Fetch() + assert.NoError(t, err) + + assert.Equal(t, 9, len(events), "Wrong number of returned events") + + testCases := map[string]interface{}{ + "_module.namespace": "kube-system", + "_module.node.name": "minikube", + "_module.pod.name": "kube-dns-v20-5g5cb", + + "image": "gcr.io/google_containers/exechealthz-amd64:1.2", + "status.phase": "running", + "status.ready": true, + "status.restarts": 2, + + "memory.limit.bytes": 52428800, + "memory.request.bytes": 52428800, + "cpu.request.nanocores": 10000000, + } + + for _, event := range events { + name, err := event.GetValue("name") + if err == nil && name == "healthz" { + for k, v := range testCases { + testValue(t, event, k, v) + } + return + } + } + + t.Error("Test reference event not found") +} + +func testValue(t *testing.T, event common.MapStr, field string, expected interface{}) { + data, err := event.GetValue(field) + assert.NoError(t, err, "Could not read field "+field) + assert.EqualValues(t, expected, data, "Wrong value for field "+field) +} diff --git a/metricbeat/module/kubernetes/state_deployment/_meta/data.json b/metricbeat/module/kubernetes/state_deployment/_meta/data.json new file mode 100644 index 00000000000..9ab79bdaea8 --- /dev/null +++ b/metricbeat/module/kubernetes/state_deployment/_meta/data.json @@ -0,0 +1,28 @@ +{ + "@timestamp": "2017-05-10T16:44:27.915Z", + "beat": { + "hostname": "X1", + "name": "X1", + "version": "6.0.0-alpha1" + }, + "kubernetes": { + "deployment": { + "name": "wise-lynx-jenkins", + "paused": false, + "replicas": { + "available": 1, + "desired": 1, + "unavailable": 0, + "updated": 1 + } + }, + "namespace": "jenkins" + }, + "metricset": { + "host": "192.168.99.100:18080", + "module": "kubernetes", + "name": "state_deployment", + "namespace": "deployment", + "rtt": 198882 + } +} diff --git a/metricbeat/module/kubernetes/state_deployment/_meta/docs.asciidoc b/metricbeat/module/kubernetes/state_deployment/_meta/docs.asciidoc new file mode 100644 index 00000000000..c17160ba76a --- /dev/null +++ b/metricbeat/module/kubernetes/state_deployment/_meta/docs.asciidoc @@ -0,0 +1,3 @@ +=== kubernetes state_deployment MetricSet + +This is the state_deployment metricset of the module kubernetes. diff --git a/metricbeat/module/kubernetes/state_deployment/_meta/fields.yml b/metricbeat/module/kubernetes/state_deployment/_meta/fields.yml new file mode 100644 index 00000000000..10981f71e9e --- /dev/null +++ b/metricbeat/module/kubernetes/state_deployment/_meta/fields.yml @@ -0,0 +1,34 @@ +- name: deployment + type: group + description: > + kubernetes deployment metrics + fields: + - name: name + type: keyword + description: > + Kubernetes deployment name + - name: paused + type: boolean + description: > + Kubernetes deployment paused status + - name: replicas + type: group + description: > + Kubernetes deployment replicas info + fields: + - name: desired + type: integer + description: > + Deployment number of desired replicas (spec) + - name: available + type: integer + description: > + Deployment available replicas + - name: unavailable + type: integer + description: > + Deployment unavailable replicas + - name: updated + type: integer + description: > + Deployment updated replicas diff --git a/metricbeat/module/kubernetes/state_deployment/data.go b/metricbeat/module/kubernetes/state_deployment/data.go new file mode 100644 index 00000000000..9634de2dbbb --- /dev/null +++ b/metricbeat/module/kubernetes/state_deployment/data.go @@ -0,0 +1,62 @@ +package state_deployment + +import ( + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/module/kubernetes/util" + + dto "github.com/prometheus/client_model/go" +) + +const ( + // Nanocores conversion 10^9 + nanocores = 1000000000 +) + +func eventMapping(families []*dto.MetricFamily) ([]common.MapStr, error) { + eventsMap := map[string]common.MapStr{} + for _, family := range families { + for _, metric := range family.GetMetric() { + deployment := util.GetLabel(metric, "deployment") + if deployment == "" { + continue + } + event, ok := eventsMap[deployment] + if !ok { + event = common.MapStr{} + eventsMap[deployment] = event + } + switch family.GetName() { + case "kube_deployment_metadata_generation": + event.Put(mb.ModuleDataKey+".namespace", util.GetLabel(metric, "namespace")) + event.Put(mb.NamespaceKey, "deployment") + event.Put("name", util.GetLabel(metric, "deployment")) + + case "kube_deployment_spec_paused": + event.Put("paused", metric.GetGauge().GetValue() == 1) + + case "kube_deployment_spec_replicas": + event.Put("replicas.desired", metric.GetGauge().GetValue()) + + case "kube_deployment_status_replicas_available": + event.Put("replicas.available", metric.GetGauge().GetValue()) + + case "kube_deployment_status_replicas_unavailable": + event.Put("replicas.unavailable", metric.GetGauge().GetValue()) + + case "kube_deployment_status_replicas_updated": + event.Put("replicas.updated", metric.GetGauge().GetValue()) + + default: + // Ignore unknown metric + continue + } + } + } + + var events []common.MapStr + for _, event := range eventsMap { + events = append(events, event) + } + return events, nil +} diff --git a/metricbeat/module/kubernetes/state_deployment/state_deployment.go b/metricbeat/module/kubernetes/state_deployment/state_deployment.go new file mode 100644 index 00000000000..78d36451d8f --- /dev/null +++ b/metricbeat/module/kubernetes/state_deployment/state_deployment.go @@ -0,0 +1,62 @@ +package state_deployment + +import ( + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/libbeat/logp" + "github.com/elastic/beats/metricbeat/helper" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/mb/parse" +) + +const ( + defaultScheme = "http" + defaultPath = "/metrics" +) + +var ( + hostParser = parse.URLHostParserBuilder{ + DefaultScheme: defaultScheme, + DefaultPath: defaultPath, + }.Build() +) + +// init registers the MetricSet with the central registry. +// The New method will be called after the setup of the module and before starting to fetch data +func init() { + if err := mb.Registry.AddMetricSet("kubernetes", "state_deployment", New, hostParser); err != nil { + panic(err) + } +} + +// MetricSet type defines all fields of the MetricSet +// As a minimum it must inherit the mb.BaseMetricSet fields, but can be extended with +// additional entries. These variables can be used to persist data or configuration between +// multiple fetch calls. +type MetricSet struct { + mb.BaseMetricSet + prometheus *helper.Prometheus +} + +// New create a new instance of the MetricSet +// Part of new is also setting up the configuration by processing additional +// configuration entries if needed. +func New(base mb.BaseMetricSet) (mb.MetricSet, error) { + logp.Beta("The kubernetes state_deployment metricset is beta") + + return &MetricSet{ + BaseMetricSet: base, + prometheus: helper.NewPrometheusClient(base), + }, nil +} + +// Fetch methods implements the data gathering and data conversion to the right format +// It returns the event which is then forward to the output. In case of an error, a +// descriptive error must be returned. +func (m *MetricSet) Fetch() ([]common.MapStr, error) { + families, err := m.prometheus.GetFamilies() + if err != nil { + return nil, err + } + + return eventMapping(families) +} diff --git a/metricbeat/module/kubernetes/state_deployment/state_deployment_test.go b/metricbeat/module/kubernetes/state_deployment/state_deployment_test.go new file mode 100644 index 00000000000..4fee50499e1 --- /dev/null +++ b/metricbeat/module/kubernetes/state_deployment/state_deployment_test.go @@ -0,0 +1,79 @@ +// +build !integration + +package state_deployment + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/elastic/beats/libbeat/common" + mbtest "github.com/elastic/beats/metricbeat/mb/testing" + + "github.com/stretchr/testify/assert" +) + +const testFile = "../_meta/test/kube-state-metrics" + +func TestEventMapping(t *testing.T) { + + file, err := os.Open(testFile) + assert.NoError(t, err, "cannot open test file "+testFile) + + body, err := ioutil.ReadAll(file) + assert.NoError(t, err, "cannot read test file "+testFile) + + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + w.Header().Set("Content-Type", "text/plain; charset=ISO-8859-1") + w.Write([]byte(body)) + })) + + server.Start() + defer server.Close() + + config := map[string]interface{}{ + "module": "kubernetes", + "metricsets": []string{"state_deployment"}, + "hosts": []string{server.URL}, + } + + f := mbtest.NewEventsFetcher(t, config) + + events, err := f.Fetch() + assert.NoError(t, err) + + assert.Equal(t, 4, len(events), "Wrong number of returned events") + + testCases := map[string]interface{}{ + "_module.namespace": "default", + + "name": "jumpy-owl-redis", + "paused": false, + + "replicas.available": 0, + "replicas.desired": 1, + "replicas.unavailable": 1, + "replicas.updated": 1, + } + + for _, event := range events { + name, err := event.GetValue("name") + if err == nil && name == "jumpy-owl-redis" { + for k, v := range testCases { + testValue(t, event, k, v) + } + return + } + } + + t.Error("Test reference event not found") +} + +func testValue(t *testing.T, event common.MapStr, field string, expected interface{}) { + data, err := event.GetValue(field) + assert.NoError(t, err, "Could not read field "+field) + assert.EqualValues(t, expected, data, "Wrong value for field "+field) +} diff --git a/metricbeat/module/kubernetes/state_node/_meta/data.json b/metricbeat/module/kubernetes/state_node/_meta/data.json new file mode 100644 index 00000000000..1e3770a3858 --- /dev/null +++ b/metricbeat/module/kubernetes/state_node/_meta/data.json @@ -0,0 +1,48 @@ +{ + "@timestamp": "2017-05-10T16:45:47.726Z", + "beat": { + "hostname": "X1", + "name": "X1", + "version": "6.0.0-alpha1" + }, + "kubernetes": { + "node": { + "cpu": { + "allocatable": { + "cores": 2 + }, + "capacity": { + "cores": 2 + } + }, + "memory": { + "allocatable": { + "bytes": 2097786880 + }, + "capacity": { + "bytes": 2097786880 + } + }, + "name": "minikube", + "pod": { + "allocatable": { + "total": 110 + }, + "capacity": { + "total": 110 + } + }, + "status": { + "ready": "true", + "unschedulable": false + } + } + }, + "metricset": { + "host": "192.168.99.100:18080", + "module": "kubernetes", + "name": "state_node", + "namespace": "node", + "rtt": 94611 + } +} diff --git a/metricbeat/module/kubernetes/state_node/_meta/docs.asciidoc b/metricbeat/module/kubernetes/state_node/_meta/docs.asciidoc new file mode 100644 index 00000000000..a6109ae9f34 --- /dev/null +++ b/metricbeat/module/kubernetes/state_node/_meta/docs.asciidoc @@ -0,0 +1,3 @@ +=== kubernetes state_node MetricSet + +This is the state_node metricset of the module kubernetes. diff --git a/metricbeat/module/kubernetes/state_node/_meta/fields.yml b/metricbeat/module/kubernetes/state_node/_meta/fields.yml new file mode 100644 index 00000000000..4b4471afe79 --- /dev/null +++ b/metricbeat/module/kubernetes/state_node/_meta/fields.yml @@ -0,0 +1,51 @@ +- name: node + type: group + description: > + kubernetes node metrics + fields: + - name: status + type: group + fields: + - name: ready + type: keyword + description: > + Node ready status (true, false or unknown) + - name: unschedulable + type: boolean + description: > + Node unschedulable status + - name: cpu + type: group + fields: + - name: allocatable.cores + type: long + description: > + Node CPU allocatable cores + - name: capacity.cores + type: long + description: > + Node CPU capacity cores + - name: memory + type: group + fields: + - name: allocatable.bytes + type: long + format: bytes + description: > + Node allocatable memory in bytes + - name: capacity.bytes + type: long + format: bytes + description: > + Node memory capacity in bytes + - name: pod + type: group + fields: + - name: allocatable.total + type: long + description: > + Node allocatable pods + - name: capacity.total + type: long + description: > + Node pod capacity diff --git a/metricbeat/module/kubernetes/state_node/data.go b/metricbeat/module/kubernetes/state_node/data.go new file mode 100644 index 00000000000..138a5625f24 --- /dev/null +++ b/metricbeat/module/kubernetes/state_node/data.go @@ -0,0 +1,67 @@ +package state_node + +import ( + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/module/kubernetes/util" + + dto "github.com/prometheus/client_model/go" +) + +func eventMapping(families []*dto.MetricFamily) ([]common.MapStr, error) { + eventsMap := map[string]common.MapStr{} + for _, family := range families { + for _, metric := range family.GetMetric() { + node := util.GetLabel(metric, "node") + if node == "" { + continue + } + event, ok := eventsMap[node] + if !ok { + event = common.MapStr{} + eventsMap[node] = event + } + switch family.GetName() { + case "kube_node_info": + event.Put(mb.NamespaceKey, "node") + event.Put("name", util.GetLabel(metric, "node")) + + case "kube_node_status_allocatable_cpu_cores": + event.Put("cpu.allocatable.cores", metric.GetGauge().GetValue()) + + case "kube_node_status_capacity_cpu_cores": + event.Put("cpu.capacity.cores", metric.GetGauge().GetValue()) + + case "kube_node_status_allocatable_memory_bytes": + event.Put("memory.allocatable.bytes", metric.GetGauge().GetValue()) + + case "kube_node_status_capacity_memory_bytes": + event.Put("memory.capacity.bytes", metric.GetGauge().GetValue()) + + case "kube_node_status_capacity_pods": + event.Put("pod.capacity.total", metric.GetGauge().GetValue()) + + case "kube_node_status_allocatable_pods": + event.Put("pod.allocatable.total", metric.GetGauge().GetValue()) + + case "kube_node_status_ready": + if metric.GetGauge().GetValue() == 1 { + event.Put("status.ready", util.GetLabel(metric, "condition")) + } + + case "kube_node_spec_unschedulable": + event.Put("status.unschedulable", metric.GetGauge().GetValue() == 1) + + default: + // Ignore unknown metric + continue + } + } + } + + var events []common.MapStr + for _, event := range eventsMap { + events = append(events, event) + } + return events, nil +} diff --git a/metricbeat/module/kubernetes/state_node/state_node.go b/metricbeat/module/kubernetes/state_node/state_node.go new file mode 100644 index 00000000000..b45cc2c9708 --- /dev/null +++ b/metricbeat/module/kubernetes/state_node/state_node.go @@ -0,0 +1,62 @@ +package state_node + +import ( + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/libbeat/logp" + "github.com/elastic/beats/metricbeat/helper" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/mb/parse" +) + +const ( + defaultScheme = "http" + defaultPath = "/metrics" +) + +var ( + hostParser = parse.URLHostParserBuilder{ + DefaultScheme: defaultScheme, + DefaultPath: defaultPath, + }.Build() +) + +// init registers the MetricSet with the central registry. +// The New method will be called after the setup of the module and before starting to fetch data +func init() { + if err := mb.Registry.AddMetricSet("kubernetes", "state_node", New, hostParser); err != nil { + panic(err) + } +} + +// MetricSet type defines all fields of the MetricSet +// As a minimum it must inherit the mb.BaseMetricSet fields, but can be extended with +// additional entries. These variables can be used to persist data or configuration between +// multiple fetch calls. +type MetricSet struct { + mb.BaseMetricSet + prometheus *helper.Prometheus +} + +// New create a new instance of the MetricSet +// Part of new is also setting up the configuration by processing additional +// configuration entries if needed. +func New(base mb.BaseMetricSet) (mb.MetricSet, error) { + logp.Beta("The kubernetes state_node metricset is beta") + + return &MetricSet{ + BaseMetricSet: base, + prometheus: helper.NewPrometheusClient(base), + }, nil +} + +// Fetch methods implements the data gathering and data conversion to the right format +// It returns the event which is then forward to the output. In case of an error, a +// descriptive error must be returned. +func (m *MetricSet) Fetch() ([]common.MapStr, error) { + families, err := m.prometheus.GetFamilies() + if err != nil { + return nil, err + } + + return eventMapping(families) +} diff --git a/metricbeat/module/kubernetes/state_node/state_node_test.go b/metricbeat/module/kubernetes/state_node/state_node_test.go new file mode 100644 index 00000000000..1c0ea74fa2b --- /dev/null +++ b/metricbeat/module/kubernetes/state_node/state_node_test.go @@ -0,0 +1,76 @@ +// +build !integration + +package state_node + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/elastic/beats/libbeat/common" + mbtest "github.com/elastic/beats/metricbeat/mb/testing" + + "github.com/stretchr/testify/assert" +) + +const testFile = "../_meta/test/kube-state-metrics" + +func TestEventMapping(t *testing.T) { + + file, err := os.Open(testFile) + assert.NoError(t, err, "cannot open test file "+testFile) + + body, err := ioutil.ReadAll(file) + assert.NoError(t, err, "cannot read test file "+testFile) + + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + w.Header().Set("Content-Type", "text/plain; charset=ISO-8859-1") + w.Write([]byte(body)) + })) + + server.Start() + defer server.Close() + + config := map[string]interface{}{ + "module": "kubernetes", + "metricsets": []string{"state_node"}, + "hosts": []string{server.URL}, + } + + f := mbtest.NewEventsFetcher(t, config) + + events, err := f.Fetch() + assert.NoError(t, err) + + assert.Equal(t, 1, len(events), "Wrong number of returned events") + + testCases := map[string]interface{}{ + "_namespace": "node", + "name": "minikube", + + "status.ready": "true", + "status.unschedulable": false, + + "cpu.allocatable.cores": 2, + "cpu.capacity.cores": 2, + + "memory.allocatable.bytes": 2097786880, + "memory.capacity.bytes": 2097786880, + + "pod.allocatable.total": 110, + "pod.capacity.total": 110, + } + + for k, v := range testCases { + testValue(t, events[0], k, v) + } +} + +func testValue(t *testing.T, event common.MapStr, field string, expected interface{}) { + data, err := event.GetValue(field) + assert.NoError(t, err, "Could not read field "+field) + assert.EqualValues(t, expected, data, "Wrong value for field "+field) +} diff --git a/metricbeat/module/kubernetes/state_pod/_meta/data.json b/metricbeat/module/kubernetes/state_pod/_meta/data.json new file mode 100644 index 00000000000..7b07380ecc8 --- /dev/null +++ b/metricbeat/module/kubernetes/state_pod/_meta/data.json @@ -0,0 +1,31 @@ +{ + "@timestamp": "2017-05-10T16:46:17.825Z", + "beat": { + "hostname": "X1", + "name": "X1", + "version": "6.0.0-alpha1" + }, + "kubernetes": { + "namespace": "kube-system", + "node": { + "name": "minikube" + }, + "pod": { + "host_ip": "192.168.99.100", + "ip": "172.17.0.3", + "name": "tiller-deploy-3067024529-1gp80", + "status": { + "phase": "running", + "ready": "true", + "scheduled": "true" + } + } + }, + "metricset": { + "host": "192.168.99.100:18080", + "module": "kubernetes", + "name": "state_pod", + "namespace": "pod", + "rtt": 3911 + } +} diff --git a/metricbeat/module/kubernetes/state_pod/_meta/docs.asciidoc b/metricbeat/module/kubernetes/state_pod/_meta/docs.asciidoc new file mode 100644 index 00000000000..dc2e89e9447 --- /dev/null +++ b/metricbeat/module/kubernetes/state_pod/_meta/docs.asciidoc @@ -0,0 +1,3 @@ +=== kubernetes state_pod MetricSet + +This is the state_pod metricset of the module kubernetes. diff --git a/metricbeat/module/kubernetes/state_pod/_meta/fields.yml b/metricbeat/module/kubernetes/state_pod/_meta/fields.yml new file mode 100644 index 00000000000..338f0193ca8 --- /dev/null +++ b/metricbeat/module/kubernetes/state_pod/_meta/fields.yml @@ -0,0 +1,30 @@ +- name: pod + type: group + description: > + kubernetes pod metrics + fields: + - name: ip + type: ip + description: > + Kubernetes pod IP + - name: host_ip + type: ip + description: > + Kubernetes pod host IP + - name: status + type: group + description: > + Kubernetes pod status metrics + fields: + - name: phase + type: keyword + description: > + Kubernetes pod phase (Running, Pending...) + - name: ready + type: keyword + description: > + Kubernetes pod ready status (true, false or unknown) + - name: scheduled + type: keyword + description: > + Kubernetes pod scheduled status (true, false, unknown) diff --git a/metricbeat/module/kubernetes/state_pod/data.go b/metricbeat/module/kubernetes/state_pod/data.go new file mode 100644 index 00000000000..2a9845ac0e0 --- /dev/null +++ b/metricbeat/module/kubernetes/state_pod/data.go @@ -0,0 +1,68 @@ +package state_pod + +import ( + "strings" + + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/module/kubernetes/util" + + dto "github.com/prometheus/client_model/go" +) + +func eventMapping(families []*dto.MetricFamily) ([]common.MapStr, error) { + eventsMap := map[string]common.MapStr{} + for _, family := range families { + for _, metric := range family.GetMetric() { + pod := util.GetLabel(metric, "pod") + if pod == "" { + continue + } + event, ok := eventsMap[pod] + if !ok { + event = common.MapStr{} + eventsMap[pod] = event + } + switch family.GetName() { + case "kube_pod_info": + event.Put(mb.ModuleDataKey+".node.name", util.GetLabel(metric, "node")) + event.Put(mb.ModuleDataKey+".namespace", util.GetLabel(metric, "namespace")) + event.Put(mb.NamespaceKey, "pod") + + event.Put("name", util.GetLabel(metric, "pod")) + + podIP := util.GetLabel(metric, "pod_ip") + hostIP := util.GetLabel(metric, "host_ip") + if podIP != "" { + event.Put("ip", podIP) + } + if hostIP != "" { + event.Put("host_ip", hostIP) + } + + case "kube_pod_status_phase": + event.Put("status.phase", strings.ToLower(util.GetLabel(metric, "phase"))) + + case "kube_pod_status_ready": + if metric.GetGauge().GetValue() == 1 { + event.Put("status.ready", util.GetLabel(metric, "condition")) + } + + case "kube_pod_status_scheduled": + if metric.GetGauge().GetValue() == 1 { + event.Put("status.scheduled", util.GetLabel(metric, "condition")) + } + + default: + // Ignore unknown metric + continue + } + } + } + + var events []common.MapStr + for _, event := range eventsMap { + events = append(events, event) + } + return events, nil +} diff --git a/metricbeat/module/kubernetes/state_pod/state_pod.go b/metricbeat/module/kubernetes/state_pod/state_pod.go new file mode 100644 index 00000000000..327f85d5e4a --- /dev/null +++ b/metricbeat/module/kubernetes/state_pod/state_pod.go @@ -0,0 +1,62 @@ +package state_pod + +import ( + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/libbeat/logp" + "github.com/elastic/beats/metricbeat/helper" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/mb/parse" +) + +const ( + defaultScheme = "http" + defaultPath = "/metrics" +) + +var ( + hostParser = parse.URLHostParserBuilder{ + DefaultScheme: defaultScheme, + DefaultPath: defaultPath, + }.Build() +) + +// init registers the MetricSet with the central registry. +// The New method will be called after the setup of the module and before starting to fetch data +func init() { + if err := mb.Registry.AddMetricSet("kubernetes", "state_pod", New, hostParser); err != nil { + panic(err) + } +} + +// MetricSet type defines all fields of the MetricSet +// As a minimum it must inherit the mb.BaseMetricSet fields, but can be extended with +// additional entries. These variables can be used to persist data or configuration between +// multiple fetch calls. +type MetricSet struct { + mb.BaseMetricSet + prometheus *helper.Prometheus +} + +// New create a new instance of the MetricSet +// Part of new is also setting up the configuration by processing additional +// configuration entries if needed. +func New(base mb.BaseMetricSet) (mb.MetricSet, error) { + logp.Beta("The kubernetes state_pod metricset is beta") + + return &MetricSet{ + BaseMetricSet: base, + prometheus: helper.NewPrometheusClient(base), + }, nil +} + +// Fetch methods implements the data gathering and data conversion to the right format +// It returns the event which is then forward to the output. In case of an error, a +// descriptive error must be returned. +func (m *MetricSet) Fetch() ([]common.MapStr, error) { + families, err := m.prometheus.GetFamilies() + if err != nil { + return nil, err + } + + return eventMapping(families) +} diff --git a/metricbeat/module/kubernetes/state_pod/state_pod_test.go b/metricbeat/module/kubernetes/state_pod/state_pod_test.go new file mode 100644 index 00000000000..7ec290c1032 --- /dev/null +++ b/metricbeat/module/kubernetes/state_pod/state_pod_test.go @@ -0,0 +1,80 @@ +// +build !integration + +package state_pod + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/elastic/beats/libbeat/common" + mbtest "github.com/elastic/beats/metricbeat/mb/testing" + + "github.com/stretchr/testify/assert" +) + +const testFile = "../_meta/test/kube-state-metrics" + +func TestEventMapping(t *testing.T) { + + file, err := os.Open(testFile) + assert.NoError(t, err, "cannot open test file "+testFile) + + body, err := ioutil.ReadAll(file) + assert.NoError(t, err, "cannot read test file "+testFile) + + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + w.Header().Set("Content-Type", "text/plain; charset=ISO-8859-1") + w.Write([]byte(body)) + })) + + server.Start() + defer server.Close() + + config := map[string]interface{}{ + "module": "kubernetes", + "metricsets": []string{"state_pod"}, + "hosts": []string{server.URL}, + } + + f := mbtest.NewEventsFetcher(t, config) + + events, err := f.Fetch() + assert.NoError(t, err) + + assert.Equal(t, 8, len(events), "Wrong number of returned events") + + testCases := map[string]interface{}{ + "_module.namespace": "default", + "_module.node.name": "minikube", + "name": "jumpy-owl-redis-3481028193-s78x9", + + "host_ip": "192.168.99.100", + "ip": "172.17.0.4", + + "status.phase": "running", + "status.ready": "false", + "status.scheduled": "true", + } + + for _, event := range events { + name, err := event.GetValue("name") + if err == nil && name == "jumpy-owl-redis-3481028193-s78x9" { + for k, v := range testCases { + testValue(t, event, k, v) + } + return + } + } + + t.Error("Test reference event not found") +} + +func testValue(t *testing.T, event common.MapStr, field string, expected interface{}) { + data, err := event.GetValue(field) + assert.NoError(t, err, "Could not read field "+field) + assert.EqualValues(t, expected, data, "Wrong value for field "+field) +} diff --git a/metricbeat/module/kubernetes/state_replicaset/_meta/data.json b/metricbeat/module/kubernetes/state_replicaset/_meta/data.json new file mode 100644 index 00000000000..83d0c60a9d6 --- /dev/null +++ b/metricbeat/module/kubernetes/state_replicaset/_meta/data.json @@ -0,0 +1,28 @@ +{ + "@timestamp": "2017-05-10T16:46:37.821Z", + "beat": { + "hostname": "X1", + "name": "X1", + "version": "6.0.0-alpha1" + }, + "kubernetes": { + "namespace": "jenkins", + "replicaset": { + "name": "wise-lynx-jenkins-1616735317", + "replicas": { + "available": 1, + "desired": 1, + "labeled": 1, + "observed": 1, + "ready": 1 + } + } + }, + "metricset": { + "host": "192.168.99.100:18080", + "module": "kubernetes", + "name": "state_replicaset", + "namespace": "replicaset", + "rtt": 6719 + } +} diff --git a/metricbeat/module/kubernetes/state_replicaset/_meta/docs.asciidoc b/metricbeat/module/kubernetes/state_replicaset/_meta/docs.asciidoc new file mode 100644 index 00000000000..5c78069ff83 --- /dev/null +++ b/metricbeat/module/kubernetes/state_replicaset/_meta/docs.asciidoc @@ -0,0 +1,3 @@ +=== kubernetes state_replicaset MetricSet + +This is the state_replicaset metricset of the module kubernetes. diff --git a/metricbeat/module/kubernetes/state_replicaset/_meta/fields.yml b/metricbeat/module/kubernetes/state_replicaset/_meta/fields.yml new file mode 100644 index 00000000000..d095dda1c94 --- /dev/null +++ b/metricbeat/module/kubernetes/state_replicaset/_meta/fields.yml @@ -0,0 +1,34 @@ +- name: replicaset + type: group + description: > + kubernetes replica set metrics + fields: + - name: name + type: keyword + description: > + Kubernetes replica set name + - name: replicas + type: group + description: > + Kubernetes replica set paused status + fields: + - name: available + type: long + description: > + The number of replicas per ReplicaSet + - name: desired + type: long + description: > + The number of replicas per ReplicaSet + - name: ready + type: long + description: > + The number of ready replicas per ReplicaSet + - name: observed + type: long + description: > + The generation observed by the ReplicaSet controller + - name: labeled + type: long + description: > + The number of fully labeled replicas per ReplicaSet diff --git a/metricbeat/module/kubernetes/state_replicaset/data.go b/metricbeat/module/kubernetes/state_replicaset/data.go new file mode 100644 index 00000000000..16bddcd9fa1 --- /dev/null +++ b/metricbeat/module/kubernetes/state_replicaset/data.go @@ -0,0 +1,58 @@ +package state_replicaset + +import ( + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/module/kubernetes/util" + + dto "github.com/prometheus/client_model/go" +) + +func eventMapping(families []*dto.MetricFamily) ([]common.MapStr, error) { + eventsMap := map[string]common.MapStr{} + for _, family := range families { + for _, metric := range family.GetMetric() { + replicaset := util.GetLabel(metric, "replicaset") + if replicaset == "" { + continue + } + event, ok := eventsMap[replicaset] + if !ok { + event = common.MapStr{} + eventsMap[replicaset] = event + } + switch family.GetName() { + case "kube_replicaset_metadata_generation": + event.Put(mb.ModuleDataKey+".namespace", util.GetLabel(metric, "namespace")) + event.Put(mb.NamespaceKey, "replicaset") + + event.Put("name", util.GetLabel(metric, "replicaset")) + + case "kube_replicaset_status_replicas": + event.Put("replicas.available", metric.GetGauge().GetValue()) + + case "kube_replicaset_spec_replicas": + event.Put("replicas.desired", metric.GetGauge().GetValue()) + + case "kube_replicaset_status_ready_replicas": + event.Put("replicas.ready", metric.GetGauge().GetValue()) + + case "kube_replicaset_status_observed_generation": + event.Put("replicas.observed", metric.GetGauge().GetValue()) + + case "kube_replicaset_status_fully_labeled_replicas": + event.Put("replicas.labeled", metric.GetGauge().GetValue()) + + default: + // Ignore unknown metric + continue + } + } + } + + var events []common.MapStr + for _, event := range eventsMap { + events = append(events, event) + } + return events, nil +} diff --git a/metricbeat/module/kubernetes/state_replicaset/state_replicaset.go b/metricbeat/module/kubernetes/state_replicaset/state_replicaset.go new file mode 100644 index 00000000000..ba0f046f913 --- /dev/null +++ b/metricbeat/module/kubernetes/state_replicaset/state_replicaset.go @@ -0,0 +1,62 @@ +package state_replicaset + +import ( + "github.com/elastic/beats/libbeat/common" + "github.com/elastic/beats/libbeat/logp" + "github.com/elastic/beats/metricbeat/helper" + "github.com/elastic/beats/metricbeat/mb" + "github.com/elastic/beats/metricbeat/mb/parse" +) + +const ( + defaultScheme = "http" + defaultPath = "/metrics" +) + +var ( + hostParser = parse.URLHostParserBuilder{ + DefaultScheme: defaultScheme, + DefaultPath: defaultPath, + }.Build() +) + +// init registers the MetricSet with the central registry. +// The New method will be called after the setup of the module and before starting to fetch data +func init() { + if err := mb.Registry.AddMetricSet("kubernetes", "state_replicaset", New, hostParser); err != nil { + panic(err) + } +} + +// MetricSet type defines all fields of the MetricSet +// As a minimum it must inherit the mb.BaseMetricSet fields, but can be extended with +// additional entries. These variables can be used to persist data or configuration between +// multiple fetch calls. +type MetricSet struct { + mb.BaseMetricSet + prometheus *helper.Prometheus +} + +// New create a new instance of the MetricSet +// Part of new is also setting up the configuration by processing additional +// configuration entries if needed. +func New(base mb.BaseMetricSet) (mb.MetricSet, error) { + logp.Beta("The kubernetes state_replicaset metricset is beta") + + return &MetricSet{ + BaseMetricSet: base, + prometheus: helper.NewPrometheusClient(base), + }, nil +} + +// Fetch methods implements the data gathering and data conversion to the right format +// It returns the event which is then forward to the output. In case of an error, a +// descriptive error must be returned. +func (m *MetricSet) Fetch() ([]common.MapStr, error) { + families, err := m.prometheus.GetFamilies() + if err != nil { + return nil, err + } + + return eventMapping(families) +} diff --git a/metricbeat/module/kubernetes/state_replicaset/state_replicaset_test.go b/metricbeat/module/kubernetes/state_replicaset/state_replicaset_test.go new file mode 100644 index 00000000000..2091e42b200 --- /dev/null +++ b/metricbeat/module/kubernetes/state_replicaset/state_replicaset_test.go @@ -0,0 +1,78 @@ +// +build !integration + +package state_replicaset + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/elastic/beats/libbeat/common" + mbtest "github.com/elastic/beats/metricbeat/mb/testing" + + "github.com/stretchr/testify/assert" +) + +const testFile = "../_meta/test/kube-state-metrics" + +func TestEventMapping(t *testing.T) { + + file, err := os.Open(testFile) + assert.NoError(t, err, "cannot open test file "+testFile) + + body, err := ioutil.ReadAll(file) + assert.NoError(t, err, "cannot read test file "+testFile) + + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + w.Header().Set("Content-Type", "text/plain; charset=ISO-8859-1") + w.Write([]byte(body)) + })) + + server.Start() + defer server.Close() + + config := map[string]interface{}{ + "module": "kubernetes", + "metricsets": []string{"state_replicaset"}, + "hosts": []string{server.URL}, + } + + f := mbtest.NewEventsFetcher(t, config) + + events, err := f.Fetch() + assert.NoError(t, err) + + assert.Equal(t, 4, len(events), "Wrong number of returned events") + + testCases := map[string]interface{}{ + "_module.namespace": "kube-system", + "name": "kube-state-metrics-1303537707", + + "replicas.labeled": 2, + "replicas.observed": 1, + "replicas.ready": 1, + "replicas.available": 2, + "replicas.desired": 2, + } + + for _, event := range events { + name, err := event.GetValue("name") + if err == nil && name == "kube-state-metrics-1303537707" { + for k, v := range testCases { + testValue(t, event, k, v) + } + return + } + } + + t.Error("Test reference event not found") +} + +func testValue(t *testing.T, event common.MapStr, field string, expected interface{}) { + data, err := event.GetValue(field) + assert.NoError(t, err, "Could not read field "+field) + assert.EqualValues(t, expected, data, "Wrong value for field "+field) +} diff --git a/metricbeat/module/kubernetes/system/_meta/fields.yml b/metricbeat/module/kubernetes/system/_meta/fields.yml index 572477f887d..d53bb0a7541 100644 --- a/metricbeat/module/kubernetes/system/_meta/fields.yml +++ b/metricbeat/module/kubernetes/system/_meta/fields.yml @@ -7,6 +7,10 @@ type: keyword description: > Container name + - name: start_time + type: date + description: > + Start time - name: cpu type: group description: > diff --git a/metricbeat/module/kubernetes/util/prometheus.go b/metricbeat/module/kubernetes/util/prometheus.go new file mode 100644 index 00000000000..704857943af --- /dev/null +++ b/metricbeat/module/kubernetes/util/prometheus.go @@ -0,0 +1,13 @@ +package util + +import dto "github.com/prometheus/client_model/go" + +// GetLabel returns desired label from the given metric, or "" if not present +func GetLabel(m *dto.Metric, label string) string { + for _, l := range m.GetLabel() { + if l.GetName() == label { + return l.GetValue() + } + } + return "" +} diff --git a/metricbeat/module/prometheus/collector/collector.go b/metricbeat/module/prometheus/collector/collector.go index 373d4724b3f..cdf91767109 100644 --- a/metricbeat/module/prometheus/collector/collector.go +++ b/metricbeat/module/prometheus/collector/collector.go @@ -8,7 +8,6 @@ import ( "github.com/elastic/beats/metricbeat/helper" "github.com/elastic/beats/metricbeat/mb" "github.com/elastic/beats/metricbeat/mb/parse" - "github.com/elastic/beats/metricbeat/module/prometheus" ) const ( @@ -32,8 +31,8 @@ func init() { type MetricSet struct { mb.BaseMetricSet - http *helper.HTTP - namespace string + prometheus *helper.Prometheus + namespace string } func New(base mb.BaseMetricSet) (mb.MetricSet, error) { @@ -49,19 +48,13 @@ func New(base mb.BaseMetricSet) (mb.MetricSet, error) { return &MetricSet{ BaseMetricSet: base, - http: helper.NewHTTP(base), + prometheus: helper.NewPrometheusClient(base), namespace: config.Namespace, }, nil } func (m *MetricSet) Fetch() ([]common.MapStr, error) { - - resp, err := m.http.FetchResponse() - if err != nil { - return nil, err - } - defer resp.Body.Close() - families, err := prometheus.GetMetricFamiliesFromResponse(resp) + families, err := m.prometheus.GetFamilies() if err != nil { return nil, fmt.Errorf("Unable to decode response from prometheus endpoint") @@ -80,11 +73,9 @@ func (m *MetricSet) Fetch() ([]common.MapStr, error) { if len(promEvent.labels) > 0 { eventList[promEvent.labelHash]["label"] = promEvent.labels } - } eventList[promEvent.labelHash][promEvent.key] = promEvent.value - } } diff --git a/metricbeat/module/prometheus/utils.go b/metricbeat/module/prometheus/utils.go deleted file mode 100644 index 6afd5a92f7e..00000000000 --- a/metricbeat/module/prometheus/utils.go +++ /dev/null @@ -1,33 +0,0 @@ -package prometheus - -import ( - "fmt" - "net/http" - - dto "github.com/prometheus/client_model/go" - "github.com/prometheus/common/expfmt" -) - -func GetMetricFamiliesFromResponse(resp *http.Response) ([]*dto.MetricFamily, error) { - format := expfmt.ResponseFormat(resp.Header) - if format == "" { - return nil, fmt.Errorf("Invalid format for response of response") - } - - decoder := expfmt.NewDecoder(resp.Body, format) - if decoder == nil { - return nil, fmt.Errorf("Unable to create decoder to decode response") - } - - var err error - result := []*dto.MetricFamily{} - for err == nil { - mf := &dto.MetricFamily{} - err = decoder.Decode(mf) - if err == nil { - result = append(result, mf) - } - } - - return result, nil -} diff --git a/metricbeat/module/prometheus/vendor/bitbucket.org/ww/goautoneg/Makefile b/metricbeat/module/prometheus/vendor/bitbucket.org/ww/goautoneg/Makefile deleted file mode 100644 index e33ee173036..00000000000 --- a/metricbeat/module/prometheus/vendor/bitbucket.org/ww/goautoneg/Makefile +++ /dev/null @@ -1,13 +0,0 @@ -include $(GOROOT)/src/Make.inc - -TARG=bitbucket.org/ww/goautoneg -GOFILES=autoneg.go - -include $(GOROOT)/src/Make.pkg - -format: - gofmt -w *.go - -docs: - gomake clean - godoc ${TARG} > README.txt diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt b/metricbeat/module/prometheus/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt deleted file mode 100644 index 7723656d58d..00000000000 --- a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt +++ /dev/null @@ -1,67 +0,0 @@ -PACKAGE - -package goautoneg -import "bitbucket.org/ww/goautoneg" - -HTTP Content-Type Autonegotiation. - -The functions in this package implement the behaviour specified in -http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html - -Copyright (c) 2011, Open Knowledge Foundation Ltd. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - - Neither the name of the Open Knowledge Foundation Ltd. nor the - names of its contributors may be used to endorse or promote - products derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -FUNCTIONS - -func Negotiate(header string, alternatives []string) (content_type string) -Negotiate the most appropriate content_type given the accept header -and a list of alternatives. - -func ParseAccept(header string) (accept []Accept) -Parse an Accept Header string returning a sorted list -of clauses - - -TYPES - -type Accept struct { - Type, SubType string - Q float32 - Params map[string]string -} -Structure to represent a clause in an HTTP Accept Header - - -SUBDIRECTORIES - - .hg diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go b/metricbeat/module/prometheus/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go deleted file mode 100644 index 648b38cb654..00000000000 --- a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go +++ /dev/null @@ -1,162 +0,0 @@ -/* -HTTP Content-Type Autonegotiation. - -The functions in this package implement the behaviour specified in -http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html - -Copyright (c) 2011, Open Knowledge Foundation Ltd. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - - Neither the name of the Open Knowledge Foundation Ltd. nor the - names of its contributors may be used to endorse or promote - products derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -*/ -package goautoneg - -import ( - "sort" - "strconv" - "strings" -) - -// Structure to represent a clause in an HTTP Accept Header -type Accept struct { - Type, SubType string - Q float64 - Params map[string]string -} - -// For internal use, so that we can use the sort interface -type accept_slice []Accept - -func (accept accept_slice) Len() int { - slice := []Accept(accept) - return len(slice) -} - -func (accept accept_slice) Less(i, j int) bool { - slice := []Accept(accept) - ai, aj := slice[i], slice[j] - if ai.Q > aj.Q { - return true - } - if ai.Type != "*" && aj.Type == "*" { - return true - } - if ai.SubType != "*" && aj.SubType == "*" { - return true - } - return false -} - -func (accept accept_slice) Swap(i, j int) { - slice := []Accept(accept) - slice[i], slice[j] = slice[j], slice[i] -} - -// Parse an Accept Header string returning a sorted list -// of clauses -func ParseAccept(header string) (accept []Accept) { - parts := strings.Split(header, ",") - accept = make([]Accept, 0, len(parts)) - for _, part := range parts { - part := strings.Trim(part, " ") - - a := Accept{} - a.Params = make(map[string]string) - a.Q = 1.0 - - mrp := strings.Split(part, ";") - - media_range := mrp[0] - sp := strings.Split(media_range, "/") - a.Type = strings.Trim(sp[0], " ") - - switch { - case len(sp) == 1 && a.Type == "*": - a.SubType = "*" - case len(sp) == 2: - a.SubType = strings.Trim(sp[1], " ") - default: - continue - } - - if len(mrp) == 1 { - accept = append(accept, a) - continue - } - - for _, param := range mrp[1:] { - sp := strings.SplitN(param, "=", 2) - if len(sp) != 2 { - continue - } - token := strings.Trim(sp[0], " ") - if token == "q" { - a.Q, _ = strconv.ParseFloat(sp[1], 32) - } else { - a.Params[token] = strings.Trim(sp[1], " ") - } - } - - accept = append(accept, a) - } - - slice := accept_slice(accept) - sort.Sort(slice) - - return -} - -// Negotiate the most appropriate content_type given the accept header -// and a list of alternatives. -func Negotiate(header string, alternatives []string) (content_type string) { - asp := make([][]string, 0, len(alternatives)) - for _, ctype := range alternatives { - asp = append(asp, strings.SplitN(ctype, "/", 2)) - } - for _, clause := range ParseAccept(header) { - for i, ctsp := range asp { - if clause.Type == ctsp[0] && clause.SubType == ctsp[1] { - content_type = alternatives[i] - return - } - if clause.Type == ctsp[0] && clause.SubType == "*" { - content_type = alternatives[i] - return - } - if clause.Type == "*" && clause.SubType == "*" { - content_type = alternatives[i] - return - } - } - } - return -} diff --git a/metricbeat/tests/system/test_kubernetes.py b/metricbeat/tests/system/test_kubernetes.py new file mode 100644 index 00000000000..f70971dadca --- /dev/null +++ b/metricbeat/tests/system/test_kubernetes.py @@ -0,0 +1,84 @@ +import os +import metricbeat +import unittest + +KUBERNETES_FIELDS = metricbeat.COMMON_FIELDS + ["kubernetes"] + + +class Test(metricbeat.BaseTest): + + @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, "integration test") + def test_kubelet_node(self): + """ Kubernetes kubelet node metricset tests """ + self._test_metricset('node', 1, self.get_kubelet_hosts()) + + @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, "integration test") + def test_kubelet_system(self): + """ Kubernetes kubelet system metricset tests """ + self._test_metricset('system', 2, self.get_kubelet_hosts()) + + @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, "integration test") + def test_kubelet_pod(self): + """ Kubernetes kubelet pod metricset tests """ + self._test_metricset('pod', 1, self.get_kubelet_hosts()) + + @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, "integration test") + def test_kubelet_container(self): + """ Kubernetes kubelet container metricset tests """ + self._test_metricset('container', 1, self.get_kubelet_hosts()) + + @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, "integration test") + def test_state_node(self): + """ Kubernetes state node metricset tests """ + self._test_metricset('state_node', 1, self.get_kube_state_hosts()) + + @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, "integration test") + def test_state_pod(self): + """ Kubernetes state pod metricset tests """ + self._test_metricset('state_pod', 1, self.get_kube_state_hosts()) + + @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, "integration test") + def test_state_container(self): + """ Kubernetes state container metricset tests """ + self._test_metricset('state_container', 1, self.get_kube_state_hosts()) + + def _test_metricset(self, metricset, expected_events, hosts): + self.render_config_template(modules=[{ + "name": "kubernetes", + "enabled": "true", + "metricsets": [metricset], + "hosts": hosts, + "period": "5s" + }]) + + proc = self.start_beat() + self.wait_until(lambda: self.output_lines() > 0) + proc.check_kill_and_wait() + + # Ensure no errors or warnings exist in the log. + log = self.get_log() + self.assertNotRegexpMatches(log.replace("WARN BETA", ""), "ERR|WARN") + + output = self.read_output_json() + self.assertEqual(len(output), expected_events) + evt = output[0] + + self.assertItemsEqual(self.de_dot(KUBERNETES_FIELDS), evt.keys(), evt) + + self.assert_fields_are_documented(evt) + + @classmethod + def get_kubelet_hosts(cls): + return [ + "http://" + + os.getenv('KUBELET_HOST', 'localhost') + ':' + + os.getenv('KUBELET_PORT', '10255') + ] + + @classmethod + def get_kube_state_hosts(cls): + return [ + "http://" + + os.getenv('KUBE_STATE_METRICS_HOST', 'localhost') + ':' + + os.getenv('KUBE_STATE_METRICS_PORT', '18080') + ] diff --git a/metricbeat/vendor/github.com/golang/protobuf/LICENSE b/metricbeat/vendor/github.com/golang/protobuf/LICENSE new file mode 100644 index 00000000000..1b1b1921efa --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/LICENSE @@ -0,0 +1,31 @@ +Go support for Protocol Buffers - Google's data interchange format + +Copyright 2010 The Go Authors. All rights reserved. +https://github.com/golang/protobuf + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/Makefile b/metricbeat/vendor/github.com/golang/protobuf/proto/Makefile new file mode 100644 index 00000000000..e2e0651a934 --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/Makefile @@ -0,0 +1,43 @@ +# Go support for Protocol Buffers - Google's data interchange format +# +# Copyright 2010 The Go Authors. All rights reserved. +# https://github.com/golang/protobuf +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +install: + go install + +test: install generate-test-pbs + go test + + +generate-test-pbs: + make install + make -C testdata + protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto + make diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/clone.go b/metricbeat/vendor/github.com/golang/protobuf/proto/clone.go new file mode 100644 index 00000000000..e392575b353 --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/clone.go @@ -0,0 +1,229 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2011 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Protocol buffer deep copy and merge. +// TODO: RawMessage. + +package proto + +import ( + "log" + "reflect" + "strings" +) + +// Clone returns a deep copy of a protocol buffer. +func Clone(pb Message) Message { + in := reflect.ValueOf(pb) + if in.IsNil() { + return pb + } + + out := reflect.New(in.Type().Elem()) + // out is empty so a merge is a deep copy. + mergeStruct(out.Elem(), in.Elem()) + return out.Interface().(Message) +} + +// Merge merges src into dst. +// Required and optional fields that are set in src will be set to that value in dst. +// Elements of repeated fields will be appended. +// Merge panics if src and dst are not the same type, or if dst is nil. +func Merge(dst, src Message) { + in := reflect.ValueOf(src) + out := reflect.ValueOf(dst) + if out.IsNil() { + panic("proto: nil destination") + } + if in.Type() != out.Type() { + // Explicit test prior to mergeStruct so that mistyped nils will fail + panic("proto: type mismatch") + } + if in.IsNil() { + // Merging nil into non-nil is a quiet no-op + return + } + mergeStruct(out.Elem(), in.Elem()) +} + +func mergeStruct(out, in reflect.Value) { + sprop := GetProperties(in.Type()) + for i := 0; i < in.NumField(); i++ { + f := in.Type().Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) + } + + if emIn, ok := extendable(in.Addr().Interface()); ok { + emOut, _ := extendable(out.Addr().Interface()) + mIn, muIn := emIn.extensionsRead() + if mIn != nil { + mOut := emOut.extensionsWrite() + muIn.Lock() + mergeExtension(mOut, mIn) + muIn.Unlock() + } + } + + uf := in.FieldByName("XXX_unrecognized") + if !uf.IsValid() { + return + } + uin := uf.Bytes() + if len(uin) > 0 { + out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) + } +} + +// mergeAny performs a merge between two values of the same type. +// viaPtr indicates whether the values were indirected through a pointer (implying proto2). +// prop is set if this is a struct field (it may be nil). +func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { + if in.Type() == protoMessageType { + if !in.IsNil() { + if out.IsNil() { + out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) + } else { + Merge(out.Interface().(Message), in.Interface().(Message)) + } + } + return + } + switch in.Kind() { + case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, + reflect.String, reflect.Uint32, reflect.Uint64: + if !viaPtr && isProto3Zero(in) { + return + } + out.Set(in) + case reflect.Interface: + // Probably a oneof field; copy non-nil values. + if in.IsNil() { + return + } + // Allocate destination if it is not set, or set to a different type. + // Otherwise we will merge as normal. + if out.IsNil() || out.Elem().Type() != in.Elem().Type() { + out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) + } + mergeAny(out.Elem(), in.Elem(), false, nil) + case reflect.Map: + if in.Len() == 0 { + return + } + if out.IsNil() { + out.Set(reflect.MakeMap(in.Type())) + } + // For maps with value types of *T or []byte we need to deep copy each value. + elemKind := in.Type().Elem().Kind() + for _, key := range in.MapKeys() { + var val reflect.Value + switch elemKind { + case reflect.Ptr: + val = reflect.New(in.Type().Elem().Elem()) + mergeAny(val, in.MapIndex(key), false, nil) + case reflect.Slice: + val = in.MapIndex(key) + val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) + default: + val = in.MapIndex(key) + } + out.SetMapIndex(key, val) + } + case reflect.Ptr: + if in.IsNil() { + return + } + if out.IsNil() { + out.Set(reflect.New(in.Elem().Type())) + } + mergeAny(out.Elem(), in.Elem(), true, nil) + case reflect.Slice: + if in.IsNil() { + return + } + if in.Type().Elem().Kind() == reflect.Uint8 { + // []byte is a scalar bytes field, not a repeated field. + + // Edge case: if this is in a proto3 message, a zero length + // bytes field is considered the zero value, and should not + // be merged. + if prop != nil && prop.proto3 && in.Len() == 0 { + return + } + + // Make a deep copy. + // Append to []byte{} instead of []byte(nil) so that we never end up + // with a nil result. + out.SetBytes(append([]byte{}, in.Bytes()...)) + return + } + n := in.Len() + if out.IsNil() { + out.Set(reflect.MakeSlice(in.Type(), 0, n)) + } + switch in.Type().Elem().Kind() { + case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, + reflect.String, reflect.Uint32, reflect.Uint64: + out.Set(reflect.AppendSlice(out, in)) + default: + for i := 0; i < n; i++ { + x := reflect.Indirect(reflect.New(in.Type().Elem())) + mergeAny(x, in.Index(i), false, nil) + out.Set(reflect.Append(out, x)) + } + } + case reflect.Struct: + mergeStruct(out, in) + default: + // unknown type, so not a protocol buffer + log.Printf("proto: don't know how to copy %v", in) + } +} + +func mergeExtension(out, in map[int32]Extension) { + for extNum, eIn := range in { + eOut := Extension{desc: eIn.desc} + if eIn.value != nil { + v := reflect.New(reflect.TypeOf(eIn.value)).Elem() + mergeAny(v, reflect.ValueOf(eIn.value), false, nil) + eOut.value = v.Interface() + } + if eIn.enc != nil { + eOut.enc = make([]byte, len(eIn.enc)) + copy(eOut.enc, eIn.enc) + } + + out[extNum] = eOut + } +} diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/decode.go b/metricbeat/vendor/github.com/golang/protobuf/proto/decode.go new file mode 100644 index 00000000000..aa207298f99 --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/decode.go @@ -0,0 +1,970 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Routines for decoding protocol buffer data to construct in-memory representations. + */ + +import ( + "errors" + "fmt" + "io" + "os" + "reflect" +) + +// errOverflow is returned when an integer is too large to be represented. +var errOverflow = errors.New("proto: integer overflow") + +// ErrInternalBadWireType is returned by generated code when an incorrect +// wire type is encountered. It does not get returned to user code. +var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") + +// The fundamental decoders that interpret bytes on the wire. +// Those that take integer types all return uint64 and are +// therefore of type valueDecoder. + +// DecodeVarint reads a varint-encoded integer from the slice. +// It returns the integer and the number of bytes consumed, or +// zero if there is not enough. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func DecodeVarint(buf []byte) (x uint64, n int) { + for shift := uint(0); shift < 64; shift += 7 { + if n >= len(buf) { + return 0, 0 + } + b := uint64(buf[n]) + n++ + x |= (b & 0x7F) << shift + if (b & 0x80) == 0 { + return x, n + } + } + + // The number is too large to represent in a 64-bit value. + return 0, 0 +} + +func (p *Buffer) decodeVarintSlow() (x uint64, err error) { + i := p.index + l := len(p.buf) + + for shift := uint(0); shift < 64; shift += 7 { + if i >= l { + err = io.ErrUnexpectedEOF + return + } + b := p.buf[i] + i++ + x |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + p.index = i + return + } + } + + // The number is too large to represent in a 64-bit value. + err = errOverflow + return +} + +// DecodeVarint reads a varint-encoded integer from the Buffer. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func (p *Buffer) DecodeVarint() (x uint64, err error) { + i := p.index + buf := p.buf + + if i >= len(buf) { + return 0, io.ErrUnexpectedEOF + } else if buf[i] < 0x80 { + p.index++ + return uint64(buf[i]), nil + } else if len(buf)-i < 10 { + return p.decodeVarintSlow() + } + + var b uint64 + // we already checked the first byte + x = uint64(buf[i]) - 0x80 + i++ + + b = uint64(buf[i]) + i++ + x += b << 7 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 7 + + b = uint64(buf[i]) + i++ + x += b << 14 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 14 + + b = uint64(buf[i]) + i++ + x += b << 21 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 21 + + b = uint64(buf[i]) + i++ + x += b << 28 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 28 + + b = uint64(buf[i]) + i++ + x += b << 35 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 35 + + b = uint64(buf[i]) + i++ + x += b << 42 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 42 + + b = uint64(buf[i]) + i++ + x += b << 49 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 49 + + b = uint64(buf[i]) + i++ + x += b << 56 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 56 + + b = uint64(buf[i]) + i++ + x += b << 63 + if b&0x80 == 0 { + goto done + } + // x -= 0x80 << 63 // Always zero. + + return 0, errOverflow + +done: + p.index = i + return x, nil +} + +// DecodeFixed64 reads a 64-bit integer from the Buffer. +// This is the format for the +// fixed64, sfixed64, and double protocol buffer types. +func (p *Buffer) DecodeFixed64() (x uint64, err error) { + // x, err already 0 + i := p.index + 8 + if i < 0 || i > len(p.buf) { + err = io.ErrUnexpectedEOF + return + } + p.index = i + + x = uint64(p.buf[i-8]) + x |= uint64(p.buf[i-7]) << 8 + x |= uint64(p.buf[i-6]) << 16 + x |= uint64(p.buf[i-5]) << 24 + x |= uint64(p.buf[i-4]) << 32 + x |= uint64(p.buf[i-3]) << 40 + x |= uint64(p.buf[i-2]) << 48 + x |= uint64(p.buf[i-1]) << 56 + return +} + +// DecodeFixed32 reads a 32-bit integer from the Buffer. +// This is the format for the +// fixed32, sfixed32, and float protocol buffer types. +func (p *Buffer) DecodeFixed32() (x uint64, err error) { + // x, err already 0 + i := p.index + 4 + if i < 0 || i > len(p.buf) { + err = io.ErrUnexpectedEOF + return + } + p.index = i + + x = uint64(p.buf[i-4]) + x |= uint64(p.buf[i-3]) << 8 + x |= uint64(p.buf[i-2]) << 16 + x |= uint64(p.buf[i-1]) << 24 + return +} + +// DecodeZigzag64 reads a zigzag-encoded 64-bit integer +// from the Buffer. +// This is the format used for the sint64 protocol buffer type. +func (p *Buffer) DecodeZigzag64() (x uint64, err error) { + x, err = p.DecodeVarint() + if err != nil { + return + } + x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) + return +} + +// DecodeZigzag32 reads a zigzag-encoded 32-bit integer +// from the Buffer. +// This is the format used for the sint32 protocol buffer type. +func (p *Buffer) DecodeZigzag32() (x uint64, err error) { + x, err = p.DecodeVarint() + if err != nil { + return + } + x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) + return +} + +// These are not ValueDecoders: they produce an array of bytes or a string. +// bytes, embedded messages + +// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. +// This is the format used for the bytes protocol buffer +// type and for embedded messages. +func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { + n, err := p.DecodeVarint() + if err != nil { + return nil, err + } + + nb := int(n) + if nb < 0 { + return nil, fmt.Errorf("proto: bad byte length %d", nb) + } + end := p.index + nb + if end < p.index || end > len(p.buf) { + return nil, io.ErrUnexpectedEOF + } + + if !alloc { + // todo: check if can get more uses of alloc=false + buf = p.buf[p.index:end] + p.index += nb + return + } + + buf = make([]byte, nb) + copy(buf, p.buf[p.index:]) + p.index += nb + return +} + +// DecodeStringBytes reads an encoded string from the Buffer. +// This is the format used for the proto2 string type. +func (p *Buffer) DecodeStringBytes() (s string, err error) { + buf, err := p.DecodeRawBytes(false) + if err != nil { + return + } + return string(buf), nil +} + +// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. +// If the protocol buffer has extensions, and the field matches, add it as an extension. +// Otherwise, if the XXX_unrecognized field exists, append the skipped data there. +func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { + oi := o.index + + err := o.skip(t, tag, wire) + if err != nil { + return err + } + + if !unrecField.IsValid() { + return nil + } + + ptr := structPointer_Bytes(base, unrecField) + + // Add the skipped field to struct field + obuf := o.buf + + o.buf = *ptr + o.EncodeVarint(uint64(tag<<3 | wire)) + *ptr = append(o.buf, obuf[oi:o.index]...) + + o.buf = obuf + + return nil +} + +// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. +func (o *Buffer) skip(t reflect.Type, tag, wire int) error { + + var u uint64 + var err error + + switch wire { + case WireVarint: + _, err = o.DecodeVarint() + case WireFixed64: + _, err = o.DecodeFixed64() + case WireBytes: + _, err = o.DecodeRawBytes(false) + case WireFixed32: + _, err = o.DecodeFixed32() + case WireStartGroup: + for { + u, err = o.DecodeVarint() + if err != nil { + break + } + fwire := int(u & 0x7) + if fwire == WireEndGroup { + break + } + ftag := int(u >> 3) + err = o.skip(t, ftag, fwire) + if err != nil { + break + } + } + default: + err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) + } + return err +} + +// Unmarshaler is the interface representing objects that can +// unmarshal themselves. The method should reset the receiver before +// decoding starts. The argument points to data that may be +// overwritten, so implementations should not keep references to the +// buffer. +type Unmarshaler interface { + Unmarshal([]byte) error +} + +// Unmarshal parses the protocol buffer representation in buf and places the +// decoded result in pb. If the struct underlying pb does not match +// the data in buf, the results can be unpredictable. +// +// Unmarshal resets pb before starting to unmarshal, so any +// existing data in pb is always removed. Use UnmarshalMerge +// to preserve and append to existing data. +func Unmarshal(buf []byte, pb Message) error { + pb.Reset() + return UnmarshalMerge(buf, pb) +} + +// UnmarshalMerge parses the protocol buffer representation in buf and +// writes the decoded result to pb. If the struct underlying pb does not match +// the data in buf, the results can be unpredictable. +// +// UnmarshalMerge merges into existing data in pb. +// Most code should use Unmarshal instead. +func UnmarshalMerge(buf []byte, pb Message) error { + // If the object can unmarshal itself, let it. + if u, ok := pb.(Unmarshaler); ok { + return u.Unmarshal(buf) + } + return NewBuffer(buf).Unmarshal(pb) +} + +// DecodeMessage reads a count-delimited message from the Buffer. +func (p *Buffer) DecodeMessage(pb Message) error { + enc, err := p.DecodeRawBytes(false) + if err != nil { + return err + } + return NewBuffer(enc).Unmarshal(pb) +} + +// DecodeGroup reads a tag-delimited group from the Buffer. +func (p *Buffer) DecodeGroup(pb Message) error { + typ, base, err := getbase(pb) + if err != nil { + return err + } + return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base) +} + +// Unmarshal parses the protocol buffer representation in the +// Buffer and places the decoded result in pb. If the struct +// underlying pb does not match the data in the buffer, the results can be +// unpredictable. +// +// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. +func (p *Buffer) Unmarshal(pb Message) error { + // If the object can unmarshal itself, let it. + if u, ok := pb.(Unmarshaler); ok { + err := u.Unmarshal(p.buf[p.index:]) + p.index = len(p.buf) + return err + } + + typ, base, err := getbase(pb) + if err != nil { + return err + } + + err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) + + if collectStats { + stats.Decode++ + } + + return err +} + +// unmarshalType does the work of unmarshaling a structure. +func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { + var state errorState + required, reqFields := prop.reqCount, uint64(0) + + var err error + for err == nil && o.index < len(o.buf) { + oi := o.index + var u uint64 + u, err = o.DecodeVarint() + if err != nil { + break + } + wire := int(u & 0x7) + if wire == WireEndGroup { + if is_group { + if required > 0 { + // Not enough information to determine the exact field. + // (See below.) + return &RequiredNotSetError{"{Unknown}"} + } + return nil // input is satisfied + } + return fmt.Errorf("proto: %s: wiretype end group for non-group", st) + } + tag := int(u >> 3) + if tag <= 0 { + return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) + } + fieldnum, ok := prop.decoderTags.get(tag) + if !ok { + // Maybe it's an extension? + if prop.extendable { + if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) { + if err = o.skip(st, tag, wire); err == nil { + extmap := e.extensionsWrite() + ext := extmap[int32(tag)] // may be missing + ext.enc = append(ext.enc, o.buf[oi:o.index]...) + extmap[int32(tag)] = ext + } + continue + } + } + // Maybe it's a oneof? + if prop.oneofUnmarshaler != nil { + m := structPointer_Interface(base, st).(Message) + // First return value indicates whether tag is a oneof field. + ok, err = prop.oneofUnmarshaler(m, tag, wire, o) + if err == ErrInternalBadWireType { + // Map the error to something more descriptive. + // Do the formatting here to save generated code space. + err = fmt.Errorf("bad wiretype for oneof field in %T", m) + } + if ok { + continue + } + } + err = o.skipAndSave(st, tag, wire, base, prop.unrecField) + continue + } + p := prop.Prop[fieldnum] + + if p.dec == nil { + fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) + continue + } + dec := p.dec + if wire != WireStartGroup && wire != p.WireType { + if wire == WireBytes && p.packedDec != nil { + // a packable field + dec = p.packedDec + } else { + err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) + continue + } + } + decErr := dec(o, p, base) + if decErr != nil && !state.shouldContinue(decErr, p) { + err = decErr + } + if err == nil && p.Required { + // Successfully decoded a required field. + if tag <= 64 { + // use bitmap for fields 1-64 to catch field reuse. + var mask uint64 = 1 << uint64(tag-1) + if reqFields&mask == 0 { + // new required field + reqFields |= mask + required-- + } + } else { + // This is imprecise. It can be fooled by a required field + // with a tag > 64 that is encoded twice; that's very rare. + // A fully correct implementation would require allocating + // a data structure, which we would like to avoid. + required-- + } + } + } + if err == nil { + if is_group { + return io.ErrUnexpectedEOF + } + if state.err != nil { + return state.err + } + if required > 0 { + // Not enough information to determine the exact field. If we use extra + // CPU, we could determine the field only if the missing required field + // has a tag <= 64 and we check reqFields. + return &RequiredNotSetError{"{Unknown}"} + } + } + return err +} + +// Individual type decoders +// For each, +// u is the decoded value, +// v is a pointer to the field (pointer) in the struct + +// Sizes of the pools to allocate inside the Buffer. +// The goal is modest amortization and allocation +// on at least 16-byte boundaries. +const ( + boolPoolSize = 16 + uint32PoolSize = 8 + uint64PoolSize = 4 +) + +// Decode a bool. +func (o *Buffer) dec_bool(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + if len(o.bools) == 0 { + o.bools = make([]bool, boolPoolSize) + } + o.bools[0] = u != 0 + *structPointer_Bool(base, p.field) = &o.bools[0] + o.bools = o.bools[1:] + return nil +} + +func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + *structPointer_BoolVal(base, p.field) = u != 0 + return nil +} + +// Decode an int32. +func (o *Buffer) dec_int32(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) + return nil +} + +func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) + return nil +} + +// Decode an int64. +func (o *Buffer) dec_int64(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + word64_Set(structPointer_Word64(base, p.field), o, u) + return nil +} + +func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + word64Val_Set(structPointer_Word64Val(base, p.field), o, u) + return nil +} + +// Decode a string. +func (o *Buffer) dec_string(p *Properties, base structPointer) error { + s, err := o.DecodeStringBytes() + if err != nil { + return err + } + *structPointer_String(base, p.field) = &s + return nil +} + +func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { + s, err := o.DecodeStringBytes() + if err != nil { + return err + } + *structPointer_StringVal(base, p.field) = s + return nil +} + +// Decode a slice of bytes ([]byte). +func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { + b, err := o.DecodeRawBytes(true) + if err != nil { + return err + } + *structPointer_Bytes(base, p.field) = b + return nil +} + +// Decode a slice of bools ([]bool). +func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + v := structPointer_BoolSlice(base, p.field) + *v = append(*v, u != 0) + return nil +} + +// Decode a slice of bools ([]bool) in packed format. +func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { + v := structPointer_BoolSlice(base, p.field) + + nn, err := o.DecodeVarint() + if err != nil { + return err + } + nb := int(nn) // number of bytes of encoded bools + fin := o.index + nb + if fin < o.index { + return errOverflow + } + + y := *v + for o.index < fin { + u, err := p.valDec(o) + if err != nil { + return err + } + y = append(y, u != 0) + } + + *v = y + return nil +} + +// Decode a slice of int32s ([]int32). +func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + structPointer_Word32Slice(base, p.field).Append(uint32(u)) + return nil +} + +// Decode a slice of int32s ([]int32) in packed format. +func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { + v := structPointer_Word32Slice(base, p.field) + + nn, err := o.DecodeVarint() + if err != nil { + return err + } + nb := int(nn) // number of bytes of encoded int32s + + fin := o.index + nb + if fin < o.index { + return errOverflow + } + for o.index < fin { + u, err := p.valDec(o) + if err != nil { + return err + } + v.Append(uint32(u)) + } + return nil +} + +// Decode a slice of int64s ([]int64). +func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { + u, err := p.valDec(o) + if err != nil { + return err + } + + structPointer_Word64Slice(base, p.field).Append(u) + return nil +} + +// Decode a slice of int64s ([]int64) in packed format. +func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { + v := structPointer_Word64Slice(base, p.field) + + nn, err := o.DecodeVarint() + if err != nil { + return err + } + nb := int(nn) // number of bytes of encoded int64s + + fin := o.index + nb + if fin < o.index { + return errOverflow + } + for o.index < fin { + u, err := p.valDec(o) + if err != nil { + return err + } + v.Append(u) + } + return nil +} + +// Decode a slice of strings ([]string). +func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { + s, err := o.DecodeStringBytes() + if err != nil { + return err + } + v := structPointer_StringSlice(base, p.field) + *v = append(*v, s) + return nil +} + +// Decode a slice of slice of bytes ([][]byte). +func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { + b, err := o.DecodeRawBytes(true) + if err != nil { + return err + } + v := structPointer_BytesSlice(base, p.field) + *v = append(*v, b) + return nil +} + +// Decode a map field. +func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { + raw, err := o.DecodeRawBytes(false) + if err != nil { + return err + } + oi := o.index // index at the end of this map entry + o.index -= len(raw) // move buffer back to start of map entry + + mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V + if mptr.Elem().IsNil() { + mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) + } + v := mptr.Elem() // map[K]V + + // Prepare addressable doubly-indirect placeholders for the key and value types. + // See enc_new_map for why. + keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K + keybase := toStructPointer(keyptr.Addr()) // **K + + var valbase structPointer + var valptr reflect.Value + switch p.mtype.Elem().Kind() { + case reflect.Slice: + // []byte + var dummy []byte + valptr = reflect.ValueOf(&dummy) // *[]byte + valbase = toStructPointer(valptr) // *[]byte + case reflect.Ptr: + // message; valptr is **Msg; need to allocate the intermediate pointer + valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V + valptr.Set(reflect.New(valptr.Type().Elem())) + valbase = toStructPointer(valptr) + default: + // everything else + valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V + valbase = toStructPointer(valptr.Addr()) // **V + } + + // Decode. + // This parses a restricted wire format, namely the encoding of a message + // with two fields. See enc_new_map for the format. + for o.index < oi { + // tagcode for key and value properties are always a single byte + // because they have tags 1 and 2. + tagcode := o.buf[o.index] + o.index++ + switch tagcode { + case p.mkeyprop.tagcode[0]: + if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { + return err + } + case p.mvalprop.tagcode[0]: + if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { + return err + } + default: + // TODO: Should we silently skip this instead? + return fmt.Errorf("proto: bad map data tag %d", raw[0]) + } + } + keyelem, valelem := keyptr.Elem(), valptr.Elem() + if !keyelem.IsValid() { + keyelem = reflect.Zero(p.mtype.Key()) + } + if !valelem.IsValid() { + valelem = reflect.Zero(p.mtype.Elem()) + } + + v.SetMapIndex(keyelem, valelem) + return nil +} + +// Decode a group. +func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { + bas := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(bas) { + // allocate new nested message + bas = toStructPointer(reflect.New(p.stype)) + structPointer_SetStructPointer(base, p.field, bas) + } + return o.unmarshalType(p.stype, p.sprop, true, bas) +} + +// Decode an embedded message. +func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { + raw, e := o.DecodeRawBytes(false) + if e != nil { + return e + } + + bas := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(bas) { + // allocate new nested message + bas = toStructPointer(reflect.New(p.stype)) + structPointer_SetStructPointer(base, p.field, bas) + } + + // If the object can unmarshal itself, let it. + if p.isUnmarshaler { + iv := structPointer_Interface(bas, p.stype) + return iv.(Unmarshaler).Unmarshal(raw) + } + + obuf := o.buf + oi := o.index + o.buf = raw + o.index = 0 + + err = o.unmarshalType(p.stype, p.sprop, false, bas) + o.buf = obuf + o.index = oi + + return err +} + +// Decode a slice of embedded messages. +func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { + return o.dec_slice_struct(p, false, base) +} + +// Decode a slice of embedded groups. +func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { + return o.dec_slice_struct(p, true, base) +} + +// Decode a slice of structs ([]*struct). +func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { + v := reflect.New(p.stype) + bas := toStructPointer(v) + structPointer_StructPointerSlice(base, p.field).Append(bas) + + if is_group { + err := o.unmarshalType(p.stype, p.sprop, is_group, bas) + return err + } + + raw, err := o.DecodeRawBytes(false) + if err != nil { + return err + } + + // If the object can unmarshal itself, let it. + if p.isUnmarshaler { + iv := v.Interface() + return iv.(Unmarshaler).Unmarshal(raw) + } + + obuf := o.buf + oi := o.index + o.buf = raw + o.index = 0 + + err = o.unmarshalType(p.stype, p.sprop, is_group, bas) + + o.buf = obuf + o.index = oi + + return err +} diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/encode.go b/metricbeat/vendor/github.com/golang/protobuf/proto/encode.go new file mode 100644 index 00000000000..2b30f84626a --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/encode.go @@ -0,0 +1,1362 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Routines for encoding data into the wire format for protocol buffers. + */ + +import ( + "errors" + "fmt" + "reflect" + "sort" +) + +// RequiredNotSetError is the error returned if Marshal is called with +// a protocol buffer struct whose required fields have not +// all been initialized. It is also the error returned if Unmarshal is +// called with an encoded protocol buffer that does not include all the +// required fields. +// +// When printed, RequiredNotSetError reports the first unset required field in a +// message. If the field cannot be precisely determined, it is reported as +// "{Unknown}". +type RequiredNotSetError struct { + field string +} + +func (e *RequiredNotSetError) Error() string { + return fmt.Sprintf("proto: required field %q not set", e.field) +} + +var ( + // errRepeatedHasNil is the error returned if Marshal is called with + // a struct with a repeated field containing a nil element. + errRepeatedHasNil = errors.New("proto: repeated field has nil element") + + // errOneofHasNil is the error returned if Marshal is called with + // a struct with a oneof field containing a nil element. + errOneofHasNil = errors.New("proto: oneof field has nil value") + + // ErrNil is the error returned if Marshal is called with nil. + ErrNil = errors.New("proto: Marshal called with nil") + + // ErrTooLarge is the error returned if Marshal is called with a + // message that encodes to >2GB. + ErrTooLarge = errors.New("proto: message encodes to over 2 GB") +) + +// The fundamental encoders that put bytes on the wire. +// Those that take integer types all accept uint64 and are +// therefore of type valueEncoder. + +const maxVarintBytes = 10 // maximum length of a varint + +// maxMarshalSize is the largest allowed size of an encoded protobuf, +// since C++ and Java use signed int32s for the size. +const maxMarshalSize = 1<<31 - 1 + +// EncodeVarint returns the varint encoding of x. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +// Not used by the package itself, but helpful to clients +// wishing to use the same encoding. +func EncodeVarint(x uint64) []byte { + var buf [maxVarintBytes]byte + var n int + for n = 0; x > 127; n++ { + buf[n] = 0x80 | uint8(x&0x7F) + x >>= 7 + } + buf[n] = uint8(x) + n++ + return buf[0:n] +} + +// EncodeVarint writes a varint-encoded integer to the Buffer. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func (p *Buffer) EncodeVarint(x uint64) error { + for x >= 1<<7 { + p.buf = append(p.buf, uint8(x&0x7f|0x80)) + x >>= 7 + } + p.buf = append(p.buf, uint8(x)) + return nil +} + +// SizeVarint returns the varint encoding size of an integer. +func SizeVarint(x uint64) int { + return sizeVarint(x) +} + +func sizeVarint(x uint64) (n int) { + for { + n++ + x >>= 7 + if x == 0 { + break + } + } + return n +} + +// EncodeFixed64 writes a 64-bit integer to the Buffer. +// This is the format for the +// fixed64, sfixed64, and double protocol buffer types. +func (p *Buffer) EncodeFixed64(x uint64) error { + p.buf = append(p.buf, + uint8(x), + uint8(x>>8), + uint8(x>>16), + uint8(x>>24), + uint8(x>>32), + uint8(x>>40), + uint8(x>>48), + uint8(x>>56)) + return nil +} + +func sizeFixed64(x uint64) int { + return 8 +} + +// EncodeFixed32 writes a 32-bit integer to the Buffer. +// This is the format for the +// fixed32, sfixed32, and float protocol buffer types. +func (p *Buffer) EncodeFixed32(x uint64) error { + p.buf = append(p.buf, + uint8(x), + uint8(x>>8), + uint8(x>>16), + uint8(x>>24)) + return nil +} + +func sizeFixed32(x uint64) int { + return 4 +} + +// EncodeZigzag64 writes a zigzag-encoded 64-bit integer +// to the Buffer. +// This is the format used for the sint64 protocol buffer type. +func (p *Buffer) EncodeZigzag64(x uint64) error { + // use signed number to get arithmetic right shift. + return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} + +func sizeZigzag64(x uint64) int { + return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} + +// EncodeZigzag32 writes a zigzag-encoded 32-bit integer +// to the Buffer. +// This is the format used for the sint32 protocol buffer type. +func (p *Buffer) EncodeZigzag32(x uint64) error { + // use signed number to get arithmetic right shift. + return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) +} + +func sizeZigzag32(x uint64) int { + return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) +} + +// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. +// This is the format used for the bytes protocol buffer +// type and for embedded messages. +func (p *Buffer) EncodeRawBytes(b []byte) error { + p.EncodeVarint(uint64(len(b))) + p.buf = append(p.buf, b...) + return nil +} + +func sizeRawBytes(b []byte) int { + return sizeVarint(uint64(len(b))) + + len(b) +} + +// EncodeStringBytes writes an encoded string to the Buffer. +// This is the format used for the proto2 string type. +func (p *Buffer) EncodeStringBytes(s string) error { + p.EncodeVarint(uint64(len(s))) + p.buf = append(p.buf, s...) + return nil +} + +func sizeStringBytes(s string) int { + return sizeVarint(uint64(len(s))) + + len(s) +} + +// Marshaler is the interface representing objects that can marshal themselves. +type Marshaler interface { + Marshal() ([]byte, error) +} + +// Marshal takes the protocol buffer +// and encodes it into the wire format, returning the data. +func Marshal(pb Message) ([]byte, error) { + // Can the object marshal itself? + if m, ok := pb.(Marshaler); ok { + return m.Marshal() + } + p := NewBuffer(nil) + err := p.Marshal(pb) + if p.buf == nil && err == nil { + // Return a non-nil slice on success. + return []byte{}, nil + } + return p.buf, err +} + +// EncodeMessage writes the protocol buffer to the Buffer, +// prefixed by a varint-encoded length. +func (p *Buffer) EncodeMessage(pb Message) error { + t, base, err := getbase(pb) + if structPointer_IsNil(base) { + return ErrNil + } + if err == nil { + var state errorState + err = p.enc_len_struct(GetProperties(t.Elem()), base, &state) + } + return err +} + +// Marshal takes the protocol buffer +// and encodes it into the wire format, writing the result to the +// Buffer. +func (p *Buffer) Marshal(pb Message) error { + // Can the object marshal itself? + if m, ok := pb.(Marshaler); ok { + data, err := m.Marshal() + p.buf = append(p.buf, data...) + return err + } + + t, base, err := getbase(pb) + if structPointer_IsNil(base) { + return ErrNil + } + if err == nil { + err = p.enc_struct(GetProperties(t.Elem()), base) + } + + if collectStats { + (stats).Encode++ // Parens are to work around a goimports bug. + } + + if len(p.buf) > maxMarshalSize { + return ErrTooLarge + } + return err +} + +// Size returns the encoded size of a protocol buffer. +func Size(pb Message) (n int) { + // Can the object marshal itself? If so, Size is slow. + // TODO: add Size to Marshaler, or add a Sizer interface. + if m, ok := pb.(Marshaler); ok { + b, _ := m.Marshal() + return len(b) + } + + t, base, err := getbase(pb) + if structPointer_IsNil(base) { + return 0 + } + if err == nil { + n = size_struct(GetProperties(t.Elem()), base) + } + + if collectStats { + (stats).Size++ // Parens are to work around a goimports bug. + } + + return +} + +// Individual type encoders. + +// Encode a bool. +func (o *Buffer) enc_bool(p *Properties, base structPointer) error { + v := *structPointer_Bool(base, p.field) + if v == nil { + return ErrNil + } + x := 0 + if *v { + x = 1 + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { + v := *structPointer_BoolVal(base, p.field) + if !v { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, 1) + return nil +} + +func size_bool(p *Properties, base structPointer) int { + v := *structPointer_Bool(base, p.field) + if v == nil { + return 0 + } + return len(p.tagcode) + 1 // each bool takes exactly one byte +} + +func size_proto3_bool(p *Properties, base structPointer) int { + v := *structPointer_BoolVal(base, p.field) + if !v && !p.oneof { + return 0 + } + return len(p.tagcode) + 1 // each bool takes exactly one byte +} + +// Encode an int32. +func (o *Buffer) enc_int32(p *Properties, base structPointer) error { + v := structPointer_Word32(base, p.field) + if word32_IsNil(v) { + return ErrNil + } + x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { + v := structPointer_Word32Val(base, p.field) + x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range + if x == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func size_int32(p *Properties, base structPointer) (n int) { + v := structPointer_Word32(base, p.field) + if word32_IsNil(v) { + return 0 + } + x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range + n += len(p.tagcode) + n += p.valSize(uint64(x)) + return +} + +func size_proto3_int32(p *Properties, base structPointer) (n int) { + v := structPointer_Word32Val(base, p.field) + x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range + if x == 0 && !p.oneof { + return 0 + } + n += len(p.tagcode) + n += p.valSize(uint64(x)) + return +} + +// Encode a uint32. +// Exactly the same as int32, except for no sign extension. +func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { + v := structPointer_Word32(base, p.field) + if word32_IsNil(v) { + return ErrNil + } + x := word32_Get(v) + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { + v := structPointer_Word32Val(base, p.field) + x := word32Val_Get(v) + if x == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, uint64(x)) + return nil +} + +func size_uint32(p *Properties, base structPointer) (n int) { + v := structPointer_Word32(base, p.field) + if word32_IsNil(v) { + return 0 + } + x := word32_Get(v) + n += len(p.tagcode) + n += p.valSize(uint64(x)) + return +} + +func size_proto3_uint32(p *Properties, base structPointer) (n int) { + v := structPointer_Word32Val(base, p.field) + x := word32Val_Get(v) + if x == 0 && !p.oneof { + return 0 + } + n += len(p.tagcode) + n += p.valSize(uint64(x)) + return +} + +// Encode an int64. +func (o *Buffer) enc_int64(p *Properties, base structPointer) error { + v := structPointer_Word64(base, p.field) + if word64_IsNil(v) { + return ErrNil + } + x := word64_Get(v) + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, x) + return nil +} + +func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { + v := structPointer_Word64Val(base, p.field) + x := word64Val_Get(v) + if x == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, x) + return nil +} + +func size_int64(p *Properties, base structPointer) (n int) { + v := structPointer_Word64(base, p.field) + if word64_IsNil(v) { + return 0 + } + x := word64_Get(v) + n += len(p.tagcode) + n += p.valSize(x) + return +} + +func size_proto3_int64(p *Properties, base structPointer) (n int) { + v := structPointer_Word64Val(base, p.field) + x := word64Val_Get(v) + if x == 0 && !p.oneof { + return 0 + } + n += len(p.tagcode) + n += p.valSize(x) + return +} + +// Encode a string. +func (o *Buffer) enc_string(p *Properties, base structPointer) error { + v := *structPointer_String(base, p.field) + if v == nil { + return ErrNil + } + x := *v + o.buf = append(o.buf, p.tagcode...) + o.EncodeStringBytes(x) + return nil +} + +func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { + v := *structPointer_StringVal(base, p.field) + if v == "" { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeStringBytes(v) + return nil +} + +func size_string(p *Properties, base structPointer) (n int) { + v := *structPointer_String(base, p.field) + if v == nil { + return 0 + } + x := *v + n += len(p.tagcode) + n += sizeStringBytes(x) + return +} + +func size_proto3_string(p *Properties, base structPointer) (n int) { + v := *structPointer_StringVal(base, p.field) + if v == "" && !p.oneof { + return 0 + } + n += len(p.tagcode) + n += sizeStringBytes(v) + return +} + +// All protocol buffer fields are nillable, but be careful. +func isNil(v reflect.Value) bool { + switch v.Kind() { + case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return v.IsNil() + } + return false +} + +// Encode a message struct. +func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { + var state errorState + structp := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(structp) { + return ErrNil + } + + // Can the object marshal itself? + if p.isMarshaler { + m := structPointer_Interface(structp, p.stype).(Marshaler) + data, err := m.Marshal() + if err != nil && !state.shouldContinue(err, nil) { + return err + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(data) + return state.err + } + + o.buf = append(o.buf, p.tagcode...) + return o.enc_len_struct(p.sprop, structp, &state) +} + +func size_struct_message(p *Properties, base structPointer) int { + structp := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(structp) { + return 0 + } + + // Can the object marshal itself? + if p.isMarshaler { + m := structPointer_Interface(structp, p.stype).(Marshaler) + data, _ := m.Marshal() + n0 := len(p.tagcode) + n1 := sizeRawBytes(data) + return n0 + n1 + } + + n0 := len(p.tagcode) + n1 := size_struct(p.sprop, structp) + n2 := sizeVarint(uint64(n1)) // size of encoded length + return n0 + n1 + n2 +} + +// Encode a group struct. +func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { + var state errorState + b := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(b) { + return ErrNil + } + + o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) + err := o.enc_struct(p.sprop, b) + if err != nil && !state.shouldContinue(err, nil) { + return err + } + o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) + return state.err +} + +func size_struct_group(p *Properties, base structPointer) (n int) { + b := structPointer_GetStructPointer(base, p.field) + if structPointer_IsNil(b) { + return 0 + } + + n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) + n += size_struct(p.sprop, b) + n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) + return +} + +// Encode a slice of bools ([]bool). +func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { + s := *structPointer_BoolSlice(base, p.field) + l := len(s) + if l == 0 { + return ErrNil + } + for _, x := range s { + o.buf = append(o.buf, p.tagcode...) + v := uint64(0) + if x { + v = 1 + } + p.valEnc(o, v) + } + return nil +} + +func size_slice_bool(p *Properties, base structPointer) int { + s := *structPointer_BoolSlice(base, p.field) + l := len(s) + if l == 0 { + return 0 + } + return l * (len(p.tagcode) + 1) // each bool takes exactly one byte +} + +// Encode a slice of bools ([]bool) in packed format. +func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { + s := *structPointer_BoolSlice(base, p.field) + l := len(s) + if l == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeVarint(uint64(l)) // each bool takes exactly one byte + for _, x := range s { + v := uint64(0) + if x { + v = 1 + } + p.valEnc(o, v) + } + return nil +} + +func size_slice_packed_bool(p *Properties, base structPointer) (n int) { + s := *structPointer_BoolSlice(base, p.field) + l := len(s) + if l == 0 { + return 0 + } + n += len(p.tagcode) + n += sizeVarint(uint64(l)) + n += l // each bool takes exactly one byte + return +} + +// Encode a slice of bytes ([]byte). +func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { + s := *structPointer_Bytes(base, p.field) + if s == nil { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(s) + return nil +} + +func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { + s := *structPointer_Bytes(base, p.field) + if len(s) == 0 { + return ErrNil + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(s) + return nil +} + +func size_slice_byte(p *Properties, base structPointer) (n int) { + s := *structPointer_Bytes(base, p.field) + if s == nil && !p.oneof { + return 0 + } + n += len(p.tagcode) + n += sizeRawBytes(s) + return +} + +func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { + s := *structPointer_Bytes(base, p.field) + if len(s) == 0 && !p.oneof { + return 0 + } + n += len(p.tagcode) + n += sizeRawBytes(s) + return +} + +// Encode a slice of int32s ([]int32). +func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + x := int32(s.Index(i)) // permit sign extension to use full 64-bit range + p.valEnc(o, uint64(x)) + } + return nil +} + +func size_slice_int32(p *Properties, base structPointer) (n int) { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + for i := 0; i < l; i++ { + n += len(p.tagcode) + x := int32(s.Index(i)) // permit sign extension to use full 64-bit range + n += p.valSize(uint64(x)) + } + return +} + +// Encode a slice of int32s ([]int32) in packed format. +func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + // TODO: Reuse a Buffer. + buf := NewBuffer(nil) + for i := 0; i < l; i++ { + x := int32(s.Index(i)) // permit sign extension to use full 64-bit range + p.valEnc(buf, uint64(x)) + } + + o.buf = append(o.buf, p.tagcode...) + o.EncodeVarint(uint64(len(buf.buf))) + o.buf = append(o.buf, buf.buf...) + return nil +} + +func size_slice_packed_int32(p *Properties, base structPointer) (n int) { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + var bufSize int + for i := 0; i < l; i++ { + x := int32(s.Index(i)) // permit sign extension to use full 64-bit range + bufSize += p.valSize(uint64(x)) + } + + n += len(p.tagcode) + n += sizeVarint(uint64(bufSize)) + n += bufSize + return +} + +// Encode a slice of uint32s ([]uint32). +// Exactly the same as int32, except for no sign extension. +func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + x := s.Index(i) + p.valEnc(o, uint64(x)) + } + return nil +} + +func size_slice_uint32(p *Properties, base structPointer) (n int) { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + for i := 0; i < l; i++ { + n += len(p.tagcode) + x := s.Index(i) + n += p.valSize(uint64(x)) + } + return +} + +// Encode a slice of uint32s ([]uint32) in packed format. +// Exactly the same as int32, except for no sign extension. +func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + // TODO: Reuse a Buffer. + buf := NewBuffer(nil) + for i := 0; i < l; i++ { + p.valEnc(buf, uint64(s.Index(i))) + } + + o.buf = append(o.buf, p.tagcode...) + o.EncodeVarint(uint64(len(buf.buf))) + o.buf = append(o.buf, buf.buf...) + return nil +} + +func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { + s := structPointer_Word32Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + var bufSize int + for i := 0; i < l; i++ { + bufSize += p.valSize(uint64(s.Index(i))) + } + + n += len(p.tagcode) + n += sizeVarint(uint64(bufSize)) + n += bufSize + return +} + +// Encode a slice of int64s ([]int64). +func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { + s := structPointer_Word64Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + p.valEnc(o, s.Index(i)) + } + return nil +} + +func size_slice_int64(p *Properties, base structPointer) (n int) { + s := structPointer_Word64Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + for i := 0; i < l; i++ { + n += len(p.tagcode) + n += p.valSize(s.Index(i)) + } + return +} + +// Encode a slice of int64s ([]int64) in packed format. +func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { + s := structPointer_Word64Slice(base, p.field) + l := s.Len() + if l == 0 { + return ErrNil + } + // TODO: Reuse a Buffer. + buf := NewBuffer(nil) + for i := 0; i < l; i++ { + p.valEnc(buf, s.Index(i)) + } + + o.buf = append(o.buf, p.tagcode...) + o.EncodeVarint(uint64(len(buf.buf))) + o.buf = append(o.buf, buf.buf...) + return nil +} + +func size_slice_packed_int64(p *Properties, base structPointer) (n int) { + s := structPointer_Word64Slice(base, p.field) + l := s.Len() + if l == 0 { + return 0 + } + var bufSize int + for i := 0; i < l; i++ { + bufSize += p.valSize(s.Index(i)) + } + + n += len(p.tagcode) + n += sizeVarint(uint64(bufSize)) + n += bufSize + return +} + +// Encode a slice of slice of bytes ([][]byte). +func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { + ss := *structPointer_BytesSlice(base, p.field) + l := len(ss) + if l == 0 { + return ErrNil + } + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(ss[i]) + } + return nil +} + +func size_slice_slice_byte(p *Properties, base structPointer) (n int) { + ss := *structPointer_BytesSlice(base, p.field) + l := len(ss) + if l == 0 { + return 0 + } + n += l * len(p.tagcode) + for i := 0; i < l; i++ { + n += sizeRawBytes(ss[i]) + } + return +} + +// Encode a slice of strings ([]string). +func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { + ss := *structPointer_StringSlice(base, p.field) + l := len(ss) + for i := 0; i < l; i++ { + o.buf = append(o.buf, p.tagcode...) + o.EncodeStringBytes(ss[i]) + } + return nil +} + +func size_slice_string(p *Properties, base structPointer) (n int) { + ss := *structPointer_StringSlice(base, p.field) + l := len(ss) + n += l * len(p.tagcode) + for i := 0; i < l; i++ { + n += sizeStringBytes(ss[i]) + } + return +} + +// Encode a slice of message structs ([]*struct). +func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { + var state errorState + s := structPointer_StructPointerSlice(base, p.field) + l := s.Len() + + for i := 0; i < l; i++ { + structp := s.Index(i) + if structPointer_IsNil(structp) { + return errRepeatedHasNil + } + + // Can the object marshal itself? + if p.isMarshaler { + m := structPointer_Interface(structp, p.stype).(Marshaler) + data, err := m.Marshal() + if err != nil && !state.shouldContinue(err, nil) { + return err + } + o.buf = append(o.buf, p.tagcode...) + o.EncodeRawBytes(data) + continue + } + + o.buf = append(o.buf, p.tagcode...) + err := o.enc_len_struct(p.sprop, structp, &state) + if err != nil && !state.shouldContinue(err, nil) { + if err == ErrNil { + return errRepeatedHasNil + } + return err + } + } + return state.err +} + +func size_slice_struct_message(p *Properties, base structPointer) (n int) { + s := structPointer_StructPointerSlice(base, p.field) + l := s.Len() + n += l * len(p.tagcode) + for i := 0; i < l; i++ { + structp := s.Index(i) + if structPointer_IsNil(structp) { + return // return the size up to this point + } + + // Can the object marshal itself? + if p.isMarshaler { + m := structPointer_Interface(structp, p.stype).(Marshaler) + data, _ := m.Marshal() + n += sizeRawBytes(data) + continue + } + + n0 := size_struct(p.sprop, structp) + n1 := sizeVarint(uint64(n0)) // size of encoded length + n += n0 + n1 + } + return +} + +// Encode a slice of group structs ([]*struct). +func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { + var state errorState + s := structPointer_StructPointerSlice(base, p.field) + l := s.Len() + + for i := 0; i < l; i++ { + b := s.Index(i) + if structPointer_IsNil(b) { + return errRepeatedHasNil + } + + o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) + + err := o.enc_struct(p.sprop, b) + + if err != nil && !state.shouldContinue(err, nil) { + if err == ErrNil { + return errRepeatedHasNil + } + return err + } + + o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) + } + return state.err +} + +func size_slice_struct_group(p *Properties, base structPointer) (n int) { + s := structPointer_StructPointerSlice(base, p.field) + l := s.Len() + + n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) + n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) + for i := 0; i < l; i++ { + b := s.Index(i) + if structPointer_IsNil(b) { + return // return size up to this point + } + + n += size_struct(p.sprop, b) + } + return +} + +// Encode an extension map. +func (o *Buffer) enc_map(p *Properties, base structPointer) error { + exts := structPointer_ExtMap(base, p.field) + if err := encodeExtensionsMap(*exts); err != nil { + return err + } + + return o.enc_map_body(*exts) +} + +func (o *Buffer) enc_exts(p *Properties, base structPointer) error { + exts := structPointer_Extensions(base, p.field) + + v, mu := exts.extensionsRead() + if v == nil { + return nil + } + + mu.Lock() + defer mu.Unlock() + if err := encodeExtensionsMap(v); err != nil { + return err + } + + return o.enc_map_body(v) +} + +func (o *Buffer) enc_map_body(v map[int32]Extension) error { + // Fast-path for common cases: zero or one extensions. + if len(v) <= 1 { + for _, e := range v { + o.buf = append(o.buf, e.enc...) + } + return nil + } + + // Sort keys to provide a deterministic encoding. + keys := make([]int, 0, len(v)) + for k := range v { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + for _, k := range keys { + o.buf = append(o.buf, v[int32(k)].enc...) + } + return nil +} + +func size_map(p *Properties, base structPointer) int { + v := structPointer_ExtMap(base, p.field) + return extensionsMapSize(*v) +} + +func size_exts(p *Properties, base structPointer) int { + v := structPointer_Extensions(base, p.field) + return extensionsSize(v) +} + +// Encode a map field. +func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { + var state errorState // XXX: or do we need to plumb this through? + + /* + A map defined as + map map_field = N; + is encoded in the same way as + message MapFieldEntry { + key_type key = 1; + value_type value = 2; + } + repeated MapFieldEntry map_field = N; + */ + + v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V + if v.Len() == 0 { + return nil + } + + keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) + + enc := func() error { + if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { + return err + } + if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil { + return err + } + return nil + } + + // Don't sort map keys. It is not required by the spec, and C++ doesn't do it. + for _, key := range v.MapKeys() { + val := v.MapIndex(key) + + keycopy.Set(key) + valcopy.Set(val) + + o.buf = append(o.buf, p.tagcode...) + if err := o.enc_len_thing(enc, &state); err != nil { + return err + } + } + return nil +} + +func size_new_map(p *Properties, base structPointer) int { + v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V + + keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) + + n := 0 + for _, key := range v.MapKeys() { + val := v.MapIndex(key) + keycopy.Set(key) + valcopy.Set(val) + + // Tag codes for key and val are the responsibility of the sub-sizer. + keysize := p.mkeyprop.size(p.mkeyprop, keybase) + valsize := p.mvalprop.size(p.mvalprop, valbase) + entry := keysize + valsize + // Add on tag code and length of map entry itself. + n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry + } + return n +} + +// mapEncodeScratch returns a new reflect.Value matching the map's value type, +// and a structPointer suitable for passing to an encoder or sizer. +func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { + // Prepare addressable doubly-indirect placeholders for the key and value types. + // This is needed because the element-type encoders expect **T, but the map iteration produces T. + + keycopy = reflect.New(mapType.Key()).Elem() // addressable K + keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K + keyptr.Set(keycopy.Addr()) // + keybase = toStructPointer(keyptr.Addr()) // **K + + // Value types are more varied and require special handling. + switch mapType.Elem().Kind() { + case reflect.Slice: + // []byte + var dummy []byte + valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte + valbase = toStructPointer(valcopy.Addr()) + case reflect.Ptr: + // message; the generated field type is map[K]*Msg (so V is *Msg), + // so we only need one level of indirection. + valcopy = reflect.New(mapType.Elem()).Elem() // addressable V + valbase = toStructPointer(valcopy.Addr()) + default: + // everything else + valcopy = reflect.New(mapType.Elem()).Elem() // addressable V + valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V + valptr.Set(valcopy.Addr()) // + valbase = toStructPointer(valptr.Addr()) // **V + } + return +} + +// Encode a struct. +func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { + var state errorState + // Encode fields in tag order so that decoders may use optimizations + // that depend on the ordering. + // https://developers.google.com/protocol-buffers/docs/encoding#order + for _, i := range prop.order { + p := prop.Prop[i] + if p.enc != nil { + err := p.enc(o, p, base) + if err != nil { + if err == ErrNil { + if p.Required && state.err == nil { + state.err = &RequiredNotSetError{p.Name} + } + } else if err == errRepeatedHasNil { + // Give more context to nil values in repeated fields. + return errors.New("repeated field " + p.OrigName + " has nil element") + } else if !state.shouldContinue(err, p) { + return err + } + } + if len(o.buf) > maxMarshalSize { + return ErrTooLarge + } + } + } + + // Do oneof fields. + if prop.oneofMarshaler != nil { + m := structPointer_Interface(base, prop.stype).(Message) + if err := prop.oneofMarshaler(m, o); err == ErrNil { + return errOneofHasNil + } else if err != nil { + return err + } + } + + // Add unrecognized fields at the end. + if prop.unrecField.IsValid() { + v := *structPointer_Bytes(base, prop.unrecField) + if len(o.buf)+len(v) > maxMarshalSize { + return ErrTooLarge + } + if len(v) > 0 { + o.buf = append(o.buf, v...) + } + } + + return state.err +} + +func size_struct(prop *StructProperties, base structPointer) (n int) { + for _, i := range prop.order { + p := prop.Prop[i] + if p.size != nil { + n += p.size(p, base) + } + } + + // Add unrecognized fields at the end. + if prop.unrecField.IsValid() { + v := *structPointer_Bytes(base, prop.unrecField) + n += len(v) + } + + // Factor in any oneof fields. + if prop.oneofSizer != nil { + m := structPointer_Interface(base, prop.stype).(Message) + n += prop.oneofSizer(m) + } + + return +} + +var zeroes [20]byte // longer than any conceivable sizeVarint + +// Encode a struct, preceded by its encoded length (as a varint). +func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { + return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) +} + +// Encode something, preceded by its encoded length (as a varint). +func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { + iLen := len(o.buf) + o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length + iMsg := len(o.buf) + err := enc() + if err != nil && !state.shouldContinue(err, nil) { + return err + } + lMsg := len(o.buf) - iMsg + lLen := sizeVarint(uint64(lMsg)) + switch x := lLen - (iMsg - iLen); { + case x > 0: // actual length is x bytes larger than the space we reserved + // Move msg x bytes right. + o.buf = append(o.buf, zeroes[:x]...) + copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) + case x < 0: // actual length is x bytes smaller than the space we reserved + // Move msg x bytes left. + copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) + o.buf = o.buf[:len(o.buf)+x] // x is negative + } + // Encode the length in the reserved space. + o.buf = o.buf[:iLen] + o.EncodeVarint(uint64(lMsg)) + o.buf = o.buf[:len(o.buf)+lMsg] + return state.err +} + +// errorState maintains the first error that occurs and updates that error +// with additional context. +type errorState struct { + err error +} + +// shouldContinue reports whether encoding should continue upon encountering the +// given error. If the error is RequiredNotSetError, shouldContinue returns true +// and, if this is the first appearance of that error, remembers it for future +// reporting. +// +// If prop is not nil, it may update any error with additional context about the +// field with the error. +func (s *errorState) shouldContinue(err error, prop *Properties) bool { + // Ignore unset required fields. + reqNotSet, ok := err.(*RequiredNotSetError) + if !ok { + return false + } + if s.err == nil { + if prop != nil { + err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} + } + s.err = err + } + return true +} diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/equal.go b/metricbeat/vendor/github.com/golang/protobuf/proto/equal.go new file mode 100644 index 00000000000..2ed1cf59666 --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/equal.go @@ -0,0 +1,300 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2011 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Protocol buffer comparison. + +package proto + +import ( + "bytes" + "log" + "reflect" + "strings" +) + +/* +Equal returns true iff protocol buffers a and b are equal. +The arguments must both be pointers to protocol buffer structs. + +Equality is defined in this way: + - Two messages are equal iff they are the same type, + corresponding fields are equal, unknown field sets + are equal, and extensions sets are equal. + - Two set scalar fields are equal iff their values are equal. + If the fields are of a floating-point type, remember that + NaN != x for all x, including NaN. If the message is defined + in a proto3 .proto file, fields are not "set"; specifically, + zero length proto3 "bytes" fields are equal (nil == {}). + - Two repeated fields are equal iff their lengths are the same, + and their corresponding elements are equal. Note a "bytes" field, + although represented by []byte, is not a repeated field and the + rule for the scalar fields described above applies. + - Two unset fields are equal. + - Two unknown field sets are equal if their current + encoded state is equal. + - Two extension sets are equal iff they have corresponding + elements that are pairwise equal. + - Two map fields are equal iff their lengths are the same, + and they contain the same set of elements. Zero-length map + fields are equal. + - Every other combination of things are not equal. + +The return value is undefined if a and b are not protocol buffers. +*/ +func Equal(a, b Message) bool { + if a == nil || b == nil { + return a == b + } + v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) + if v1.Type() != v2.Type() { + return false + } + if v1.Kind() == reflect.Ptr { + if v1.IsNil() { + return v2.IsNil() + } + if v2.IsNil() { + return false + } + v1, v2 = v1.Elem(), v2.Elem() + } + if v1.Kind() != reflect.Struct { + return false + } + return equalStruct(v1, v2) +} + +// v1 and v2 are known to have the same type. +func equalStruct(v1, v2 reflect.Value) bool { + sprop := GetProperties(v1.Type()) + for i := 0; i < v1.NumField(); i++ { + f := v1.Type().Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + f1, f2 := v1.Field(i), v2.Field(i) + if f.Type.Kind() == reflect.Ptr { + if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { + // both unset + continue + } else if n1 != n2 { + // set/unset mismatch + return false + } + b1, ok := f1.Interface().(raw) + if ok { + b2 := f2.Interface().(raw) + // RawMessage + if !bytes.Equal(b1.Bytes(), b2.Bytes()) { + return false + } + continue + } + f1, f2 = f1.Elem(), f2.Elem() + } + if !equalAny(f1, f2, sprop.Prop[i]) { + return false + } + } + + if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { + em2 := v2.FieldByName("XXX_InternalExtensions") + if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { + return false + } + } + + if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { + em2 := v2.FieldByName("XXX_extensions") + if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { + return false + } + } + + uf := v1.FieldByName("XXX_unrecognized") + if !uf.IsValid() { + return true + } + + u1 := uf.Bytes() + u2 := v2.FieldByName("XXX_unrecognized").Bytes() + if !bytes.Equal(u1, u2) { + return false + } + + return true +} + +// v1 and v2 are known to have the same type. +// prop may be nil. +func equalAny(v1, v2 reflect.Value, prop *Properties) bool { + if v1.Type() == protoMessageType { + m1, _ := v1.Interface().(Message) + m2, _ := v2.Interface().(Message) + return Equal(m1, m2) + } + switch v1.Kind() { + case reflect.Bool: + return v1.Bool() == v2.Bool() + case reflect.Float32, reflect.Float64: + return v1.Float() == v2.Float() + case reflect.Int32, reflect.Int64: + return v1.Int() == v2.Int() + case reflect.Interface: + // Probably a oneof field; compare the inner values. + n1, n2 := v1.IsNil(), v2.IsNil() + if n1 || n2 { + return n1 == n2 + } + e1, e2 := v1.Elem(), v2.Elem() + if e1.Type() != e2.Type() { + return false + } + return equalAny(e1, e2, nil) + case reflect.Map: + if v1.Len() != v2.Len() { + return false + } + for _, key := range v1.MapKeys() { + val2 := v2.MapIndex(key) + if !val2.IsValid() { + // This key was not found in the second map. + return false + } + if !equalAny(v1.MapIndex(key), val2, nil) { + return false + } + } + return true + case reflect.Ptr: + // Maps may have nil values in them, so check for nil. + if v1.IsNil() && v2.IsNil() { + return true + } + if v1.IsNil() != v2.IsNil() { + return false + } + return equalAny(v1.Elem(), v2.Elem(), prop) + case reflect.Slice: + if v1.Type().Elem().Kind() == reflect.Uint8 { + // short circuit: []byte + + // Edge case: if this is in a proto3 message, a zero length + // bytes field is considered the zero value. + if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { + return true + } + if v1.IsNil() != v2.IsNil() { + return false + } + return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) + } + + if v1.Len() != v2.Len() { + return false + } + for i := 0; i < v1.Len(); i++ { + if !equalAny(v1.Index(i), v2.Index(i), prop) { + return false + } + } + return true + case reflect.String: + return v1.Interface().(string) == v2.Interface().(string) + case reflect.Struct: + return equalStruct(v1, v2) + case reflect.Uint32, reflect.Uint64: + return v1.Uint() == v2.Uint() + } + + // unknown type, so not a protocol buffer + log.Printf("proto: don't know how to compare %v", v1) + return false +} + +// base is the struct type that the extensions are based on. +// x1 and x2 are InternalExtensions. +func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { + em1, _ := x1.extensionsRead() + em2, _ := x2.extensionsRead() + return equalExtMap(base, em1, em2) +} + +func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { + if len(em1) != len(em2) { + return false + } + + for extNum, e1 := range em1 { + e2, ok := em2[extNum] + if !ok { + return false + } + + m1, m2 := e1.value, e2.value + + if m1 != nil && m2 != nil { + // Both are unencoded. + if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { + return false + } + continue + } + + // At least one is encoded. To do a semantically correct comparison + // we need to unmarshal them first. + var desc *ExtensionDesc + if m := extensionMaps[base]; m != nil { + desc = m[extNum] + } + if desc == nil { + log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) + continue + } + var err error + if m1 == nil { + m1, err = decodeExtension(e1.enc, desc) + } + if m2 == nil && err == nil { + m2, err = decodeExtension(e2.enc, desc) + } + if err != nil { + // The encoded form is invalid. + log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) + return false + } + if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { + return false + } + } + + return true +} diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/extensions.go b/metricbeat/vendor/github.com/golang/protobuf/proto/extensions.go new file mode 100644 index 00000000000..eaad2183126 --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/extensions.go @@ -0,0 +1,587 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Types and routines for supporting protocol buffer extensions. + */ + +import ( + "errors" + "fmt" + "reflect" + "strconv" + "sync" +) + +// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. +var ErrMissingExtension = errors.New("proto: missing extension") + +// ExtensionRange represents a range of message extensions for a protocol buffer. +// Used in code generated by the protocol compiler. +type ExtensionRange struct { + Start, End int32 // both inclusive +} + +// extendableProto is an interface implemented by any protocol buffer generated by the current +// proto compiler that may be extended. +type extendableProto interface { + Message + ExtensionRangeArray() []ExtensionRange + extensionsWrite() map[int32]Extension + extensionsRead() (map[int32]Extension, sync.Locker) +} + +// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous +// version of the proto compiler that may be extended. +type extendableProtoV1 interface { + Message + ExtensionRangeArray() []ExtensionRange + ExtensionMap() map[int32]Extension +} + +// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. +type extensionAdapter struct { + extendableProtoV1 +} + +func (e extensionAdapter) extensionsWrite() map[int32]Extension { + return e.ExtensionMap() +} + +func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { + return e.ExtensionMap(), notLocker{} +} + +// notLocker is a sync.Locker whose Lock and Unlock methods are nops. +type notLocker struct{} + +func (n notLocker) Lock() {} +func (n notLocker) Unlock() {} + +// extendable returns the extendableProto interface for the given generated proto message. +// If the proto message has the old extension format, it returns a wrapper that implements +// the extendableProto interface. +func extendable(p interface{}) (extendableProto, bool) { + if ep, ok := p.(extendableProto); ok { + return ep, ok + } + if ep, ok := p.(extendableProtoV1); ok { + return extensionAdapter{ep}, ok + } + return nil, false +} + +// XXX_InternalExtensions is an internal representation of proto extensions. +// +// Each generated message struct type embeds an anonymous XXX_InternalExtensions field, +// thus gaining the unexported 'extensions' method, which can be called only from the proto package. +// +// The methods of XXX_InternalExtensions are not concurrency safe in general, +// but calls to logically read-only methods such as has and get may be executed concurrently. +type XXX_InternalExtensions struct { + // The struct must be indirect so that if a user inadvertently copies a + // generated message and its embedded XXX_InternalExtensions, they + // avoid the mayhem of a copied mutex. + // + // The mutex serializes all logically read-only operations to p.extensionMap. + // It is up to the client to ensure that write operations to p.extensionMap are + // mutually exclusive with other accesses. + p *struct { + mu sync.Mutex + extensionMap map[int32]Extension + } +} + +// extensionsWrite returns the extension map, creating it on first use. +func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { + if e.p == nil { + e.p = new(struct { + mu sync.Mutex + extensionMap map[int32]Extension + }) + e.p.extensionMap = make(map[int32]Extension) + } + return e.p.extensionMap +} + +// extensionsRead returns the extensions map for read-only use. It may be nil. +// The caller must hold the returned mutex's lock when accessing Elements within the map. +func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { + if e.p == nil { + return nil, nil + } + return e.p.extensionMap, &e.p.mu +} + +var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem() +var extendableProtoV1Type = reflect.TypeOf((*extendableProtoV1)(nil)).Elem() + +// ExtensionDesc represents an extension specification. +// Used in generated code from the protocol compiler. +type ExtensionDesc struct { + ExtendedType Message // nil pointer to the type that is being extended + ExtensionType interface{} // nil pointer to the extension type + Field int32 // field number + Name string // fully-qualified name of extension, for text formatting + Tag string // protobuf tag style + Filename string // name of the file in which the extension is defined +} + +func (ed *ExtensionDesc) repeated() bool { + t := reflect.TypeOf(ed.ExtensionType) + return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 +} + +// Extension represents an extension in a message. +type Extension struct { + // When an extension is stored in a message using SetExtension + // only desc and value are set. When the message is marshaled + // enc will be set to the encoded form of the message. + // + // When a message is unmarshaled and contains extensions, each + // extension will have only enc set. When such an extension is + // accessed using GetExtension (or GetExtensions) desc and value + // will be set. + desc *ExtensionDesc + value interface{} + enc []byte +} + +// SetRawExtension is for testing only. +func SetRawExtension(base Message, id int32, b []byte) { + epb, ok := extendable(base) + if !ok { + return + } + extmap := epb.extensionsWrite() + extmap[id] = Extension{enc: b} +} + +// isExtensionField returns true iff the given field number is in an extension range. +func isExtensionField(pb extendableProto, field int32) bool { + for _, er := range pb.ExtensionRangeArray() { + if er.Start <= field && field <= er.End { + return true + } + } + return false +} + +// checkExtensionTypes checks that the given extension is valid for pb. +func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { + var pbi interface{} = pb + // Check the extended type. + if ea, ok := pbi.(extensionAdapter); ok { + pbi = ea.extendableProtoV1 + } + if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { + return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String()) + } + // Check the range. + if !isExtensionField(pb, extension.Field) { + return errors.New("proto: bad extension number; not in declared ranges") + } + return nil +} + +// extPropKey is sufficient to uniquely identify an extension. +type extPropKey struct { + base reflect.Type + field int32 +} + +var extProp = struct { + sync.RWMutex + m map[extPropKey]*Properties +}{ + m: make(map[extPropKey]*Properties), +} + +func extensionProperties(ed *ExtensionDesc) *Properties { + key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} + + extProp.RLock() + if prop, ok := extProp.m[key]; ok { + extProp.RUnlock() + return prop + } + extProp.RUnlock() + + extProp.Lock() + defer extProp.Unlock() + // Check again. + if prop, ok := extProp.m[key]; ok { + return prop + } + + prop := new(Properties) + prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) + extProp.m[key] = prop + return prop +} + +// encode encodes any unmarshaled (unencoded) extensions in e. +func encodeExtensions(e *XXX_InternalExtensions) error { + m, mu := e.extensionsRead() + if m == nil { + return nil // fast path + } + mu.Lock() + defer mu.Unlock() + return encodeExtensionsMap(m) +} + +// encode encodes any unmarshaled (unencoded) extensions in e. +func encodeExtensionsMap(m map[int32]Extension) error { + for k, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + et := reflect.TypeOf(e.desc.ExtensionType) + props := extensionProperties(e.desc) + + p := NewBuffer(nil) + // If e.value has type T, the encoder expects a *struct{ X T }. + // Pass a *T with a zero field and hope it all works out. + x := reflect.New(et) + x.Elem().Set(reflect.ValueOf(e.value)) + if err := props.enc(p, props, toStructPointer(x)); err != nil { + return err + } + e.enc = p.buf + m[k] = e + } + return nil +} + +func extensionsSize(e *XXX_InternalExtensions) (n int) { + m, mu := e.extensionsRead() + if m == nil { + return 0 + } + mu.Lock() + defer mu.Unlock() + return extensionsMapSize(m) +} + +func extensionsMapSize(m map[int32]Extension) (n int) { + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + n += len(e.enc) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + et := reflect.TypeOf(e.desc.ExtensionType) + props := extensionProperties(e.desc) + + // If e.value has type T, the encoder expects a *struct{ X T }. + // Pass a *T with a zero field and hope it all works out. + x := reflect.New(et) + x.Elem().Set(reflect.ValueOf(e.value)) + n += props.size(props, toStructPointer(x)) + } + return +} + +// HasExtension returns whether the given extension is present in pb. +func HasExtension(pb Message, extension *ExtensionDesc) bool { + // TODO: Check types, field numbers, etc.? + epb, ok := extendable(pb) + if !ok { + return false + } + extmap, mu := epb.extensionsRead() + if extmap == nil { + return false + } + mu.Lock() + _, ok = extmap[extension.Field] + mu.Unlock() + return ok +} + +// ClearExtension removes the given extension from pb. +func ClearExtension(pb Message, extension *ExtensionDesc) { + epb, ok := extendable(pb) + if !ok { + return + } + // TODO: Check types, field numbers, etc.? + extmap := epb.extensionsWrite() + delete(extmap, extension.Field) +} + +// GetExtension parses and returns the given extension of pb. +// If the extension is not present and has no default value it returns ErrMissingExtension. +func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { + epb, ok := extendable(pb) + if !ok { + return nil, errors.New("proto: not an extendable proto") + } + + if err := checkExtensionTypes(epb, extension); err != nil { + return nil, err + } + + emap, mu := epb.extensionsRead() + if emap == nil { + return defaultExtensionValue(extension) + } + mu.Lock() + defer mu.Unlock() + e, ok := emap[extension.Field] + if !ok { + // defaultExtensionValue returns the default value or + // ErrMissingExtension if there is no default. + return defaultExtensionValue(extension) + } + + if e.value != nil { + // Already decoded. Check the descriptor, though. + if e.desc != extension { + // This shouldn't happen. If it does, it means that + // GetExtension was called twice with two different + // descriptors with the same field number. + return nil, errors.New("proto: descriptor conflict") + } + return e.value, nil + } + + v, err := decodeExtension(e.enc, extension) + if err != nil { + return nil, err + } + + // Remember the decoded version and drop the encoded version. + // That way it is safe to mutate what we return. + e.value = v + e.desc = extension + e.enc = nil + emap[extension.Field] = e + return e.value, nil +} + +// defaultExtensionValue returns the default value for extension. +// If no default for an extension is defined ErrMissingExtension is returned. +func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { + t := reflect.TypeOf(extension.ExtensionType) + props := extensionProperties(extension) + + sf, _, err := fieldDefault(t, props) + if err != nil { + return nil, err + } + + if sf == nil || sf.value == nil { + // There is no default value. + return nil, ErrMissingExtension + } + + if t.Kind() != reflect.Ptr { + // We do not need to return a Ptr, we can directly return sf.value. + return sf.value, nil + } + + // We need to return an interface{} that is a pointer to sf.value. + value := reflect.New(t).Elem() + value.Set(reflect.New(value.Type().Elem())) + if sf.kind == reflect.Int32 { + // We may have an int32 or an enum, but the underlying data is int32. + // Since we can't set an int32 into a non int32 reflect.value directly + // set it as a int32. + value.Elem().SetInt(int64(sf.value.(int32))) + } else { + value.Elem().Set(reflect.ValueOf(sf.value)) + } + return value.Interface(), nil +} + +// decodeExtension decodes an extension encoded in b. +func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { + o := NewBuffer(b) + + t := reflect.TypeOf(extension.ExtensionType) + + props := extensionProperties(extension) + + // t is a pointer to a struct, pointer to basic type or a slice. + // Allocate a "field" to store the pointer/slice itself; the + // pointer/slice will be stored here. We pass + // the address of this field to props.dec. + // This passes a zero field and a *t and lets props.dec + // interpret it as a *struct{ x t }. + value := reflect.New(t).Elem() + + for { + // Discard wire type and field number varint. It isn't needed. + if _, err := o.DecodeVarint(); err != nil { + return nil, err + } + + if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil { + return nil, err + } + + if o.index >= len(o.buf) { + break + } + } + return value.Interface(), nil +} + +// GetExtensions returns a slice of the extensions present in pb that are also listed in es. +// The returned slice has the same length as es; missing extensions will appear as nil elements. +func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { + epb, ok := extendable(pb) + if !ok { + return nil, errors.New("proto: not an extendable proto") + } + extensions = make([]interface{}, len(es)) + for i, e := range es { + extensions[i], err = GetExtension(epb, e) + if err == ErrMissingExtension { + err = nil + } + if err != nil { + return + } + } + return +} + +// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. +// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing +// just the Field field, which defines the extension's field number. +func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { + epb, ok := extendable(pb) + if !ok { + return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb) + } + registeredExtensions := RegisteredExtensions(pb) + + emap, mu := epb.extensionsRead() + if emap == nil { + return nil, nil + } + mu.Lock() + defer mu.Unlock() + extensions := make([]*ExtensionDesc, 0, len(emap)) + for extid, e := range emap { + desc := e.desc + if desc == nil { + desc = registeredExtensions[extid] + if desc == nil { + desc = &ExtensionDesc{Field: extid} + } + } + + extensions = append(extensions, desc) + } + return extensions, nil +} + +// SetExtension sets the specified extension of pb to the specified value. +func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { + epb, ok := extendable(pb) + if !ok { + return errors.New("proto: not an extendable proto") + } + if err := checkExtensionTypes(epb, extension); err != nil { + return err + } + typ := reflect.TypeOf(extension.ExtensionType) + if typ != reflect.TypeOf(value) { + return errors.New("proto: bad extension value type") + } + // nil extension values need to be caught early, because the + // encoder can't distinguish an ErrNil due to a nil extension + // from an ErrNil due to a missing field. Extensions are + // always optional, so the encoder would just swallow the error + // and drop all the extensions from the encoded message. + if reflect.ValueOf(value).IsNil() { + return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) + } + + extmap := epb.extensionsWrite() + extmap[extension.Field] = Extension{desc: extension, value: value} + return nil +} + +// ClearAllExtensions clears all extensions from pb. +func ClearAllExtensions(pb Message) { + epb, ok := extendable(pb) + if !ok { + return + } + m := epb.extensionsWrite() + for k := range m { + delete(m, k) + } +} + +// A global registry of extensions. +// The generated code will register the generated descriptors by calling RegisterExtension. + +var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) + +// RegisterExtension is called from the generated code. +func RegisterExtension(desc *ExtensionDesc) { + st := reflect.TypeOf(desc.ExtendedType).Elem() + m := extensionMaps[st] + if m == nil { + m = make(map[int32]*ExtensionDesc) + extensionMaps[st] = m + } + if _, ok := m[desc.Field]; ok { + panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) + } + m[desc.Field] = desc +} + +// RegisteredExtensions returns a map of the registered extensions of a +// protocol buffer struct, indexed by the extension number. +// The argument pb should be a nil pointer to the struct type. +func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { + return extensionMaps[reflect.TypeOf(pb).Elem()] +} diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/lib.go b/metricbeat/vendor/github.com/golang/protobuf/proto/lib.go new file mode 100644 index 00000000000..ac4ddbc0759 --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/lib.go @@ -0,0 +1,898 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/* +Package proto converts data structures to and from the wire format of +protocol buffers. It works in concert with the Go source code generated +for .proto files by the protocol compiler. + +A summary of the properties of the protocol buffer interface +for a protocol buffer variable v: + + - Names are turned from camel_case to CamelCase for export. + - There are no methods on v to set fields; just treat + them as structure fields. + - There are getters that return a field's value if set, + and return the field's default value if unset. + The getters work even if the receiver is a nil message. + - The zero value for a struct is its correct initialization state. + All desired fields must be set before marshaling. + - A Reset() method will restore a protobuf struct to its zero state. + - Non-repeated fields are pointers to the values; nil means unset. + That is, optional or required field int32 f becomes F *int32. + - Repeated fields are slices. + - Helper functions are available to aid the setting of fields. + msg.Foo = proto.String("hello") // set field + - Constants are defined to hold the default values of all fields that + have them. They have the form Default_StructName_FieldName. + Because the getter methods handle defaulted values, + direct use of these constants should be rare. + - Enums are given type names and maps from names to values. + Enum values are prefixed by the enclosing message's name, or by the + enum's type name if it is a top-level enum. Enum types have a String + method, and a Enum method to assist in message construction. + - Nested messages, groups and enums have type names prefixed with the name of + the surrounding message type. + - Extensions are given descriptor names that start with E_, + followed by an underscore-delimited list of the nested messages + that contain it (if any) followed by the CamelCased name of the + extension field itself. HasExtension, ClearExtension, GetExtension + and SetExtension are functions for manipulating extensions. + - Oneof field sets are given a single field in their message, + with distinguished wrapper types for each possible field value. + - Marshal and Unmarshal are functions to encode and decode the wire format. + +When the .proto file specifies `syntax="proto3"`, there are some differences: + + - Non-repeated fields of non-message type are values instead of pointers. + - Getters are only generated for message and oneof fields. + - Enum types do not get an Enum method. + +The simplest way to describe this is to see an example. +Given file test.proto, containing + + package example; + + enum FOO { X = 17; } + + message Test { + required string label = 1; + optional int32 type = 2 [default=77]; + repeated int64 reps = 3; + optional group OptionalGroup = 4 { + required string RequiredField = 5; + } + oneof union { + int32 number = 6; + string name = 7; + } + } + +The resulting file, test.pb.go, is: + + package example + + import proto "github.com/golang/protobuf/proto" + import math "math" + + type FOO int32 + const ( + FOO_X FOO = 17 + ) + var FOO_name = map[int32]string{ + 17: "X", + } + var FOO_value = map[string]int32{ + "X": 17, + } + + func (x FOO) Enum() *FOO { + p := new(FOO) + *p = x + return p + } + func (x FOO) String() string { + return proto.EnumName(FOO_name, int32(x)) + } + func (x *FOO) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(FOO_value, data) + if err != nil { + return err + } + *x = FOO(value) + return nil + } + + type Test struct { + Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` + Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` + Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` + Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` + // Types that are valid to be assigned to Union: + // *Test_Number + // *Test_Name + Union isTest_Union `protobuf_oneof:"union"` + XXX_unrecognized []byte `json:"-"` + } + func (m *Test) Reset() { *m = Test{} } + func (m *Test) String() string { return proto.CompactTextString(m) } + func (*Test) ProtoMessage() {} + + type isTest_Union interface { + isTest_Union() + } + + type Test_Number struct { + Number int32 `protobuf:"varint,6,opt,name=number"` + } + type Test_Name struct { + Name string `protobuf:"bytes,7,opt,name=name"` + } + + func (*Test_Number) isTest_Union() {} + func (*Test_Name) isTest_Union() {} + + func (m *Test) GetUnion() isTest_Union { + if m != nil { + return m.Union + } + return nil + } + const Default_Test_Type int32 = 77 + + func (m *Test) GetLabel() string { + if m != nil && m.Label != nil { + return *m.Label + } + return "" + } + + func (m *Test) GetType() int32 { + if m != nil && m.Type != nil { + return *m.Type + } + return Default_Test_Type + } + + func (m *Test) GetOptionalgroup() *Test_OptionalGroup { + if m != nil { + return m.Optionalgroup + } + return nil + } + + type Test_OptionalGroup struct { + RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` + } + func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } + func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } + + func (m *Test_OptionalGroup) GetRequiredField() string { + if m != nil && m.RequiredField != nil { + return *m.RequiredField + } + return "" + } + + func (m *Test) GetNumber() int32 { + if x, ok := m.GetUnion().(*Test_Number); ok { + return x.Number + } + return 0 + } + + func (m *Test) GetName() string { + if x, ok := m.GetUnion().(*Test_Name); ok { + return x.Name + } + return "" + } + + func init() { + proto.RegisterEnum("example.FOO", FOO_name, FOO_value) + } + +To create and play with a Test object: + + package main + + import ( + "log" + + "github.com/golang/protobuf/proto" + pb "./example.pb" + ) + + func main() { + test := &pb.Test{ + Label: proto.String("hello"), + Type: proto.Int32(17), + Reps: []int64{1, 2, 3}, + Optionalgroup: &pb.Test_OptionalGroup{ + RequiredField: proto.String("good bye"), + }, + Union: &pb.Test_Name{"fred"}, + } + data, err := proto.Marshal(test) + if err != nil { + log.Fatal("marshaling error: ", err) + } + newTest := &pb.Test{} + err = proto.Unmarshal(data, newTest) + if err != nil { + log.Fatal("unmarshaling error: ", err) + } + // Now test and newTest contain the same data. + if test.GetLabel() != newTest.GetLabel() { + log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) + } + // Use a type switch to determine which oneof was set. + switch u := test.Union.(type) { + case *pb.Test_Number: // u.Number contains the number. + case *pb.Test_Name: // u.Name contains the string. + } + // etc. + } +*/ +package proto + +import ( + "encoding/json" + "fmt" + "log" + "reflect" + "sort" + "strconv" + "sync" +) + +// Message is implemented by generated protocol buffer messages. +type Message interface { + Reset() + String() string + ProtoMessage() +} + +// Stats records allocation details about the protocol buffer encoders +// and decoders. Useful for tuning the library itself. +type Stats struct { + Emalloc uint64 // mallocs in encode + Dmalloc uint64 // mallocs in decode + Encode uint64 // number of encodes + Decode uint64 // number of decodes + Chit uint64 // number of cache hits + Cmiss uint64 // number of cache misses + Size uint64 // number of sizes +} + +// Set to true to enable stats collection. +const collectStats = false + +var stats Stats + +// GetStats returns a copy of the global Stats structure. +func GetStats() Stats { return stats } + +// A Buffer is a buffer manager for marshaling and unmarshaling +// protocol buffers. It may be reused between invocations to +// reduce memory usage. It is not necessary to use a Buffer; +// the global functions Marshal and Unmarshal create a +// temporary Buffer and are fine for most applications. +type Buffer struct { + buf []byte // encode/decode byte stream + index int // read point + + // pools of basic types to amortize allocation. + bools []bool + uint32s []uint32 + uint64s []uint64 + + // extra pools, only used with pointer_reflect.go + int32s []int32 + int64s []int64 + float32s []float32 + float64s []float64 +} + +// NewBuffer allocates a new Buffer and initializes its internal data to +// the contents of the argument slice. +func NewBuffer(e []byte) *Buffer { + return &Buffer{buf: e} +} + +// Reset resets the Buffer, ready for marshaling a new protocol buffer. +func (p *Buffer) Reset() { + p.buf = p.buf[0:0] // for reading/writing + p.index = 0 // for reading +} + +// SetBuf replaces the internal buffer with the slice, +// ready for unmarshaling the contents of the slice. +func (p *Buffer) SetBuf(s []byte) { + p.buf = s + p.index = 0 +} + +// Bytes returns the contents of the Buffer. +func (p *Buffer) Bytes() []byte { return p.buf } + +/* + * Helper routines for simplifying the creation of optional fields of basic type. + */ + +// Bool is a helper routine that allocates a new bool value +// to store v and returns a pointer to it. +func Bool(v bool) *bool { + return &v +} + +// Int32 is a helper routine that allocates a new int32 value +// to store v and returns a pointer to it. +func Int32(v int32) *int32 { + return &v +} + +// Int is a helper routine that allocates a new int32 value +// to store v and returns a pointer to it, but unlike Int32 +// its argument value is an int. +func Int(v int) *int32 { + p := new(int32) + *p = int32(v) + return p +} + +// Int64 is a helper routine that allocates a new int64 value +// to store v and returns a pointer to it. +func Int64(v int64) *int64 { + return &v +} + +// Float32 is a helper routine that allocates a new float32 value +// to store v and returns a pointer to it. +func Float32(v float32) *float32 { + return &v +} + +// Float64 is a helper routine that allocates a new float64 value +// to store v and returns a pointer to it. +func Float64(v float64) *float64 { + return &v +} + +// Uint32 is a helper routine that allocates a new uint32 value +// to store v and returns a pointer to it. +func Uint32(v uint32) *uint32 { + return &v +} + +// Uint64 is a helper routine that allocates a new uint64 value +// to store v and returns a pointer to it. +func Uint64(v uint64) *uint64 { + return &v +} + +// String is a helper routine that allocates a new string value +// to store v and returns a pointer to it. +func String(v string) *string { + return &v +} + +// EnumName is a helper function to simplify printing protocol buffer enums +// by name. Given an enum map and a value, it returns a useful string. +func EnumName(m map[int32]string, v int32) string { + s, ok := m[v] + if ok { + return s + } + return strconv.Itoa(int(v)) +} + +// UnmarshalJSONEnum is a helper function to simplify recovering enum int values +// from their JSON-encoded representation. Given a map from the enum's symbolic +// names to its int values, and a byte buffer containing the JSON-encoded +// value, it returns an int32 that can be cast to the enum type by the caller. +// +// The function can deal with both JSON representations, numeric and symbolic. +func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { + if data[0] == '"' { + // New style: enums are strings. + var repr string + if err := json.Unmarshal(data, &repr); err != nil { + return -1, err + } + val, ok := m[repr] + if !ok { + return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) + } + return val, nil + } + // Old style: enums are ints. + var val int32 + if err := json.Unmarshal(data, &val); err != nil { + return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) + } + return val, nil +} + +// DebugPrint dumps the encoded data in b in a debugging format with a header +// including the string s. Used in testing but made available for general debugging. +func (p *Buffer) DebugPrint(s string, b []byte) { + var u uint64 + + obuf := p.buf + index := p.index + p.buf = b + p.index = 0 + depth := 0 + + fmt.Printf("\n--- %s ---\n", s) + +out: + for { + for i := 0; i < depth; i++ { + fmt.Print(" ") + } + + index := p.index + if index == len(p.buf) { + break + } + + op, err := p.DecodeVarint() + if err != nil { + fmt.Printf("%3d: fetching op err %v\n", index, err) + break out + } + tag := op >> 3 + wire := op & 7 + + switch wire { + default: + fmt.Printf("%3d: t=%3d unknown wire=%d\n", + index, tag, wire) + break out + + case WireBytes: + var r []byte + + r, err = p.DecodeRawBytes(false) + if err != nil { + break out + } + fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) + if len(r) <= 6 { + for i := 0; i < len(r); i++ { + fmt.Printf(" %.2x", r[i]) + } + } else { + for i := 0; i < 3; i++ { + fmt.Printf(" %.2x", r[i]) + } + fmt.Printf(" ..") + for i := len(r) - 3; i < len(r); i++ { + fmt.Printf(" %.2x", r[i]) + } + } + fmt.Printf("\n") + + case WireFixed32: + u, err = p.DecodeFixed32() + if err != nil { + fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) + + case WireFixed64: + u, err = p.DecodeFixed64() + if err != nil { + fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) + + case WireVarint: + u, err = p.DecodeVarint() + if err != nil { + fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) + break out + } + fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) + + case WireStartGroup: + fmt.Printf("%3d: t=%3d start\n", index, tag) + depth++ + + case WireEndGroup: + depth-- + fmt.Printf("%3d: t=%3d end\n", index, tag) + } + } + + if depth != 0 { + fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) + } + fmt.Printf("\n") + + p.buf = obuf + p.index = index +} + +// SetDefaults sets unset protocol buffer fields to their default values. +// It only modifies fields that are both unset and have defined defaults. +// It recursively sets default values in any non-nil sub-messages. +func SetDefaults(pb Message) { + setDefaults(reflect.ValueOf(pb), true, false) +} + +// v is a pointer to a struct. +func setDefaults(v reflect.Value, recur, zeros bool) { + v = v.Elem() + + defaultMu.RLock() + dm, ok := defaults[v.Type()] + defaultMu.RUnlock() + if !ok { + dm = buildDefaultMessage(v.Type()) + defaultMu.Lock() + defaults[v.Type()] = dm + defaultMu.Unlock() + } + + for _, sf := range dm.scalars { + f := v.Field(sf.index) + if !f.IsNil() { + // field already set + continue + } + dv := sf.value + if dv == nil && !zeros { + // no explicit default, and don't want to set zeros + continue + } + fptr := f.Addr().Interface() // **T + // TODO: Consider batching the allocations we do here. + switch sf.kind { + case reflect.Bool: + b := new(bool) + if dv != nil { + *b = dv.(bool) + } + *(fptr.(**bool)) = b + case reflect.Float32: + f := new(float32) + if dv != nil { + *f = dv.(float32) + } + *(fptr.(**float32)) = f + case reflect.Float64: + f := new(float64) + if dv != nil { + *f = dv.(float64) + } + *(fptr.(**float64)) = f + case reflect.Int32: + // might be an enum + if ft := f.Type(); ft != int32PtrType { + // enum + f.Set(reflect.New(ft.Elem())) + if dv != nil { + f.Elem().SetInt(int64(dv.(int32))) + } + } else { + // int32 field + i := new(int32) + if dv != nil { + *i = dv.(int32) + } + *(fptr.(**int32)) = i + } + case reflect.Int64: + i := new(int64) + if dv != nil { + *i = dv.(int64) + } + *(fptr.(**int64)) = i + case reflect.String: + s := new(string) + if dv != nil { + *s = dv.(string) + } + *(fptr.(**string)) = s + case reflect.Uint8: + // exceptional case: []byte + var b []byte + if dv != nil { + db := dv.([]byte) + b = make([]byte, len(db)) + copy(b, db) + } else { + b = []byte{} + } + *(fptr.(*[]byte)) = b + case reflect.Uint32: + u := new(uint32) + if dv != nil { + *u = dv.(uint32) + } + *(fptr.(**uint32)) = u + case reflect.Uint64: + u := new(uint64) + if dv != nil { + *u = dv.(uint64) + } + *(fptr.(**uint64)) = u + default: + log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) + } + } + + for _, ni := range dm.nested { + f := v.Field(ni) + // f is *T or []*T or map[T]*T + switch f.Kind() { + case reflect.Ptr: + if f.IsNil() { + continue + } + setDefaults(f, recur, zeros) + + case reflect.Slice: + for i := 0; i < f.Len(); i++ { + e := f.Index(i) + if e.IsNil() { + continue + } + setDefaults(e, recur, zeros) + } + + case reflect.Map: + for _, k := range f.MapKeys() { + e := f.MapIndex(k) + if e.IsNil() { + continue + } + setDefaults(e, recur, zeros) + } + } + } +} + +var ( + // defaults maps a protocol buffer struct type to a slice of the fields, + // with its scalar fields set to their proto-declared non-zero default values. + defaultMu sync.RWMutex + defaults = make(map[reflect.Type]defaultMessage) + + int32PtrType = reflect.TypeOf((*int32)(nil)) +) + +// defaultMessage represents information about the default values of a message. +type defaultMessage struct { + scalars []scalarField + nested []int // struct field index of nested messages +} + +type scalarField struct { + index int // struct field index + kind reflect.Kind // element type (the T in *T or []T) + value interface{} // the proto-declared default value, or nil +} + +// t is a struct type. +func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { + sprop := GetProperties(t) + for _, prop := range sprop.Prop { + fi, ok := sprop.decoderTags.get(prop.Tag) + if !ok { + // XXX_unrecognized + continue + } + ft := t.Field(fi).Type + + sf, nested, err := fieldDefault(ft, prop) + switch { + case err != nil: + log.Print(err) + case nested: + dm.nested = append(dm.nested, fi) + case sf != nil: + sf.index = fi + dm.scalars = append(dm.scalars, *sf) + } + } + + return dm +} + +// fieldDefault returns the scalarField for field type ft. +// sf will be nil if the field can not have a default. +// nestedMessage will be true if this is a nested message. +// Note that sf.index is not set on return. +func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { + var canHaveDefault bool + switch ft.Kind() { + case reflect.Ptr: + if ft.Elem().Kind() == reflect.Struct { + nestedMessage = true + } else { + canHaveDefault = true // proto2 scalar field + } + + case reflect.Slice: + switch ft.Elem().Kind() { + case reflect.Ptr: + nestedMessage = true // repeated message + case reflect.Uint8: + canHaveDefault = true // bytes field + } + + case reflect.Map: + if ft.Elem().Kind() == reflect.Ptr { + nestedMessage = true // map with message values + } + } + + if !canHaveDefault { + if nestedMessage { + return nil, true, nil + } + return nil, false, nil + } + + // We now know that ft is a pointer or slice. + sf = &scalarField{kind: ft.Elem().Kind()} + + // scalar fields without defaults + if !prop.HasDefault { + return sf, false, nil + } + + // a scalar field: either *T or []byte + switch ft.Elem().Kind() { + case reflect.Bool: + x, err := strconv.ParseBool(prop.Default) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) + } + sf.value = x + case reflect.Float32: + x, err := strconv.ParseFloat(prop.Default, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) + } + sf.value = float32(x) + case reflect.Float64: + x, err := strconv.ParseFloat(prop.Default, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) + } + sf.value = x + case reflect.Int32: + x, err := strconv.ParseInt(prop.Default, 10, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) + } + sf.value = int32(x) + case reflect.Int64: + x, err := strconv.ParseInt(prop.Default, 10, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) + } + sf.value = x + case reflect.String: + sf.value = prop.Default + case reflect.Uint8: + // []byte (not *uint8) + sf.value = []byte(prop.Default) + case reflect.Uint32: + x, err := strconv.ParseUint(prop.Default, 10, 32) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) + } + sf.value = uint32(x) + case reflect.Uint64: + x, err := strconv.ParseUint(prop.Default, 10, 64) + if err != nil { + return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) + } + sf.value = x + default: + return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) + } + + return sf, false, nil +} + +// Map fields may have key types of non-float scalars, strings and enums. +// The easiest way to sort them in some deterministic order is to use fmt. +// If this turns out to be inefficient we can always consider other options, +// such as doing a Schwartzian transform. + +func mapKeys(vs []reflect.Value) sort.Interface { + s := mapKeySorter{ + vs: vs, + // default Less function: textual comparison + less: func(a, b reflect.Value) bool { + return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface()) + }, + } + + // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps; + // numeric keys are sorted numerically. + if len(vs) == 0 { + return s + } + switch vs[0].Kind() { + case reflect.Int32, reflect.Int64: + s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } + case reflect.Uint32, reflect.Uint64: + s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } + } + + return s +} + +type mapKeySorter struct { + vs []reflect.Value + less func(a, b reflect.Value) bool +} + +func (s mapKeySorter) Len() int { return len(s.vs) } +func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } +func (s mapKeySorter) Less(i, j int) bool { + return s.less(s.vs[i], s.vs[j]) +} + +// isProto3Zero reports whether v is a zero proto3 value. +func isProto3Zero(v reflect.Value) bool { + switch v.Kind() { + case reflect.Bool: + return !v.Bool() + case reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint32, reflect.Uint64: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.String: + return v.String() == "" + } + return false +} + +// ProtoPackageIsVersion2 is referenced from generated protocol buffer files +// to assert that that code is compatible with this version of the proto package. +const ProtoPackageIsVersion2 = true + +// ProtoPackageIsVersion1 is referenced from generated protocol buffer files +// to assert that that code is compatible with this version of the proto package. +const ProtoPackageIsVersion1 = true diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/message_set.go b/metricbeat/vendor/github.com/golang/protobuf/proto/message_set.go new file mode 100644 index 00000000000..fd982decd66 --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/message_set.go @@ -0,0 +1,311 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Support for message sets. + */ + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "reflect" + "sort" +) + +// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. +// A message type ID is required for storing a protocol buffer in a message set. +var errNoMessageTypeID = errors.New("proto does not have a message type ID") + +// The first two types (_MessageSet_Item and messageSet) +// model what the protocol compiler produces for the following protocol message: +// message MessageSet { +// repeated group Item = 1 { +// required int32 type_id = 2; +// required string message = 3; +// }; +// } +// That is the MessageSet wire format. We can't use a proto to generate these +// because that would introduce a circular dependency between it and this package. + +type _MessageSet_Item struct { + TypeId *int32 `protobuf:"varint,2,req,name=type_id"` + Message []byte `protobuf:"bytes,3,req,name=message"` +} + +type messageSet struct { + Item []*_MessageSet_Item `protobuf:"group,1,rep"` + XXX_unrecognized []byte + // TODO: caching? +} + +// Make sure messageSet is a Message. +var _ Message = (*messageSet)(nil) + +// messageTypeIder is an interface satisfied by a protocol buffer type +// that may be stored in a MessageSet. +type messageTypeIder interface { + MessageTypeId() int32 +} + +func (ms *messageSet) find(pb Message) *_MessageSet_Item { + mti, ok := pb.(messageTypeIder) + if !ok { + return nil + } + id := mti.MessageTypeId() + for _, item := range ms.Item { + if *item.TypeId == id { + return item + } + } + return nil +} + +func (ms *messageSet) Has(pb Message) bool { + if ms.find(pb) != nil { + return true + } + return false +} + +func (ms *messageSet) Unmarshal(pb Message) error { + if item := ms.find(pb); item != nil { + return Unmarshal(item.Message, pb) + } + if _, ok := pb.(messageTypeIder); !ok { + return errNoMessageTypeID + } + return nil // TODO: return error instead? +} + +func (ms *messageSet) Marshal(pb Message) error { + msg, err := Marshal(pb) + if err != nil { + return err + } + if item := ms.find(pb); item != nil { + // reuse existing item + item.Message = msg + return nil + } + + mti, ok := pb.(messageTypeIder) + if !ok { + return errNoMessageTypeID + } + + mtid := mti.MessageTypeId() + ms.Item = append(ms.Item, &_MessageSet_Item{ + TypeId: &mtid, + Message: msg, + }) + return nil +} + +func (ms *messageSet) Reset() { *ms = messageSet{} } +func (ms *messageSet) String() string { return CompactTextString(ms) } +func (*messageSet) ProtoMessage() {} + +// Support for the message_set_wire_format message option. + +func skipVarint(buf []byte) []byte { + i := 0 + for ; buf[i]&0x80 != 0; i++ { + } + return buf[i+1:] +} + +// MarshalMessageSet encodes the extension map represented by m in the message set wire format. +// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. +func MarshalMessageSet(exts interface{}) ([]byte, error) { + var m map[int32]Extension + switch exts := exts.(type) { + case *XXX_InternalExtensions: + if err := encodeExtensions(exts); err != nil { + return nil, err + } + m, _ = exts.extensionsRead() + case map[int32]Extension: + if err := encodeExtensionsMap(exts); err != nil { + return nil, err + } + m = exts + default: + return nil, errors.New("proto: not an extension map") + } + + // Sort extension IDs to provide a deterministic encoding. + // See also enc_map in encode.go. + ids := make([]int, 0, len(m)) + for id := range m { + ids = append(ids, int(id)) + } + sort.Ints(ids) + + ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))} + for _, id := range ids { + e := m[int32(id)] + // Remove the wire type and field number varint, as well as the length varint. + msg := skipVarint(skipVarint(e.enc)) + + ms.Item = append(ms.Item, &_MessageSet_Item{ + TypeId: Int32(int32(id)), + Message: msg, + }) + } + return Marshal(ms) +} + +// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. +// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. +func UnmarshalMessageSet(buf []byte, exts interface{}) error { + var m map[int32]Extension + switch exts := exts.(type) { + case *XXX_InternalExtensions: + m = exts.extensionsWrite() + case map[int32]Extension: + m = exts + default: + return errors.New("proto: not an extension map") + } + + ms := new(messageSet) + if err := Unmarshal(buf, ms); err != nil { + return err + } + for _, item := range ms.Item { + id := *item.TypeId + msg := item.Message + + // Restore wire type and field number varint, plus length varint. + // Be careful to preserve duplicate items. + b := EncodeVarint(uint64(id)<<3 | WireBytes) + if ext, ok := m[id]; ok { + // Existing data; rip off the tag and length varint + // so we join the new data correctly. + // We can assume that ext.enc is set because we are unmarshaling. + o := ext.enc[len(b):] // skip wire type and field number + _, n := DecodeVarint(o) // calculate length of length varint + o = o[n:] // skip length varint + msg = append(o, msg...) // join old data and new data + } + b = append(b, EncodeVarint(uint64(len(msg)))...) + b = append(b, msg...) + + m[id] = Extension{enc: b} + } + return nil +} + +// MarshalMessageSetJSON encodes the extension map represented by m in JSON format. +// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. +func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { + var m map[int32]Extension + switch exts := exts.(type) { + case *XXX_InternalExtensions: + m, _ = exts.extensionsRead() + case map[int32]Extension: + m = exts + default: + return nil, errors.New("proto: not an extension map") + } + var b bytes.Buffer + b.WriteByte('{') + + // Process the map in key order for deterministic output. + ids := make([]int32, 0, len(m)) + for id := range m { + ids = append(ids, id) + } + sort.Sort(int32Slice(ids)) // int32Slice defined in text.go + + for i, id := range ids { + ext := m[id] + if i > 0 { + b.WriteByte(',') + } + + msd, ok := messageSetMap[id] + if !ok { + // Unknown type; we can't render it, so skip it. + continue + } + fmt.Fprintf(&b, `"[%s]":`, msd.name) + + x := ext.value + if x == nil { + x = reflect.New(msd.t.Elem()).Interface() + if err := Unmarshal(ext.enc, x.(Message)); err != nil { + return nil, err + } + } + d, err := json.Marshal(x) + if err != nil { + return nil, err + } + b.Write(d) + } + b.WriteByte('}') + return b.Bytes(), nil +} + +// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. +// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. +func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { + // Common-case fast path. + if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { + return nil + } + + // This is fairly tricky, and it's not clear that it is needed. + return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") +} + +// A global registry of types that can be used in a MessageSet. + +var messageSetMap = make(map[int32]messageSetDesc) + +type messageSetDesc struct { + t reflect.Type // pointer to struct + name string +} + +// RegisterMessageSetType is called from the generated code. +func RegisterMessageSetType(m Message, fieldNum int32, name string) { + messageSetMap[fieldNum] = messageSetDesc{ + t: reflect.TypeOf(m), + name: name, + } +} diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/metricbeat/vendor/github.com/golang/protobuf/proto/pointer_reflect.go new file mode 100644 index 00000000000..fb512e2e16d --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/pointer_reflect.go @@ -0,0 +1,484 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2012 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// +build appengine js + +// This file contains an implementation of proto field accesses using package reflect. +// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can +// be used on App Engine. + +package proto + +import ( + "math" + "reflect" +) + +// A structPointer is a pointer to a struct. +type structPointer struct { + v reflect.Value +} + +// toStructPointer returns a structPointer equivalent to the given reflect value. +// The reflect value must itself be a pointer to a struct. +func toStructPointer(v reflect.Value) structPointer { + return structPointer{v} +} + +// IsNil reports whether p is nil. +func structPointer_IsNil(p structPointer) bool { + return p.v.IsNil() +} + +// Interface returns the struct pointer as an interface value. +func structPointer_Interface(p structPointer, _ reflect.Type) interface{} { + return p.v.Interface() +} + +// A field identifies a field in a struct, accessible from a structPointer. +// In this implementation, a field is identified by the sequence of field indices +// passed to reflect's FieldByIndex. +type field []int + +// toField returns a field equivalent to the given reflect field. +func toField(f *reflect.StructField) field { + return f.Index +} + +// invalidField is an invalid field identifier. +var invalidField = field(nil) + +// IsValid reports whether the field identifier is valid. +func (f field) IsValid() bool { return f != nil } + +// field returns the given field in the struct as a reflect value. +func structPointer_field(p structPointer, f field) reflect.Value { + // Special case: an extension map entry with a value of type T + // passes a *T to the struct-handling code with a zero field, + // expecting that it will be treated as equivalent to *struct{ X T }, + // which has the same memory layout. We have to handle that case + // specially, because reflect will panic if we call FieldByIndex on a + // non-struct. + if f == nil { + return p.v.Elem() + } + + return p.v.Elem().FieldByIndex(f) +} + +// ifield returns the given field in the struct as an interface value. +func structPointer_ifield(p structPointer, f field) interface{} { + return structPointer_field(p, f).Addr().Interface() +} + +// Bytes returns the address of a []byte field in the struct. +func structPointer_Bytes(p structPointer, f field) *[]byte { + return structPointer_ifield(p, f).(*[]byte) +} + +// BytesSlice returns the address of a [][]byte field in the struct. +func structPointer_BytesSlice(p structPointer, f field) *[][]byte { + return structPointer_ifield(p, f).(*[][]byte) +} + +// Bool returns the address of a *bool field in the struct. +func structPointer_Bool(p structPointer, f field) **bool { + return structPointer_ifield(p, f).(**bool) +} + +// BoolVal returns the address of a bool field in the struct. +func structPointer_BoolVal(p structPointer, f field) *bool { + return structPointer_ifield(p, f).(*bool) +} + +// BoolSlice returns the address of a []bool field in the struct. +func structPointer_BoolSlice(p structPointer, f field) *[]bool { + return structPointer_ifield(p, f).(*[]bool) +} + +// String returns the address of a *string field in the struct. +func structPointer_String(p structPointer, f field) **string { + return structPointer_ifield(p, f).(**string) +} + +// StringVal returns the address of a string field in the struct. +func structPointer_StringVal(p structPointer, f field) *string { + return structPointer_ifield(p, f).(*string) +} + +// StringSlice returns the address of a []string field in the struct. +func structPointer_StringSlice(p structPointer, f field) *[]string { + return structPointer_ifield(p, f).(*[]string) +} + +// Extensions returns the address of an extension map field in the struct. +func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { + return structPointer_ifield(p, f).(*XXX_InternalExtensions) +} + +// ExtMap returns the address of an extension map field in the struct. +func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { + return structPointer_ifield(p, f).(*map[int32]Extension) +} + +// NewAt returns the reflect.Value for a pointer to a field in the struct. +func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { + return structPointer_field(p, f).Addr() +} + +// SetStructPointer writes a *struct field in the struct. +func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { + structPointer_field(p, f).Set(q.v) +} + +// GetStructPointer reads a *struct field in the struct. +func structPointer_GetStructPointer(p structPointer, f field) structPointer { + return structPointer{structPointer_field(p, f)} +} + +// StructPointerSlice the address of a []*struct field in the struct. +func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice { + return structPointerSlice{structPointer_field(p, f)} +} + +// A structPointerSlice represents the address of a slice of pointers to structs +// (themselves messages or groups). That is, v.Type() is *[]*struct{...}. +type structPointerSlice struct { + v reflect.Value +} + +func (p structPointerSlice) Len() int { return p.v.Len() } +func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} } +func (p structPointerSlice) Append(q structPointer) { + p.v.Set(reflect.Append(p.v, q.v)) +} + +var ( + int32Type = reflect.TypeOf(int32(0)) + uint32Type = reflect.TypeOf(uint32(0)) + float32Type = reflect.TypeOf(float32(0)) + int64Type = reflect.TypeOf(int64(0)) + uint64Type = reflect.TypeOf(uint64(0)) + float64Type = reflect.TypeOf(float64(0)) +) + +// A word32 represents a field of type *int32, *uint32, *float32, or *enum. +// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable. +type word32 struct { + v reflect.Value +} + +// IsNil reports whether p is nil. +func word32_IsNil(p word32) bool { + return p.v.IsNil() +} + +// Set sets p to point at a newly allocated word with bits set to x. +func word32_Set(p word32, o *Buffer, x uint32) { + t := p.v.Type().Elem() + switch t { + case int32Type: + if len(o.int32s) == 0 { + o.int32s = make([]int32, uint32PoolSize) + } + o.int32s[0] = int32(x) + p.v.Set(reflect.ValueOf(&o.int32s[0])) + o.int32s = o.int32s[1:] + return + case uint32Type: + if len(o.uint32s) == 0 { + o.uint32s = make([]uint32, uint32PoolSize) + } + o.uint32s[0] = x + p.v.Set(reflect.ValueOf(&o.uint32s[0])) + o.uint32s = o.uint32s[1:] + return + case float32Type: + if len(o.float32s) == 0 { + o.float32s = make([]float32, uint32PoolSize) + } + o.float32s[0] = math.Float32frombits(x) + p.v.Set(reflect.ValueOf(&o.float32s[0])) + o.float32s = o.float32s[1:] + return + } + + // must be enum + p.v.Set(reflect.New(t)) + p.v.Elem().SetInt(int64(int32(x))) +} + +// Get gets the bits pointed at by p, as a uint32. +func word32_Get(p word32) uint32 { + elem := p.v.Elem() + switch elem.Kind() { + case reflect.Int32: + return uint32(elem.Int()) + case reflect.Uint32: + return uint32(elem.Uint()) + case reflect.Float32: + return math.Float32bits(float32(elem.Float())) + } + panic("unreachable") +} + +// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct. +func structPointer_Word32(p structPointer, f field) word32 { + return word32{structPointer_field(p, f)} +} + +// A word32Val represents a field of type int32, uint32, float32, or enum. +// That is, v.Type() is int32, uint32, float32, or enum and v is assignable. +type word32Val struct { + v reflect.Value +} + +// Set sets *p to x. +func word32Val_Set(p word32Val, x uint32) { + switch p.v.Type() { + case int32Type: + p.v.SetInt(int64(x)) + return + case uint32Type: + p.v.SetUint(uint64(x)) + return + case float32Type: + p.v.SetFloat(float64(math.Float32frombits(x))) + return + } + + // must be enum + p.v.SetInt(int64(int32(x))) +} + +// Get gets the bits pointed at by p, as a uint32. +func word32Val_Get(p word32Val) uint32 { + elem := p.v + switch elem.Kind() { + case reflect.Int32: + return uint32(elem.Int()) + case reflect.Uint32: + return uint32(elem.Uint()) + case reflect.Float32: + return math.Float32bits(float32(elem.Float())) + } + panic("unreachable") +} + +// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct. +func structPointer_Word32Val(p structPointer, f field) word32Val { + return word32Val{structPointer_field(p, f)} +} + +// A word32Slice is a slice of 32-bit values. +// That is, v.Type() is []int32, []uint32, []float32, or []enum. +type word32Slice struct { + v reflect.Value +} + +func (p word32Slice) Append(x uint32) { + n, m := p.v.Len(), p.v.Cap() + if n < m { + p.v.SetLen(n + 1) + } else { + t := p.v.Type().Elem() + p.v.Set(reflect.Append(p.v, reflect.Zero(t))) + } + elem := p.v.Index(n) + switch elem.Kind() { + case reflect.Int32: + elem.SetInt(int64(int32(x))) + case reflect.Uint32: + elem.SetUint(uint64(x)) + case reflect.Float32: + elem.SetFloat(float64(math.Float32frombits(x))) + } +} + +func (p word32Slice) Len() int { + return p.v.Len() +} + +func (p word32Slice) Index(i int) uint32 { + elem := p.v.Index(i) + switch elem.Kind() { + case reflect.Int32: + return uint32(elem.Int()) + case reflect.Uint32: + return uint32(elem.Uint()) + case reflect.Float32: + return math.Float32bits(float32(elem.Float())) + } + panic("unreachable") +} + +// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct. +func structPointer_Word32Slice(p structPointer, f field) word32Slice { + return word32Slice{structPointer_field(p, f)} +} + +// word64 is like word32 but for 64-bit values. +type word64 struct { + v reflect.Value +} + +func word64_Set(p word64, o *Buffer, x uint64) { + t := p.v.Type().Elem() + switch t { + case int64Type: + if len(o.int64s) == 0 { + o.int64s = make([]int64, uint64PoolSize) + } + o.int64s[0] = int64(x) + p.v.Set(reflect.ValueOf(&o.int64s[0])) + o.int64s = o.int64s[1:] + return + case uint64Type: + if len(o.uint64s) == 0 { + o.uint64s = make([]uint64, uint64PoolSize) + } + o.uint64s[0] = x + p.v.Set(reflect.ValueOf(&o.uint64s[0])) + o.uint64s = o.uint64s[1:] + return + case float64Type: + if len(o.float64s) == 0 { + o.float64s = make([]float64, uint64PoolSize) + } + o.float64s[0] = math.Float64frombits(x) + p.v.Set(reflect.ValueOf(&o.float64s[0])) + o.float64s = o.float64s[1:] + return + } + panic("unreachable") +} + +func word64_IsNil(p word64) bool { + return p.v.IsNil() +} + +func word64_Get(p word64) uint64 { + elem := p.v.Elem() + switch elem.Kind() { + case reflect.Int64: + return uint64(elem.Int()) + case reflect.Uint64: + return elem.Uint() + case reflect.Float64: + return math.Float64bits(elem.Float()) + } + panic("unreachable") +} + +func structPointer_Word64(p structPointer, f field) word64 { + return word64{structPointer_field(p, f)} +} + +// word64Val is like word32Val but for 64-bit values. +type word64Val struct { + v reflect.Value +} + +func word64Val_Set(p word64Val, o *Buffer, x uint64) { + switch p.v.Type() { + case int64Type: + p.v.SetInt(int64(x)) + return + case uint64Type: + p.v.SetUint(x) + return + case float64Type: + p.v.SetFloat(math.Float64frombits(x)) + return + } + panic("unreachable") +} + +func word64Val_Get(p word64Val) uint64 { + elem := p.v + switch elem.Kind() { + case reflect.Int64: + return uint64(elem.Int()) + case reflect.Uint64: + return elem.Uint() + case reflect.Float64: + return math.Float64bits(elem.Float()) + } + panic("unreachable") +} + +func structPointer_Word64Val(p structPointer, f field) word64Val { + return word64Val{structPointer_field(p, f)} +} + +type word64Slice struct { + v reflect.Value +} + +func (p word64Slice) Append(x uint64) { + n, m := p.v.Len(), p.v.Cap() + if n < m { + p.v.SetLen(n + 1) + } else { + t := p.v.Type().Elem() + p.v.Set(reflect.Append(p.v, reflect.Zero(t))) + } + elem := p.v.Index(n) + switch elem.Kind() { + case reflect.Int64: + elem.SetInt(int64(int64(x))) + case reflect.Uint64: + elem.SetUint(uint64(x)) + case reflect.Float64: + elem.SetFloat(float64(math.Float64frombits(x))) + } +} + +func (p word64Slice) Len() int { + return p.v.Len() +} + +func (p word64Slice) Index(i int) uint64 { + elem := p.v.Index(i) + switch elem.Kind() { + case reflect.Int64: + return uint64(elem.Int()) + case reflect.Uint64: + return uint64(elem.Uint()) + case reflect.Float64: + return math.Float64bits(float64(elem.Float())) + } + panic("unreachable") +} + +func structPointer_Word64Slice(p structPointer, f field) word64Slice { + return word64Slice{structPointer_field(p, f)} +} diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/metricbeat/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go new file mode 100644 index 00000000000..6b5567d47cd --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go @@ -0,0 +1,270 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2012 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// +build !appengine,!js + +// This file contains the implementation of the proto field accesses using package unsafe. + +package proto + +import ( + "reflect" + "unsafe" +) + +// NOTE: These type_Foo functions would more idiomatically be methods, +// but Go does not allow methods on pointer types, and we must preserve +// some pointer type for the garbage collector. We use these +// funcs with clunky names as our poor approximation to methods. +// +// An alternative would be +// type structPointer struct { p unsafe.Pointer } +// but that does not registerize as well. + +// A structPointer is a pointer to a struct. +type structPointer unsafe.Pointer + +// toStructPointer returns a structPointer equivalent to the given reflect value. +func toStructPointer(v reflect.Value) structPointer { + return structPointer(unsafe.Pointer(v.Pointer())) +} + +// IsNil reports whether p is nil. +func structPointer_IsNil(p structPointer) bool { + return p == nil +} + +// Interface returns the struct pointer, assumed to have element type t, +// as an interface value. +func structPointer_Interface(p structPointer, t reflect.Type) interface{} { + return reflect.NewAt(t, unsafe.Pointer(p)).Interface() +} + +// A field identifies a field in a struct, accessible from a structPointer. +// In this implementation, a field is identified by its byte offset from the start of the struct. +type field uintptr + +// toField returns a field equivalent to the given reflect field. +func toField(f *reflect.StructField) field { + return field(f.Offset) +} + +// invalidField is an invalid field identifier. +const invalidField = ^field(0) + +// IsValid reports whether the field identifier is valid. +func (f field) IsValid() bool { + return f != ^field(0) +} + +// Bytes returns the address of a []byte field in the struct. +func structPointer_Bytes(p structPointer, f field) *[]byte { + return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// BytesSlice returns the address of a [][]byte field in the struct. +func structPointer_BytesSlice(p structPointer, f field) *[][]byte { + return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// Bool returns the address of a *bool field in the struct. +func structPointer_Bool(p structPointer, f field) **bool { + return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// BoolVal returns the address of a bool field in the struct. +func structPointer_BoolVal(p structPointer, f field) *bool { + return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// BoolSlice returns the address of a []bool field in the struct. +func structPointer_BoolSlice(p structPointer, f field) *[]bool { + return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// String returns the address of a *string field in the struct. +func structPointer_String(p structPointer, f field) **string { + return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// StringVal returns the address of a string field in the struct. +func structPointer_StringVal(p structPointer, f field) *string { + return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// StringSlice returns the address of a []string field in the struct. +func structPointer_StringSlice(p structPointer, f field) *[]string { + return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// ExtMap returns the address of an extension map field in the struct. +func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { + return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { + return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// NewAt returns the reflect.Value for a pointer to a field in the struct. +func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { + return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) +} + +// SetStructPointer writes a *struct field in the struct. +func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { + *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q +} + +// GetStructPointer reads a *struct field in the struct. +func structPointer_GetStructPointer(p structPointer, f field) structPointer { + return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// StructPointerSlice the address of a []*struct field in the struct. +func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { + return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). +type structPointerSlice []structPointer + +func (v *structPointerSlice) Len() int { return len(*v) } +func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } +func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } + +// A word32 is the address of a "pointer to 32-bit value" field. +type word32 **uint32 + +// IsNil reports whether *v is nil. +func word32_IsNil(p word32) bool { + return *p == nil +} + +// Set sets *v to point at a newly allocated word set to x. +func word32_Set(p word32, o *Buffer, x uint32) { + if len(o.uint32s) == 0 { + o.uint32s = make([]uint32, uint32PoolSize) + } + o.uint32s[0] = x + *p = &o.uint32s[0] + o.uint32s = o.uint32s[1:] +} + +// Get gets the value pointed at by *v. +func word32_Get(p word32) uint32 { + return **p +} + +// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. +func structPointer_Word32(p structPointer, f field) word32 { + return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +} + +// A word32Val is the address of a 32-bit value field. +type word32Val *uint32 + +// Set sets *p to x. +func word32Val_Set(p word32Val, x uint32) { + *p = x +} + +// Get gets the value pointed at by p. +func word32Val_Get(p word32Val) uint32 { + return *p +} + +// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. +func structPointer_Word32Val(p structPointer, f field) word32Val { + return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +} + +// A word32Slice is a slice of 32-bit values. +type word32Slice []uint32 + +func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } +func (v *word32Slice) Len() int { return len(*v) } +func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } + +// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. +func structPointer_Word32Slice(p structPointer, f field) *word32Slice { + return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + +// word64 is like word32 but for 64-bit values. +type word64 **uint64 + +func word64_Set(p word64, o *Buffer, x uint64) { + if len(o.uint64s) == 0 { + o.uint64s = make([]uint64, uint64PoolSize) + } + o.uint64s[0] = x + *p = &o.uint64s[0] + o.uint64s = o.uint64s[1:] +} + +func word64_IsNil(p word64) bool { + return *p == nil +} + +func word64_Get(p word64) uint64 { + return **p +} + +func structPointer_Word64(p structPointer, f field) word64 { + return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +} + +// word64Val is like word32Val but for 64-bit values. +type word64Val *uint64 + +func word64Val_Set(p word64Val, o *Buffer, x uint64) { + *p = x +} + +func word64Val_Get(p word64Val) uint64 { + return *p +} + +func structPointer_Word64Val(p structPointer, f field) word64Val { + return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +} + +// word64Slice is like word32Slice but for 64-bit values. +type word64Slice []uint64 + +func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } +func (v *word64Slice) Len() int { return len(*v) } +func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } + +func structPointer_Word64Slice(p structPointer, f field) *word64Slice { + return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/properties.go b/metricbeat/vendor/github.com/golang/protobuf/proto/properties.go new file mode 100644 index 00000000000..ec2289c0058 --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/properties.go @@ -0,0 +1,872 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +/* + * Routines for encoding data into the wire format for protocol buffers. + */ + +import ( + "fmt" + "log" + "os" + "reflect" + "sort" + "strconv" + "strings" + "sync" +) + +const debug bool = false + +// Constants that identify the encoding of a value on the wire. +const ( + WireVarint = 0 + WireFixed64 = 1 + WireBytes = 2 + WireStartGroup = 3 + WireEndGroup = 4 + WireFixed32 = 5 +) + +const startSize = 10 // initial slice/string sizes + +// Encoders are defined in encode.go +// An encoder outputs the full representation of a field, including its +// tag and encoder type. +type encoder func(p *Buffer, prop *Properties, base structPointer) error + +// A valueEncoder encodes a single integer in a particular encoding. +type valueEncoder func(o *Buffer, x uint64) error + +// Sizers are defined in encode.go +// A sizer returns the encoded size of a field, including its tag and encoder +// type. +type sizer func(prop *Properties, base structPointer) int + +// A valueSizer returns the encoded size of a single integer in a particular +// encoding. +type valueSizer func(x uint64) int + +// Decoders are defined in decode.go +// A decoder creates a value from its wire representation. +// Unrecognized subelements are saved in unrec. +type decoder func(p *Buffer, prop *Properties, base structPointer) error + +// A valueDecoder decodes a single integer in a particular encoding. +type valueDecoder func(o *Buffer) (x uint64, err error) + +// A oneofMarshaler does the marshaling for all oneof fields in a message. +type oneofMarshaler func(Message, *Buffer) error + +// A oneofUnmarshaler does the unmarshaling for a oneof field in a message. +type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error) + +// A oneofSizer does the sizing for all oneof fields in a message. +type oneofSizer func(Message) int + +// tagMap is an optimization over map[int]int for typical protocol buffer +// use-cases. Encoded protocol buffers are often in tag order with small tag +// numbers. +type tagMap struct { + fastTags []int + slowTags map[int]int +} + +// tagMapFastLimit is the upper bound on the tag number that will be stored in +// the tagMap slice rather than its map. +const tagMapFastLimit = 1024 + +func (p *tagMap) get(t int) (int, bool) { + if t > 0 && t < tagMapFastLimit { + if t >= len(p.fastTags) { + return 0, false + } + fi := p.fastTags[t] + return fi, fi >= 0 + } + fi, ok := p.slowTags[t] + return fi, ok +} + +func (p *tagMap) put(t int, fi int) { + if t > 0 && t < tagMapFastLimit { + for len(p.fastTags) < t+1 { + p.fastTags = append(p.fastTags, -1) + } + p.fastTags[t] = fi + return + } + if p.slowTags == nil { + p.slowTags = make(map[int]int) + } + p.slowTags[t] = fi +} + +// StructProperties represents properties for all the fields of a struct. +// decoderTags and decoderOrigNames should only be used by the decoder. +type StructProperties struct { + Prop []*Properties // properties for each field + reqCount int // required count + decoderTags tagMap // map from proto tag to struct field number + decoderOrigNames map[string]int // map from original name to struct field number + order []int // list of struct field numbers in tag order + unrecField field // field id of the XXX_unrecognized []byte field + extendable bool // is this an extendable proto + + oneofMarshaler oneofMarshaler + oneofUnmarshaler oneofUnmarshaler + oneofSizer oneofSizer + stype reflect.Type + + // OneofTypes contains information about the oneof fields in this message. + // It is keyed by the original name of a field. + OneofTypes map[string]*OneofProperties +} + +// OneofProperties represents information about a specific field in a oneof. +type OneofProperties struct { + Type reflect.Type // pointer to generated struct type for this oneof field + Field int // struct field number of the containing oneof in the message + Prop *Properties +} + +// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. +// See encode.go, (*Buffer).enc_struct. + +func (sp *StructProperties) Len() int { return len(sp.order) } +func (sp *StructProperties) Less(i, j int) bool { + return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag +} +func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } + +// Properties represents the protocol-specific behavior of a single struct field. +type Properties struct { + Name string // name of the field, for error messages + OrigName string // original name before protocol compiler (always set) + JSONName string // name to use for JSON; determined by protoc + Wire string + WireType int + Tag int + Required bool + Optional bool + Repeated bool + Packed bool // relevant for repeated primitives only + Enum string // set for enum types only + proto3 bool // whether this is known to be a proto3 field; set for []byte only + oneof bool // whether this is a oneof field + + Default string // default value + HasDefault bool // whether an explicit default was provided + def_uint64 uint64 + + enc encoder + valEnc valueEncoder // set for bool and numeric types only + field field + tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType) + tagbuf [8]byte + stype reflect.Type // set for struct types only + sprop *StructProperties // set for struct types only + isMarshaler bool + isUnmarshaler bool + + mtype reflect.Type // set for map types only + mkeyprop *Properties // set for map types only + mvalprop *Properties // set for map types only + + size sizer + valSize valueSizer // set for bool and numeric types only + + dec decoder + valDec valueDecoder // set for bool and numeric types only + + // If this is a packable field, this will be the decoder for the packed version of the field. + packedDec decoder +} + +// String formats the properties in the protobuf struct field tag style. +func (p *Properties) String() string { + s := p.Wire + s = "," + s += strconv.Itoa(p.Tag) + if p.Required { + s += ",req" + } + if p.Optional { + s += ",opt" + } + if p.Repeated { + s += ",rep" + } + if p.Packed { + s += ",packed" + } + s += ",name=" + p.OrigName + if p.JSONName != p.OrigName { + s += ",json=" + p.JSONName + } + if p.proto3 { + s += ",proto3" + } + if p.oneof { + s += ",oneof" + } + if len(p.Enum) > 0 { + s += ",enum=" + p.Enum + } + if p.HasDefault { + s += ",def=" + p.Default + } + return s +} + +// Parse populates p by parsing a string in the protobuf struct field tag style. +func (p *Properties) Parse(s string) { + // "bytes,49,opt,name=foo,def=hello!" + fields := strings.Split(s, ",") // breaks def=, but handled below. + if len(fields) < 2 { + fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) + return + } + + p.Wire = fields[0] + switch p.Wire { + case "varint": + p.WireType = WireVarint + p.valEnc = (*Buffer).EncodeVarint + p.valDec = (*Buffer).DecodeVarint + p.valSize = sizeVarint + case "fixed32": + p.WireType = WireFixed32 + p.valEnc = (*Buffer).EncodeFixed32 + p.valDec = (*Buffer).DecodeFixed32 + p.valSize = sizeFixed32 + case "fixed64": + p.WireType = WireFixed64 + p.valEnc = (*Buffer).EncodeFixed64 + p.valDec = (*Buffer).DecodeFixed64 + p.valSize = sizeFixed64 + case "zigzag32": + p.WireType = WireVarint + p.valEnc = (*Buffer).EncodeZigzag32 + p.valDec = (*Buffer).DecodeZigzag32 + p.valSize = sizeZigzag32 + case "zigzag64": + p.WireType = WireVarint + p.valEnc = (*Buffer).EncodeZigzag64 + p.valDec = (*Buffer).DecodeZigzag64 + p.valSize = sizeZigzag64 + case "bytes", "group": + p.WireType = WireBytes + // no numeric converter for non-numeric types + default: + fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) + return + } + + var err error + p.Tag, err = strconv.Atoi(fields[1]) + if err != nil { + return + } + + for i := 2; i < len(fields); i++ { + f := fields[i] + switch { + case f == "req": + p.Required = true + case f == "opt": + p.Optional = true + case f == "rep": + p.Repeated = true + case f == "packed": + p.Packed = true + case strings.HasPrefix(f, "name="): + p.OrigName = f[5:] + case strings.HasPrefix(f, "json="): + p.JSONName = f[5:] + case strings.HasPrefix(f, "enum="): + p.Enum = f[5:] + case f == "proto3": + p.proto3 = true + case f == "oneof": + p.oneof = true + case strings.HasPrefix(f, "def="): + p.HasDefault = true + p.Default = f[4:] // rest of string + if i+1 < len(fields) { + // Commas aren't escaped, and def is always last. + p.Default += "," + strings.Join(fields[i+1:], ",") + break + } + } + } +} + +func logNoSliceEnc(t1, t2 reflect.Type) { + fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2) +} + +var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() + +// Initialize the fields for encoding and decoding. +func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { + p.enc = nil + p.dec = nil + p.size = nil + + switch t1 := typ; t1.Kind() { + default: + fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1) + + // proto3 scalar types + + case reflect.Bool: + p.enc = (*Buffer).enc_proto3_bool + p.dec = (*Buffer).dec_proto3_bool + p.size = size_proto3_bool + case reflect.Int32: + p.enc = (*Buffer).enc_proto3_int32 + p.dec = (*Buffer).dec_proto3_int32 + p.size = size_proto3_int32 + case reflect.Uint32: + p.enc = (*Buffer).enc_proto3_uint32 + p.dec = (*Buffer).dec_proto3_int32 // can reuse + p.size = size_proto3_uint32 + case reflect.Int64, reflect.Uint64: + p.enc = (*Buffer).enc_proto3_int64 + p.dec = (*Buffer).dec_proto3_int64 + p.size = size_proto3_int64 + case reflect.Float32: + p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits + p.dec = (*Buffer).dec_proto3_int32 + p.size = size_proto3_uint32 + case reflect.Float64: + p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits + p.dec = (*Buffer).dec_proto3_int64 + p.size = size_proto3_int64 + case reflect.String: + p.enc = (*Buffer).enc_proto3_string + p.dec = (*Buffer).dec_proto3_string + p.size = size_proto3_string + + case reflect.Ptr: + switch t2 := t1.Elem(); t2.Kind() { + default: + fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2) + break + case reflect.Bool: + p.enc = (*Buffer).enc_bool + p.dec = (*Buffer).dec_bool + p.size = size_bool + case reflect.Int32: + p.enc = (*Buffer).enc_int32 + p.dec = (*Buffer).dec_int32 + p.size = size_int32 + case reflect.Uint32: + p.enc = (*Buffer).enc_uint32 + p.dec = (*Buffer).dec_int32 // can reuse + p.size = size_uint32 + case reflect.Int64, reflect.Uint64: + p.enc = (*Buffer).enc_int64 + p.dec = (*Buffer).dec_int64 + p.size = size_int64 + case reflect.Float32: + p.enc = (*Buffer).enc_uint32 // can just treat them as bits + p.dec = (*Buffer).dec_int32 + p.size = size_uint32 + case reflect.Float64: + p.enc = (*Buffer).enc_int64 // can just treat them as bits + p.dec = (*Buffer).dec_int64 + p.size = size_int64 + case reflect.String: + p.enc = (*Buffer).enc_string + p.dec = (*Buffer).dec_string + p.size = size_string + case reflect.Struct: + p.stype = t1.Elem() + p.isMarshaler = isMarshaler(t1) + p.isUnmarshaler = isUnmarshaler(t1) + if p.Wire == "bytes" { + p.enc = (*Buffer).enc_struct_message + p.dec = (*Buffer).dec_struct_message + p.size = size_struct_message + } else { + p.enc = (*Buffer).enc_struct_group + p.dec = (*Buffer).dec_struct_group + p.size = size_struct_group + } + } + + case reflect.Slice: + switch t2 := t1.Elem(); t2.Kind() { + default: + logNoSliceEnc(t1, t2) + break + case reflect.Bool: + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_bool + p.size = size_slice_packed_bool + } else { + p.enc = (*Buffer).enc_slice_bool + p.size = size_slice_bool + } + p.dec = (*Buffer).dec_slice_bool + p.packedDec = (*Buffer).dec_slice_packed_bool + case reflect.Int32: + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_int32 + p.size = size_slice_packed_int32 + } else { + p.enc = (*Buffer).enc_slice_int32 + p.size = size_slice_int32 + } + p.dec = (*Buffer).dec_slice_int32 + p.packedDec = (*Buffer).dec_slice_packed_int32 + case reflect.Uint32: + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_uint32 + p.size = size_slice_packed_uint32 + } else { + p.enc = (*Buffer).enc_slice_uint32 + p.size = size_slice_uint32 + } + p.dec = (*Buffer).dec_slice_int32 + p.packedDec = (*Buffer).dec_slice_packed_int32 + case reflect.Int64, reflect.Uint64: + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_int64 + p.size = size_slice_packed_int64 + } else { + p.enc = (*Buffer).enc_slice_int64 + p.size = size_slice_int64 + } + p.dec = (*Buffer).dec_slice_int64 + p.packedDec = (*Buffer).dec_slice_packed_int64 + case reflect.Uint8: + p.dec = (*Buffer).dec_slice_byte + if p.proto3 { + p.enc = (*Buffer).enc_proto3_slice_byte + p.size = size_proto3_slice_byte + } else { + p.enc = (*Buffer).enc_slice_byte + p.size = size_slice_byte + } + case reflect.Float32, reflect.Float64: + switch t2.Bits() { + case 32: + // can just treat them as bits + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_uint32 + p.size = size_slice_packed_uint32 + } else { + p.enc = (*Buffer).enc_slice_uint32 + p.size = size_slice_uint32 + } + p.dec = (*Buffer).dec_slice_int32 + p.packedDec = (*Buffer).dec_slice_packed_int32 + case 64: + // can just treat them as bits + if p.Packed { + p.enc = (*Buffer).enc_slice_packed_int64 + p.size = size_slice_packed_int64 + } else { + p.enc = (*Buffer).enc_slice_int64 + p.size = size_slice_int64 + } + p.dec = (*Buffer).dec_slice_int64 + p.packedDec = (*Buffer).dec_slice_packed_int64 + default: + logNoSliceEnc(t1, t2) + break + } + case reflect.String: + p.enc = (*Buffer).enc_slice_string + p.dec = (*Buffer).dec_slice_string + p.size = size_slice_string + case reflect.Ptr: + switch t3 := t2.Elem(); t3.Kind() { + default: + fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3) + break + case reflect.Struct: + p.stype = t2.Elem() + p.isMarshaler = isMarshaler(t2) + p.isUnmarshaler = isUnmarshaler(t2) + if p.Wire == "bytes" { + p.enc = (*Buffer).enc_slice_struct_message + p.dec = (*Buffer).dec_slice_struct_message + p.size = size_slice_struct_message + } else { + p.enc = (*Buffer).enc_slice_struct_group + p.dec = (*Buffer).dec_slice_struct_group + p.size = size_slice_struct_group + } + } + case reflect.Slice: + switch t2.Elem().Kind() { + default: + fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem()) + break + case reflect.Uint8: + p.enc = (*Buffer).enc_slice_slice_byte + p.dec = (*Buffer).dec_slice_slice_byte + p.size = size_slice_slice_byte + } + } + + case reflect.Map: + p.enc = (*Buffer).enc_new_map + p.dec = (*Buffer).dec_new_map + p.size = size_new_map + + p.mtype = t1 + p.mkeyprop = &Properties{} + p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) + p.mvalprop = &Properties{} + vtype := p.mtype.Elem() + if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { + // The value type is not a message (*T) or bytes ([]byte), + // so we need encoders for the pointer to this type. + vtype = reflect.PtrTo(vtype) + } + p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) + } + + // precalculate tag code + wire := p.WireType + if p.Packed { + wire = WireBytes + } + x := uint32(p.Tag)<<3 | uint32(wire) + i := 0 + for i = 0; x > 127; i++ { + p.tagbuf[i] = 0x80 | uint8(x&0x7F) + x >>= 7 + } + p.tagbuf[i] = uint8(x) + p.tagcode = p.tagbuf[0 : i+1] + + if p.stype != nil { + if lockGetProp { + p.sprop = GetProperties(p.stype) + } else { + p.sprop = getPropertiesLocked(p.stype) + } + } +} + +var ( + marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() + unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() +) + +// isMarshaler reports whether type t implements Marshaler. +func isMarshaler(t reflect.Type) bool { + // We're checking for (likely) pointer-receiver methods + // so if t is not a pointer, something is very wrong. + // The calls above only invoke isMarshaler on pointer types. + if t.Kind() != reflect.Ptr { + panic("proto: misuse of isMarshaler") + } + return t.Implements(marshalerType) +} + +// isUnmarshaler reports whether type t implements Unmarshaler. +func isUnmarshaler(t reflect.Type) bool { + // We're checking for (likely) pointer-receiver methods + // so if t is not a pointer, something is very wrong. + // The calls above only invoke isUnmarshaler on pointer types. + if t.Kind() != reflect.Ptr { + panic("proto: misuse of isUnmarshaler") + } + return t.Implements(unmarshalerType) +} + +// Init populates the properties from a protocol buffer struct tag. +func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { + p.init(typ, name, tag, f, true) +} + +func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { + // "bytes,49,opt,def=hello!" + p.Name = name + p.OrigName = name + if f != nil { + p.field = toField(f) + } + if tag == "" { + return + } + p.Parse(tag) + p.setEncAndDec(typ, f, lockGetProp) +} + +var ( + propertiesMu sync.RWMutex + propertiesMap = make(map[reflect.Type]*StructProperties) +) + +// GetProperties returns the list of properties for the type represented by t. +// t must represent a generated struct type of a protocol message. +func GetProperties(t reflect.Type) *StructProperties { + if t.Kind() != reflect.Struct { + panic("proto: type must have kind struct") + } + + // Most calls to GetProperties in a long-running program will be + // retrieving details for types we have seen before. + propertiesMu.RLock() + sprop, ok := propertiesMap[t] + propertiesMu.RUnlock() + if ok { + if collectStats { + stats.Chit++ + } + return sprop + } + + propertiesMu.Lock() + sprop = getPropertiesLocked(t) + propertiesMu.Unlock() + return sprop +} + +// getPropertiesLocked requires that propertiesMu is held. +func getPropertiesLocked(t reflect.Type) *StructProperties { + if prop, ok := propertiesMap[t]; ok { + if collectStats { + stats.Chit++ + } + return prop + } + if collectStats { + stats.Cmiss++ + } + + prop := new(StructProperties) + // in case of recursive protos, fill this in now. + propertiesMap[t] = prop + + // build properties + prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) || + reflect.PtrTo(t).Implements(extendableProtoV1Type) + prop.unrecField = invalidField + prop.Prop = make([]*Properties, t.NumField()) + prop.order = make([]int, t.NumField()) + + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + p := new(Properties) + name := f.Name + p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) + + if f.Name == "XXX_InternalExtensions" { // special case + p.enc = (*Buffer).enc_exts + p.dec = nil // not needed + p.size = size_exts + } else if f.Name == "XXX_extensions" { // special case + p.enc = (*Buffer).enc_map + p.dec = nil // not needed + p.size = size_map + } else if f.Name == "XXX_unrecognized" { // special case + prop.unrecField = toField(&f) + } + oneof := f.Tag.Get("protobuf_oneof") // special case + if oneof != "" { + // Oneof fields don't use the traditional protobuf tag. + p.OrigName = oneof + } + prop.Prop[i] = p + prop.order[i] = i + if debug { + print(i, " ", f.Name, " ", t.String(), " ") + if p.Tag > 0 { + print(p.String()) + } + print("\n") + } + if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" { + fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") + } + } + + // Re-order prop.order. + sort.Sort(prop) + + type oneofMessage interface { + XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) + } + if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { + var oots []interface{} + prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs() + prop.stype = t + + // Interpret oneof metadata. + prop.OneofTypes = make(map[string]*OneofProperties) + for _, oot := range oots { + oop := &OneofProperties{ + Type: reflect.ValueOf(oot).Type(), // *T + Prop: new(Properties), + } + sft := oop.Type.Elem().Field(0) + oop.Prop.Name = sft.Name + oop.Prop.Parse(sft.Tag.Get("protobuf")) + // There will be exactly one interface field that + // this new value is assignable to. + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Type.Kind() != reflect.Interface { + continue + } + if !oop.Type.AssignableTo(f.Type) { + continue + } + oop.Field = i + break + } + prop.OneofTypes[oop.Prop.OrigName] = oop + } + } + + // build required counts + // build tags + reqCount := 0 + prop.decoderOrigNames = make(map[string]int) + for i, p := range prop.Prop { + if strings.HasPrefix(p.Name, "XXX_") { + // Internal fields should not appear in tags/origNames maps. + // They are handled specially when encoding and decoding. + continue + } + if p.Required { + reqCount++ + } + prop.decoderTags.put(p.Tag, i) + prop.decoderOrigNames[p.OrigName] = i + } + prop.reqCount = reqCount + + return prop +} + +// Return the Properties object for the x[0]'th field of the structure. +func propByIndex(t reflect.Type, x []int) *Properties { + if len(x) != 1 { + fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t) + return nil + } + prop := GetProperties(t) + return prop.Prop[x[0]] +} + +// Get the address and type of a pointer to a struct from an interface. +func getbase(pb Message) (t reflect.Type, b structPointer, err error) { + if pb == nil { + err = ErrNil + return + } + // get the reflect type of the pointer to the struct. + t = reflect.TypeOf(pb) + // get the address of the struct. + value := reflect.ValueOf(pb) + b = toStructPointer(value) + return +} + +// A global registry of enum types. +// The generated code will register the generated maps by calling RegisterEnum. + +var enumValueMaps = make(map[string]map[string]int32) + +// RegisterEnum is called from the generated code to install the enum descriptor +// maps into the global table to aid parsing text format protocol buffers. +func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { + if _, ok := enumValueMaps[typeName]; ok { + panic("proto: duplicate enum registered: " + typeName) + } + enumValueMaps[typeName] = valueMap +} + +// EnumValueMap returns the mapping from names to integers of the +// enum type enumType, or a nil if not found. +func EnumValueMap(enumType string) map[string]int32 { + return enumValueMaps[enumType] +} + +// A registry of all linked message types. +// The string is a fully-qualified proto name ("pkg.Message"). +var ( + protoTypes = make(map[string]reflect.Type) + revProtoTypes = make(map[reflect.Type]string) +) + +// RegisterType is called from generated code and maps from the fully qualified +// proto name to the type (pointer to struct) of the protocol buffer. +func RegisterType(x Message, name string) { + if _, ok := protoTypes[name]; ok { + // TODO: Some day, make this a panic. + log.Printf("proto: duplicate proto type registered: %s", name) + return + } + t := reflect.TypeOf(x) + protoTypes[name] = t + revProtoTypes[t] = name +} + +// MessageName returns the fully-qualified proto name for the given message type. +func MessageName(x Message) string { + type xname interface { + XXX_MessageName() string + } + if m, ok := x.(xname); ok { + return m.XXX_MessageName() + } + return revProtoTypes[reflect.TypeOf(x)] +} + +// MessageType returns the message type (pointer to struct) for a named message. +func MessageType(name string) reflect.Type { return protoTypes[name] } + +// A registry of all linked proto files. +var ( + protoFiles = make(map[string][]byte) // file name => fileDescriptor +) + +// RegisterFile is called from generated code and maps from the +// full file name of a .proto file to its compressed FileDescriptorProto. +func RegisterFile(filename string, fileDescriptor []byte) { + protoFiles[filename] = fileDescriptor +} + +// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. +func FileDescriptor(filename string) []byte { return protoFiles[filename] } diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/text.go b/metricbeat/vendor/github.com/golang/protobuf/proto/text.go new file mode 100644 index 00000000000..965876bf033 --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/text.go @@ -0,0 +1,854 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +// Functions for writing the text protocol buffer format. + +import ( + "bufio" + "bytes" + "encoding" + "errors" + "fmt" + "io" + "log" + "math" + "reflect" + "sort" + "strings" +) + +var ( + newline = []byte("\n") + spaces = []byte(" ") + gtNewline = []byte(">\n") + endBraceNewline = []byte("}\n") + backslashN = []byte{'\\', 'n'} + backslashR = []byte{'\\', 'r'} + backslashT = []byte{'\\', 't'} + backslashDQ = []byte{'\\', '"'} + backslashBS = []byte{'\\', '\\'} + posInf = []byte("inf") + negInf = []byte("-inf") + nan = []byte("nan") +) + +type writer interface { + io.Writer + WriteByte(byte) error +} + +// textWriter is an io.Writer that tracks its indentation level. +type textWriter struct { + ind int + complete bool // if the current position is a complete line + compact bool // whether to write out as a one-liner + w writer +} + +func (w *textWriter) WriteString(s string) (n int, err error) { + if !strings.Contains(s, "\n") { + if !w.compact && w.complete { + w.writeIndent() + } + w.complete = false + return io.WriteString(w.w, s) + } + // WriteString is typically called without newlines, so this + // codepath and its copy are rare. We copy to avoid + // duplicating all of Write's logic here. + return w.Write([]byte(s)) +} + +func (w *textWriter) Write(p []byte) (n int, err error) { + newlines := bytes.Count(p, newline) + if newlines == 0 { + if !w.compact && w.complete { + w.writeIndent() + } + n, err = w.w.Write(p) + w.complete = false + return n, err + } + + frags := bytes.SplitN(p, newline, newlines+1) + if w.compact { + for i, frag := range frags { + if i > 0 { + if err := w.w.WriteByte(' '); err != nil { + return n, err + } + n++ + } + nn, err := w.w.Write(frag) + n += nn + if err != nil { + return n, err + } + } + return n, nil + } + + for i, frag := range frags { + if w.complete { + w.writeIndent() + } + nn, err := w.w.Write(frag) + n += nn + if err != nil { + return n, err + } + if i+1 < len(frags) { + if err := w.w.WriteByte('\n'); err != nil { + return n, err + } + n++ + } + } + w.complete = len(frags[len(frags)-1]) == 0 + return n, nil +} + +func (w *textWriter) WriteByte(c byte) error { + if w.compact && c == '\n' { + c = ' ' + } + if !w.compact && w.complete { + w.writeIndent() + } + err := w.w.WriteByte(c) + w.complete = c == '\n' + return err +} + +func (w *textWriter) indent() { w.ind++ } + +func (w *textWriter) unindent() { + if w.ind == 0 { + log.Print("proto: textWriter unindented too far") + return + } + w.ind-- +} + +func writeName(w *textWriter, props *Properties) error { + if _, err := w.WriteString(props.OrigName); err != nil { + return err + } + if props.Wire != "group" { + return w.WriteByte(':') + } + return nil +} + +// raw is the interface satisfied by RawMessage. +type raw interface { + Bytes() []byte +} + +func requiresQuotes(u string) bool { + // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. + for _, ch := range u { + switch { + case ch == '.' || ch == '/' || ch == '_': + continue + case '0' <= ch && ch <= '9': + continue + case 'A' <= ch && ch <= 'Z': + continue + case 'a' <= ch && ch <= 'z': + continue + default: + return true + } + } + return false +} + +// isAny reports whether sv is a google.protobuf.Any message +func isAny(sv reflect.Value) bool { + type wkt interface { + XXX_WellKnownType() string + } + t, ok := sv.Addr().Interface().(wkt) + return ok && t.XXX_WellKnownType() == "Any" +} + +// writeProto3Any writes an expanded google.protobuf.Any message. +// +// It returns (false, nil) if sv value can't be unmarshaled (e.g. because +// required messages are not linked in). +// +// It returns (true, error) when sv was written in expanded format or an error +// was encountered. +func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { + turl := sv.FieldByName("TypeUrl") + val := sv.FieldByName("Value") + if !turl.IsValid() || !val.IsValid() { + return true, errors.New("proto: invalid google.protobuf.Any message") + } + + b, ok := val.Interface().([]byte) + if !ok { + return true, errors.New("proto: invalid google.protobuf.Any message") + } + + parts := strings.Split(turl.String(), "/") + mt := MessageType(parts[len(parts)-1]) + if mt == nil { + return false, nil + } + m := reflect.New(mt.Elem()) + if err := Unmarshal(b, m.Interface().(Message)); err != nil { + return false, nil + } + w.Write([]byte("[")) + u := turl.String() + if requiresQuotes(u) { + writeString(w, u) + } else { + w.Write([]byte(u)) + } + if w.compact { + w.Write([]byte("]:<")) + } else { + w.Write([]byte("]: <\n")) + w.ind++ + } + if err := tm.writeStruct(w, m.Elem()); err != nil { + return true, err + } + if w.compact { + w.Write([]byte("> ")) + } else { + w.ind-- + w.Write([]byte(">\n")) + } + return true, nil +} + +func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { + if tm.ExpandAny && isAny(sv) { + if canExpand, err := tm.writeProto3Any(w, sv); canExpand { + return err + } + } + st := sv.Type() + sprops := GetProperties(st) + for i := 0; i < sv.NumField(); i++ { + fv := sv.Field(i) + props := sprops.Prop[i] + name := st.Field(i).Name + + if strings.HasPrefix(name, "XXX_") { + // There are two XXX_ fields: + // XXX_unrecognized []byte + // XXX_extensions map[int32]proto.Extension + // The first is handled here; + // the second is handled at the bottom of this function. + if name == "XXX_unrecognized" && !fv.IsNil() { + if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { + return err + } + } + continue + } + if fv.Kind() == reflect.Ptr && fv.IsNil() { + // Field not filled in. This could be an optional field or + // a required field that wasn't filled in. Either way, there + // isn't anything we can show for it. + continue + } + if fv.Kind() == reflect.Slice && fv.IsNil() { + // Repeated field that is empty, or a bytes field that is unused. + continue + } + + if props.Repeated && fv.Kind() == reflect.Slice { + // Repeated field. + for j := 0; j < fv.Len(); j++ { + if err := writeName(w, props); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + v := fv.Index(j) + if v.Kind() == reflect.Ptr && v.IsNil() { + // A nil message in a repeated field is not valid, + // but we can handle that more gracefully than panicking. + if _, err := w.Write([]byte("\n")); err != nil { + return err + } + continue + } + if err := tm.writeAny(w, v, props); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + continue + } + if fv.Kind() == reflect.Map { + // Map fields are rendered as a repeated struct with key/value fields. + keys := fv.MapKeys() + sort.Sort(mapKeys(keys)) + for _, key := range keys { + val := fv.MapIndex(key) + if err := writeName(w, props); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + // open struct + if err := w.WriteByte('<'); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte('\n'); err != nil { + return err + } + } + w.indent() + // key + if _, err := w.WriteString("key:"); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := tm.writeAny(w, key, props.mkeyprop); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + // nil values aren't legal, but we can avoid panicking because of them. + if val.Kind() != reflect.Ptr || !val.IsNil() { + // value + if _, err := w.WriteString("value:"); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := tm.writeAny(w, val, props.mvalprop); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + // close struct + w.unindent() + if err := w.WriteByte('>'); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + } + continue + } + if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { + // empty bytes field + continue + } + if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { + // proto3 non-repeated scalar field; skip if zero value + if isProto3Zero(fv) { + continue + } + } + + if fv.Kind() == reflect.Interface { + // Check if it is a oneof. + if st.Field(i).Tag.Get("protobuf_oneof") != "" { + // fv is nil, or holds a pointer to generated struct. + // That generated struct has exactly one field, + // which has a protobuf struct tag. + if fv.IsNil() { + continue + } + inner := fv.Elem().Elem() // interface -> *T -> T + tag := inner.Type().Field(0).Tag.Get("protobuf") + props = new(Properties) // Overwrite the outer props var, but not its pointee. + props.Parse(tag) + // Write the value in the oneof, not the oneof itself. + fv = inner.Field(0) + + // Special case to cope with malformed messages gracefully: + // If the value in the oneof is a nil pointer, don't panic + // in writeAny. + if fv.Kind() == reflect.Ptr && fv.IsNil() { + // Use errors.New so writeAny won't render quotes. + msg := errors.New("/* nil */") + fv = reflect.ValueOf(&msg).Elem() + } + } + } + + if err := writeName(w, props); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if b, ok := fv.Interface().(raw); ok { + if err := writeRaw(w, b.Bytes()); err != nil { + return err + } + continue + } + + // Enums have a String method, so writeAny will work fine. + if err := tm.writeAny(w, fv, props); err != nil { + return err + } + + if err := w.WriteByte('\n'); err != nil { + return err + } + } + + // Extensions (the XXX_extensions field). + pv := sv.Addr() + if _, ok := extendable(pv.Interface()); ok { + if err := tm.writeExtensions(w, pv); err != nil { + return err + } + } + + return nil +} + +// writeRaw writes an uninterpreted raw message. +func writeRaw(w *textWriter, b []byte) error { + if err := w.WriteByte('<'); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte('\n'); err != nil { + return err + } + } + w.indent() + if err := writeUnknownStruct(w, b); err != nil { + return err + } + w.unindent() + if err := w.WriteByte('>'); err != nil { + return err + } + return nil +} + +// writeAny writes an arbitrary field. +func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { + v = reflect.Indirect(v) + + // Floats have special cases. + if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { + x := v.Float() + var b []byte + switch { + case math.IsInf(x, 1): + b = posInf + case math.IsInf(x, -1): + b = negInf + case math.IsNaN(x): + b = nan + } + if b != nil { + _, err := w.Write(b) + return err + } + // Other values are handled below. + } + + // We don't attempt to serialise every possible value type; only those + // that can occur in protocol buffers. + switch v.Kind() { + case reflect.Slice: + // Should only be a []byte; repeated fields are handled in writeStruct. + if err := writeString(w, string(v.Bytes())); err != nil { + return err + } + case reflect.String: + if err := writeString(w, v.String()); err != nil { + return err + } + case reflect.Struct: + // Required/optional group/message. + var bra, ket byte = '<', '>' + if props != nil && props.Wire == "group" { + bra, ket = '{', '}' + } + if err := w.WriteByte(bra); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte('\n'); err != nil { + return err + } + } + w.indent() + if etm, ok := v.Interface().(encoding.TextMarshaler); ok { + text, err := etm.MarshalText() + if err != nil { + return err + } + if _, err = w.Write(text); err != nil { + return err + } + } else if err := tm.writeStruct(w, v); err != nil { + return err + } + w.unindent() + if err := w.WriteByte(ket); err != nil { + return err + } + default: + _, err := fmt.Fprint(w, v.Interface()) + return err + } + return nil +} + +// equivalent to C's isprint. +func isprint(c byte) bool { + return c >= 0x20 && c < 0x7f +} + +// writeString writes a string in the protocol buffer text format. +// It is similar to strconv.Quote except we don't use Go escape sequences, +// we treat the string as a byte sequence, and we use octal escapes. +// These differences are to maintain interoperability with the other +// languages' implementations of the text format. +func writeString(w *textWriter, s string) error { + // use WriteByte here to get any needed indent + if err := w.WriteByte('"'); err != nil { + return err + } + // Loop over the bytes, not the runes. + for i := 0; i < len(s); i++ { + var err error + // Divergence from C++: we don't escape apostrophes. + // There's no need to escape them, and the C++ parser + // copes with a naked apostrophe. + switch c := s[i]; c { + case '\n': + _, err = w.w.Write(backslashN) + case '\r': + _, err = w.w.Write(backslashR) + case '\t': + _, err = w.w.Write(backslashT) + case '"': + _, err = w.w.Write(backslashDQ) + case '\\': + _, err = w.w.Write(backslashBS) + default: + if isprint(c) { + err = w.w.WriteByte(c) + } else { + _, err = fmt.Fprintf(w.w, "\\%03o", c) + } + } + if err != nil { + return err + } + } + return w.WriteByte('"') +} + +func writeUnknownStruct(w *textWriter, data []byte) (err error) { + if !w.compact { + if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { + return err + } + } + b := NewBuffer(data) + for b.index < len(b.buf) { + x, err := b.DecodeVarint() + if err != nil { + _, err := fmt.Fprintf(w, "/* %v */\n", err) + return err + } + wire, tag := x&7, x>>3 + if wire == WireEndGroup { + w.unindent() + if _, err := w.Write(endBraceNewline); err != nil { + return err + } + continue + } + if _, err := fmt.Fprint(w, tag); err != nil { + return err + } + if wire != WireStartGroup { + if err := w.WriteByte(':'); err != nil { + return err + } + } + if !w.compact || wire == WireStartGroup { + if err := w.WriteByte(' '); err != nil { + return err + } + } + switch wire { + case WireBytes: + buf, e := b.DecodeRawBytes(false) + if e == nil { + _, err = fmt.Fprintf(w, "%q", buf) + } else { + _, err = fmt.Fprintf(w, "/* %v */", e) + } + case WireFixed32: + x, err = b.DecodeFixed32() + err = writeUnknownInt(w, x, err) + case WireFixed64: + x, err = b.DecodeFixed64() + err = writeUnknownInt(w, x, err) + case WireStartGroup: + err = w.WriteByte('{') + w.indent() + case WireVarint: + x, err = b.DecodeVarint() + err = writeUnknownInt(w, x, err) + default: + _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) + } + if err != nil { + return err + } + if err = w.WriteByte('\n'); err != nil { + return err + } + } + return nil +} + +func writeUnknownInt(w *textWriter, x uint64, err error) error { + if err == nil { + _, err = fmt.Fprint(w, x) + } else { + _, err = fmt.Fprintf(w, "/* %v */", err) + } + return err +} + +type int32Slice []int32 + +func (s int32Slice) Len() int { return len(s) } +func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } +func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +// writeExtensions writes all the extensions in pv. +// pv is assumed to be a pointer to a protocol message struct that is extendable. +func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { + emap := extensionMaps[pv.Type().Elem()] + ep, _ := extendable(pv.Interface()) + + // Order the extensions by ID. + // This isn't strictly necessary, but it will give us + // canonical output, which will also make testing easier. + m, mu := ep.extensionsRead() + if m == nil { + return nil + } + mu.Lock() + ids := make([]int32, 0, len(m)) + for id := range m { + ids = append(ids, id) + } + sort.Sort(int32Slice(ids)) + mu.Unlock() + + for _, extNum := range ids { + ext := m[extNum] + var desc *ExtensionDesc + if emap != nil { + desc = emap[extNum] + } + if desc == nil { + // Unknown extension. + if err := writeUnknownStruct(w, ext.enc); err != nil { + return err + } + continue + } + + pb, err := GetExtension(ep, desc) + if err != nil { + return fmt.Errorf("failed getting extension: %v", err) + } + + // Repeated extensions will appear as a slice. + if !desc.repeated() { + if err := tm.writeExtension(w, desc.Name, pb); err != nil { + return err + } + } else { + v := reflect.ValueOf(pb) + for i := 0; i < v.Len(); i++ { + if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { + return err + } + } + } + } + return nil +} + +func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { + if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { + return err + } + if !w.compact { + if err := w.WriteByte(' '); err != nil { + return err + } + } + if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { + return err + } + if err := w.WriteByte('\n'); err != nil { + return err + } + return nil +} + +func (w *textWriter) writeIndent() { + if !w.complete { + return + } + remain := w.ind * 2 + for remain > 0 { + n := remain + if n > len(spaces) { + n = len(spaces) + } + w.w.Write(spaces[:n]) + remain -= n + } + w.complete = false +} + +// TextMarshaler is a configurable text format marshaler. +type TextMarshaler struct { + Compact bool // use compact text format (one line). + ExpandAny bool // expand google.protobuf.Any messages of known types +} + +// Marshal writes a given protocol buffer in text format. +// The only errors returned are from w. +func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { + val := reflect.ValueOf(pb) + if pb == nil || val.IsNil() { + w.Write([]byte("")) + return nil + } + var bw *bufio.Writer + ww, ok := w.(writer) + if !ok { + bw = bufio.NewWriter(w) + ww = bw + } + aw := &textWriter{ + w: ww, + complete: true, + compact: tm.Compact, + } + + if etm, ok := pb.(encoding.TextMarshaler); ok { + text, err := etm.MarshalText() + if err != nil { + return err + } + if _, err = aw.Write(text); err != nil { + return err + } + if bw != nil { + return bw.Flush() + } + return nil + } + // Dereference the received pointer so we don't have outer < and >. + v := reflect.Indirect(val) + if err := tm.writeStruct(aw, v); err != nil { + return err + } + if bw != nil { + return bw.Flush() + } + return nil +} + +// Text is the same as Marshal, but returns the string directly. +func (tm *TextMarshaler) Text(pb Message) string { + var buf bytes.Buffer + tm.Marshal(&buf, pb) + return buf.String() +} + +var ( + defaultTextMarshaler = TextMarshaler{} + compactTextMarshaler = TextMarshaler{Compact: true} +) + +// TODO: consider removing some of the Marshal functions below. + +// MarshalText writes a given protocol buffer in text format. +// The only errors returned are from w. +func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } + +// MarshalTextString is the same as MarshalText, but returns the string directly. +func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } + +// CompactText writes a given protocol buffer in compact text format (one line). +func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } + +// CompactTextString is the same as CompactText, but returns the string directly. +func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/metricbeat/vendor/github.com/golang/protobuf/proto/text_parser.go b/metricbeat/vendor/github.com/golang/protobuf/proto/text_parser.go new file mode 100644 index 00000000000..61f83c1e10f --- /dev/null +++ b/metricbeat/vendor/github.com/golang/protobuf/proto/text_parser.go @@ -0,0 +1,895 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2010 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package proto + +// Functions for parsing the Text protocol buffer format. +// TODO: message sets. + +import ( + "encoding" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "unicode/utf8" +) + +// Error string emitted when deserializing Any and fields are already set +const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" + +type ParseError struct { + Message string + Line int // 1-based line number + Offset int // 0-based byte offset from start of input +} + +func (p *ParseError) Error() string { + if p.Line == 1 { + // show offset only for first line + return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) + } + return fmt.Sprintf("line %d: %v", p.Line, p.Message) +} + +type token struct { + value string + err *ParseError + line int // line number + offset int // byte number from start of input, not start of line + unquoted string // the unquoted version of value, if it was a quoted string +} + +func (t *token) String() string { + if t.err == nil { + return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) + } + return fmt.Sprintf("parse error: %v", t.err) +} + +type textParser struct { + s string // remaining input + done bool // whether the parsing is finished (success or error) + backed bool // whether back() was called + offset, line int + cur token +} + +func newTextParser(s string) *textParser { + p := new(textParser) + p.s = s + p.line = 1 + p.cur.line = 1 + return p +} + +func (p *textParser) errorf(format string, a ...interface{}) *ParseError { + pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} + p.cur.err = pe + p.done = true + return pe +} + +// Numbers and identifiers are matched by [-+._A-Za-z0-9] +func isIdentOrNumberChar(c byte) bool { + switch { + case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': + return true + case '0' <= c && c <= '9': + return true + } + switch c { + case '-', '+', '.', '_': + return true + } + return false +} + +func isWhitespace(c byte) bool { + switch c { + case ' ', '\t', '\n', '\r': + return true + } + return false +} + +func isQuote(c byte) bool { + switch c { + case '"', '\'': + return true + } + return false +} + +func (p *textParser) skipWhitespace() { + i := 0 + for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { + if p.s[i] == '#' { + // comment; skip to end of line or input + for i < len(p.s) && p.s[i] != '\n' { + i++ + } + if i == len(p.s) { + break + } + } + if p.s[i] == '\n' { + p.line++ + } + i++ + } + p.offset += i + p.s = p.s[i:len(p.s)] + if len(p.s) == 0 { + p.done = true + } +} + +func (p *textParser) advance() { + // Skip whitespace + p.skipWhitespace() + if p.done { + return + } + + // Start of non-whitespace + p.cur.err = nil + p.cur.offset, p.cur.line = p.offset, p.line + p.cur.unquoted = "" + switch p.s[0] { + case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': + // Single symbol + p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] + case '"', '\'': + // Quoted string + i := 1 + for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { + if p.s[i] == '\\' && i+1 < len(p.s) { + // skip escaped char + i++ + } + i++ + } + if i >= len(p.s) || p.s[i] != p.s[0] { + p.errorf("unmatched quote") + return + } + unq, err := unquoteC(p.s[1:i], rune(p.s[0])) + if err != nil { + p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) + return + } + p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] + p.cur.unquoted = unq + default: + i := 0 + for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { + i++ + } + if i == 0 { + p.errorf("unexpected byte %#x", p.s[0]) + return + } + p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] + } + p.offset += len(p.cur.value) +} + +var ( + errBadUTF8 = errors.New("proto: bad UTF-8") + errBadHex = errors.New("proto: bad hexadecimal") +) + +func unquoteC(s string, quote rune) (string, error) { + // This is based on C++'s tokenizer.cc. + // Despite its name, this is *not* parsing C syntax. + // For instance, "\0" is an invalid quoted string. + + // Avoid allocation in trivial cases. + simple := true + for _, r := range s { + if r == '\\' || r == quote { + simple = false + break + } + } + if simple { + return s, nil + } + + buf := make([]byte, 0, 3*len(s)/2) + for len(s) > 0 { + r, n := utf8.DecodeRuneInString(s) + if r == utf8.RuneError && n == 1 { + return "", errBadUTF8 + } + s = s[n:] + if r != '\\' { + if r < utf8.RuneSelf { + buf = append(buf, byte(r)) + } else { + buf = append(buf, string(r)...) + } + continue + } + + ch, tail, err := unescape(s) + if err != nil { + return "", err + } + buf = append(buf, ch...) + s = tail + } + return string(buf), nil +} + +func unescape(s string) (ch string, tail string, err error) { + r, n := utf8.DecodeRuneInString(s) + if r == utf8.RuneError && n == 1 { + return "", "", errBadUTF8 + } + s = s[n:] + switch r { + case 'a': + return "\a", s, nil + case 'b': + return "\b", s, nil + case 'f': + return "\f", s, nil + case 'n': + return "\n", s, nil + case 'r': + return "\r", s, nil + case 't': + return "\t", s, nil + case 'v': + return "\v", s, nil + case '?': + return "?", s, nil // trigraph workaround + case '\'', '"', '\\': + return string(r), s, nil + case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X': + if len(s) < 2 { + return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) + } + base := 8 + ss := s[:2] + s = s[2:] + if r == 'x' || r == 'X' { + base = 16 + } else { + ss = string(r) + ss + } + i, err := strconv.ParseUint(ss, base, 8) + if err != nil { + return "", "", err + } + return string([]byte{byte(i)}), s, nil + case 'u', 'U': + n := 4 + if r == 'U' { + n = 8 + } + if len(s) < n { + return "", "", fmt.Errorf(`\%c requires %d digits`, r, n) + } + + bs := make([]byte, n/2) + for i := 0; i < n; i += 2 { + a, ok1 := unhex(s[i]) + b, ok2 := unhex(s[i+1]) + if !ok1 || !ok2 { + return "", "", errBadHex + } + bs[i/2] = a<<4 | b + } + s = s[n:] + return string(bs), s, nil + } + return "", "", fmt.Errorf(`unknown escape \%c`, r) +} + +// Adapted from src/pkg/strconv/quote.go. +func unhex(b byte) (v byte, ok bool) { + switch { + case '0' <= b && b <= '9': + return b - '0', true + case 'a' <= b && b <= 'f': + return b - 'a' + 10, true + case 'A' <= b && b <= 'F': + return b - 'A' + 10, true + } + return 0, false +} + +// Back off the parser by one token. Can only be done between calls to next(). +// It makes the next advance() a no-op. +func (p *textParser) back() { p.backed = true } + +// Advances the parser and returns the new current token. +func (p *textParser) next() *token { + if p.backed || p.done { + p.backed = false + return &p.cur + } + p.advance() + if p.done { + p.cur.value = "" + } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { + // Look for multiple quoted strings separated by whitespace, + // and concatenate them. + cat := p.cur + for { + p.skipWhitespace() + if p.done || !isQuote(p.s[0]) { + break + } + p.advance() + if p.cur.err != nil { + return &p.cur + } + cat.value += " " + p.cur.value + cat.unquoted += p.cur.unquoted + } + p.done = false // parser may have seen EOF, but we want to return cat + p.cur = cat + } + return &p.cur +} + +func (p *textParser) consumeToken(s string) error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != s { + p.back() + return p.errorf("expected %q, found %q", s, tok.value) + } + return nil +} + +// Return a RequiredNotSetError indicating which required field was not set. +func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { + st := sv.Type() + sprops := GetProperties(st) + for i := 0; i < st.NumField(); i++ { + if !isNil(sv.Field(i)) { + continue + } + + props := sprops.Prop[i] + if props.Required { + return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} + } + } + return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen +} + +// Returns the index in the struct for the named field, as well as the parsed tag properties. +func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { + i, ok := sprops.decoderOrigNames[name] + if ok { + return i, sprops.Prop[i], true + } + return -1, nil, false +} + +// Consume a ':' from the input stream (if the next token is a colon), +// returning an error if a colon is needed but not present. +func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != ":" { + // Colon is optional when the field is a group or message. + needColon := true + switch props.Wire { + case "group": + needColon = false + case "bytes": + // A "bytes" field is either a message, a string, or a repeated field; + // those three become *T, *string and []T respectively, so we can check for + // this field being a pointer to a non-string. + if typ.Kind() == reflect.Ptr { + // *T or *string + if typ.Elem().Kind() == reflect.String { + break + } + } else if typ.Kind() == reflect.Slice { + // []T or []*T + if typ.Elem().Kind() != reflect.Ptr { + break + } + } else if typ.Kind() == reflect.String { + // The proto3 exception is for a string field, + // which requires a colon. + break + } + needColon = false + } + if needColon { + return p.errorf("expected ':', found %q", tok.value) + } + p.back() + } + return nil +} + +func (p *textParser) readStruct(sv reflect.Value, terminator string) error { + st := sv.Type() + sprops := GetProperties(st) + reqCount := sprops.reqCount + var reqFieldErr error + fieldSet := make(map[string]bool) + // A struct is a sequence of "name: value", terminated by one of + // '>' or '}', or the end of the input. A name may also be + // "[extension]" or "[type/url]". + // + // The whole struct can also be an expanded Any message, like: + // [type/url] < ... struct contents ... > + for { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == terminator { + break + } + if tok.value == "[" { + // Looks like an extension or an Any. + // + // TODO: Check whether we need to handle + // namespace rooted names (e.g. ".something.Foo"). + extName, err := p.consumeExtName() + if err != nil { + return err + } + + if s := strings.LastIndex(extName, "/"); s >= 0 { + // If it contains a slash, it's an Any type URL. + messageName := extName[s+1:] + mt := MessageType(messageName) + if mt == nil { + return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) + } + tok = p.next() + if tok.err != nil { + return tok.err + } + // consume an optional colon + if tok.value == ":" { + tok = p.next() + if tok.err != nil { + return tok.err + } + } + var terminator string + switch tok.value { + case "<": + terminator = ">" + case "{": + terminator = "}" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + v := reflect.New(mt.Elem()) + if pe := p.readStruct(v.Elem(), terminator); pe != nil { + return pe + } + b, err := Marshal(v.Interface().(Message)) + if err != nil { + return p.errorf("failed to marshal message of type %q: %v", messageName, err) + } + if fieldSet["type_url"] { + return p.errorf(anyRepeatedlyUnpacked, "type_url") + } + if fieldSet["value"] { + return p.errorf(anyRepeatedlyUnpacked, "value") + } + sv.FieldByName("TypeUrl").SetString(extName) + sv.FieldByName("Value").SetBytes(b) + fieldSet["type_url"] = true + fieldSet["value"] = true + continue + } + + var desc *ExtensionDesc + // This could be faster, but it's functional. + // TODO: Do something smarter than a linear scan. + for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { + if d.Name == extName { + desc = d + break + } + } + if desc == nil { + return p.errorf("unrecognized extension %q", extName) + } + + props := &Properties{} + props.Parse(desc.Tag) + + typ := reflect.TypeOf(desc.ExtensionType) + if err := p.checkForColon(props, typ); err != nil { + return err + } + + rep := desc.repeated() + + // Read the extension structure, and set it in + // the value we're constructing. + var ext reflect.Value + if !rep { + ext = reflect.New(typ).Elem() + } else { + ext = reflect.New(typ.Elem()).Elem() + } + if err := p.readAny(ext, props); err != nil { + if _, ok := err.(*RequiredNotSetError); !ok { + return err + } + reqFieldErr = err + } + ep := sv.Addr().Interface().(Message) + if !rep { + SetExtension(ep, desc, ext.Interface()) + } else { + old, err := GetExtension(ep, desc) + var sl reflect.Value + if err == nil { + sl = reflect.ValueOf(old) // existing slice + } else { + sl = reflect.MakeSlice(typ, 0, 1) + } + sl = reflect.Append(sl, ext) + SetExtension(ep, desc, sl.Interface()) + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + continue + } + + // This is a normal, non-extension field. + name := tok.value + var dst reflect.Value + fi, props, ok := structFieldByName(sprops, name) + if ok { + dst = sv.Field(fi) + } else if oop, ok := sprops.OneofTypes[name]; ok { + // It is a oneof. + props = oop.Prop + nv := reflect.New(oop.Type.Elem()) + dst = nv.Elem().Field(0) + field := sv.Field(oop.Field) + if !field.IsNil() { + return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) + } + field.Set(nv) + } + if !dst.IsValid() { + return p.errorf("unknown field name %q in %v", name, st) + } + + if dst.Kind() == reflect.Map { + // Consume any colon. + if err := p.checkForColon(props, dst.Type()); err != nil { + return err + } + + // Construct the map if it doesn't already exist. + if dst.IsNil() { + dst.Set(reflect.MakeMap(dst.Type())) + } + key := reflect.New(dst.Type().Key()).Elem() + val := reflect.New(dst.Type().Elem()).Elem() + + // The map entry should be this sequence of tokens: + // < key : KEY value : VALUE > + // However, implementations may omit key or value, and technically + // we should support them in any order. See b/28924776 for a time + // this went wrong. + + tok := p.next() + var terminator string + switch tok.value { + case "<": + terminator = ">" + case "{": + terminator = "}" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + for { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == terminator { + break + } + switch tok.value { + case "key": + if err := p.consumeToken(":"); err != nil { + return err + } + if err := p.readAny(key, props.mkeyprop); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + case "value": + if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { + return err + } + if err := p.readAny(val, props.mvalprop); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + default: + p.back() + return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) + } + } + + dst.SetMapIndex(key, val) + continue + } + + // Check that it's not already set if it's not a repeated field. + if !props.Repeated && fieldSet[name] { + return p.errorf("non-repeated field %q was repeated", name) + } + + if err := p.checkForColon(props, dst.Type()); err != nil { + return err + } + + // Parse into the field. + fieldSet[name] = true + if err := p.readAny(dst, props); err != nil { + if _, ok := err.(*RequiredNotSetError); !ok { + return err + } + reqFieldErr = err + } + if props.Required { + reqCount-- + } + + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + + } + + if reqCount > 0 { + return p.missingRequiredFieldError(sv) + } + return reqFieldErr +} + +// consumeExtName consumes extension name or expanded Any type URL and the +// following ']'. It returns the name or URL consumed. +func (p *textParser) consumeExtName() (string, error) { + tok := p.next() + if tok.err != nil { + return "", tok.err + } + + // If extension name or type url is quoted, it's a single token. + if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { + name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) + if err != nil { + return "", err + } + return name, p.consumeToken("]") + } + + // Consume everything up to "]" + var parts []string + for tok.value != "]" { + parts = append(parts, tok.value) + tok = p.next() + if tok.err != nil { + return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) + } + } + return strings.Join(parts, ""), nil +} + +// consumeOptionalSeparator consumes an optional semicolon or comma. +// It is used in readStruct to provide backward compatibility. +func (p *textParser) consumeOptionalSeparator() error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != ";" && tok.value != "," { + p.back() + } + return nil +} + +func (p *textParser) readAny(v reflect.Value, props *Properties) error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == "" { + return p.errorf("unexpected EOF") + } + + switch fv := v; fv.Kind() { + case reflect.Slice: + at := v.Type() + if at.Elem().Kind() == reflect.Uint8 { + // Special case for []byte + if tok.value[0] != '"' && tok.value[0] != '\'' { + // Deliberately written out here, as the error after + // this switch statement would write "invalid []byte: ...", + // which is not as user-friendly. + return p.errorf("invalid string: %v", tok.value) + } + bytes := []byte(tok.unquoted) + fv.Set(reflect.ValueOf(bytes)) + return nil + } + // Repeated field. + if tok.value == "[" { + // Repeated field with list notation, like [1,2,3]. + for { + fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) + err := p.readAny(fv.Index(fv.Len()-1), props) + if err != nil { + return err + } + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == "]" { + break + } + if tok.value != "," { + return p.errorf("Expected ']' or ',' found %q", tok.value) + } + } + return nil + } + // One value of the repeated field. + p.back() + fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) + return p.readAny(fv.Index(fv.Len()-1), props) + case reflect.Bool: + // true/1/t/True or false/f/0/False. + switch tok.value { + case "true", "1", "t", "True": + fv.SetBool(true) + return nil + case "false", "0", "f", "False": + fv.SetBool(false) + return nil + } + case reflect.Float32, reflect.Float64: + v := tok.value + // Ignore 'f' for compatibility with output generated by C++, but don't + // remove 'f' when the value is "-inf" or "inf". + if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { + v = v[:len(v)-1] + } + if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { + fv.SetFloat(f) + return nil + } + case reflect.Int32: + if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { + fv.SetInt(x) + return nil + } + + if len(props.Enum) == 0 { + break + } + m, ok := enumValueMaps[props.Enum] + if !ok { + break + } + x, ok := m[tok.value] + if !ok { + break + } + fv.SetInt(int64(x)) + return nil + case reflect.Int64: + if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { + fv.SetInt(x) + return nil + } + + case reflect.Ptr: + // A basic field (indirected through pointer), or a repeated message/group + p.back() + fv.Set(reflect.New(fv.Type().Elem())) + return p.readAny(fv.Elem(), props) + case reflect.String: + if tok.value[0] == '"' || tok.value[0] == '\'' { + fv.SetString(tok.unquoted) + return nil + } + case reflect.Struct: + var terminator string + switch tok.value { + case "{": + terminator = "}" + case "<": + terminator = ">" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + // TODO: Handle nested messages which implement encoding.TextUnmarshaler. + return p.readStruct(fv, terminator) + case reflect.Uint32: + if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { + fv.SetUint(uint64(x)) + return nil + } + case reflect.Uint64: + if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { + fv.SetUint(x) + return nil + } + } + return p.errorf("invalid %v: %v", v.Type(), tok.value) +} + +// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb +// before starting to unmarshal, so any existing data in pb is always removed. +// If a required field is not set and no other error occurs, +// UnmarshalText returns *RequiredNotSetError. +func UnmarshalText(s string, pb Message) error { + if um, ok := pb.(encoding.TextUnmarshaler); ok { + err := um.UnmarshalText([]byte(s)) + return err + } + pb.Reset() + v := reflect.ValueOf(pb) + if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil { + return pe + } + return nil +} diff --git a/metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE b/metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE rename to metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE diff --git a/metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE b/metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE rename to metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE diff --git a/metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile b/metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile rename to metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/Makefile diff --git a/metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go b/metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go rename to metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go diff --git a/metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go b/metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go rename to metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go diff --git a/metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go b/metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go rename to metricbeat/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/client_model/LICENSE b/metricbeat/vendor/github.com/prometheus/client_model/LICENSE similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/client_model/LICENSE rename to metricbeat/vendor/github.com/prometheus/client_model/LICENSE diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/client_model/NOTICE b/metricbeat/vendor/github.com/prometheus/client_model/NOTICE similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/client_model/NOTICE rename to metricbeat/vendor/github.com/prometheus/client_model/NOTICE diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/client_model/go/metrics.pb.go b/metricbeat/vendor/github.com/prometheus/client_model/go/metrics.pb.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/client_model/go/metrics.pb.go rename to metricbeat/vendor/github.com/prometheus/client_model/go/metrics.pb.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/LICENSE b/metricbeat/vendor/github.com/prometheus/common/LICENSE similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/LICENSE rename to metricbeat/vendor/github.com/prometheus/common/LICENSE diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/NOTICE b/metricbeat/vendor/github.com/prometheus/common/NOTICE similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/NOTICE rename to metricbeat/vendor/github.com/prometheus/common/NOTICE diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/decode.go b/metricbeat/vendor/github.com/prometheus/common/expfmt/decode.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/decode.go rename to metricbeat/vendor/github.com/prometheus/common/expfmt/decode.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/encode.go b/metricbeat/vendor/github.com/prometheus/common/expfmt/encode.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/encode.go rename to metricbeat/vendor/github.com/prometheus/common/expfmt/encode.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/expfmt.go b/metricbeat/vendor/github.com/prometheus/common/expfmt/expfmt.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/expfmt.go rename to metricbeat/vendor/github.com/prometheus/common/expfmt/expfmt.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/fuzz.go b/metricbeat/vendor/github.com/prometheus/common/expfmt/fuzz.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/fuzz.go rename to metricbeat/vendor/github.com/prometheus/common/expfmt/fuzz.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/text_create.go b/metricbeat/vendor/github.com/prometheus/common/expfmt/text_create.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/text_create.go rename to metricbeat/vendor/github.com/prometheus/common/expfmt/text_create.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/text_parse.go b/metricbeat/vendor/github.com/prometheus/common/expfmt/text_parse.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/expfmt/text_parse.go rename to metricbeat/vendor/github.com/prometheus/common/expfmt/text_parse.go diff --git a/metricbeat/module/prometheus/vendor/bitbucket.org/ww/goautoneg/README.txt b/metricbeat/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt similarity index 100% rename from metricbeat/module/prometheus/vendor/bitbucket.org/ww/goautoneg/README.txt rename to metricbeat/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt diff --git a/metricbeat/module/prometheus/vendor/bitbucket.org/ww/goautoneg/autoneg.go b/metricbeat/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go similarity index 100% rename from metricbeat/module/prometheus/vendor/bitbucket.org/ww/goautoneg/autoneg.go rename to metricbeat/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/alert.go b/metricbeat/vendor/github.com/prometheus/common/model/alert.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/alert.go rename to metricbeat/vendor/github.com/prometheus/common/model/alert.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/fingerprinting.go b/metricbeat/vendor/github.com/prometheus/common/model/fingerprinting.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/fingerprinting.go rename to metricbeat/vendor/github.com/prometheus/common/model/fingerprinting.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/fnv.go b/metricbeat/vendor/github.com/prometheus/common/model/fnv.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/fnv.go rename to metricbeat/vendor/github.com/prometheus/common/model/fnv.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/labels.go b/metricbeat/vendor/github.com/prometheus/common/model/labels.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/labels.go rename to metricbeat/vendor/github.com/prometheus/common/model/labels.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/labelset.go b/metricbeat/vendor/github.com/prometheus/common/model/labelset.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/labelset.go rename to metricbeat/vendor/github.com/prometheus/common/model/labelset.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/metric.go b/metricbeat/vendor/github.com/prometheus/common/model/metric.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/metric.go rename to metricbeat/vendor/github.com/prometheus/common/model/metric.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/model.go b/metricbeat/vendor/github.com/prometheus/common/model/model.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/model.go rename to metricbeat/vendor/github.com/prometheus/common/model/model.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/signature.go b/metricbeat/vendor/github.com/prometheus/common/model/signature.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/signature.go rename to metricbeat/vendor/github.com/prometheus/common/model/signature.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/silence.go b/metricbeat/vendor/github.com/prometheus/common/model/silence.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/silence.go rename to metricbeat/vendor/github.com/prometheus/common/model/silence.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/time.go b/metricbeat/vendor/github.com/prometheus/common/model/time.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/time.go rename to metricbeat/vendor/github.com/prometheus/common/model/time.go diff --git a/metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/value.go b/metricbeat/vendor/github.com/prometheus/common/model/value.go similarity index 100% rename from metricbeat/module/prometheus/vendor/github.com/prometheus/common/model/value.go rename to metricbeat/vendor/github.com/prometheus/common/model/value.go diff --git a/metricbeat/module/prometheus/vendor/vendor.json b/metricbeat/vendor/vendor.json similarity index 61% rename from metricbeat/module/prometheus/vendor/vendor.json rename to metricbeat/vendor/vendor.json index c27ec2cf11d..e115f579824 100644 --- a/metricbeat/module/prometheus/vendor/vendor.json +++ b/metricbeat/vendor/vendor.json @@ -3,10 +3,10 @@ "ignore": "test github.com/elastic/beats", "package": [ { - "checksumSHA1": "xFtqcXoLV+TzdA4IgRPb3GMmi3E=", - "path": "bitbucket.org/ww/goautoneg", - "revision": "75cd24fc2f2c", - "revisionTime": "2012-07-07T11:04:53Z" + "checksumSHA1": "kBeNcaKk56FguvPSUCEaH6AxpRc=", + "path": "github.com/golang/protobuf/proto", + "revision": "18c9bb3261723cd5401db4d0c9fbc5c3b6c70fe8", + "revisionTime": "2017-04-27T21:32:20Z" }, { "checksumSHA1": "bKMZjd2wPw13VwoE7mBeSv5djFA=", @@ -23,21 +23,21 @@ { "checksumSHA1": "Wtpzndm/+bdwwNU5PCTfb4oUhc8=", "path": "github.com/prometheus/common/expfmt", - "revision": "9e0844febd9e2856f839c9cb974fbd676d1755a8", - "revisionTime": "2017-04-18T15:52:10Z" + "revision": "13ba4ddd0caa9c28ca7b7bffe1dfa9ed8d5ef207", + "revisionTime": "2017-04-27T09:54:55Z" }, { "checksumSHA1": "GWlM3d2vPYyNATtTFgftS10/A9w=", "path": "github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg", - "revision": "9e0844febd9e2856f839c9cb974fbd676d1755a8", - "revisionTime": "2017-04-18T15:52:10Z" + "revision": "13ba4ddd0caa9c28ca7b7bffe1dfa9ed8d5ef207", + "revisionTime": "2017-04-27T09:54:55Z" }, { "checksumSHA1": "0LL9u9tfv1KPBjNEiMDP6q7lpog=", "path": "github.com/prometheus/common/model", - "revision": "9e0844febd9e2856f839c9cb974fbd676d1755a8", - "revisionTime": "2017-04-18T15:52:10Z" + "revision": "13ba4ddd0caa9c28ca7b7bffe1dfa9ed8d5ef207", + "revisionTime": "2017-04-27T09:54:55Z" } ], - "rootPath": "github.com/elastic/beats/metricbeat/module/prometheus" + "rootPath": "github.com/elastic/beats/metricbeat" } diff --git a/packetbeat/docs/fields.asciidoc b/packetbeat/docs/fields.asciidoc index 5df9c2cd7d4..1783be6ddb1 100644 --- a/packetbeat/docs/fields.asciidoc +++ b/packetbeat/docs/fields.asciidoc @@ -1903,12 +1903,14 @@ type: long The response code. [[exported-fields-kubernetes-processor]] -== Kubernetes info Fields +== kubernetes Fields +beta[] Kubernetes metadata added by the kubernetes processor + [float] === kubernetes.pod.name @@ -1949,6 +1951,14 @@ type: keyword Kubernetes container name +[float] +=== kubernetes.container.image + +type: keyword + +Kubernetes container image + + [[exported-fields-memcache]] == Memcache Fields diff --git a/winlogbeat/docs/fields.asciidoc b/winlogbeat/docs/fields.asciidoc index 08b329e010e..03e35a17065 100644 --- a/winlogbeat/docs/fields.asciidoc +++ b/winlogbeat/docs/fields.asciidoc @@ -429,12 +429,14 @@ The XML representation of the event is useful for troubleshooting purposes. The [[exported-fields-kubernetes-processor]] -== Kubernetes info Fields +== kubernetes Fields +beta[] Kubernetes metadata added by the kubernetes processor + [float] === kubernetes.pod.name @@ -475,3 +477,11 @@ type: keyword Kubernetes container name +[float] +=== kubernetes.container.image + +type: keyword + +Kubernetes container image + +