diff options
Diffstat (limited to 'src/kube2msb/vendor/github.com/google')
10 files changed, 1898 insertions, 0 deletions
diff --git a/src/kube2msb/vendor/github.com/google/cadvisor/LICENSE b/src/kube2msb/vendor/github.com/google/cadvisor/LICENSE new file mode 100644 index 0000000..97cec18 --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/cadvisor/LICENSE @@ -0,0 +1,190 @@ + Copyright 2014 The cAdvisor Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/container.go b/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/container.go new file mode 100644 index 0000000..6e7e658 --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/container.go @@ -0,0 +1,583 @@ +// Copyright 2014 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +import ( + "reflect" + "time" +) + +type CpuSpec struct { + Limit uint64 `json:"limit"` + MaxLimit uint64 `json:"max_limit"` + Mask string `json:"mask,omitempty"` + Quota uint64 `json:"quota,omitempty"` + Period uint64 `json:"period,omitempty"` +} + +type MemorySpec struct { + // The amount of memory requested. Default is unlimited (-1). + // Units: bytes. + Limit uint64 `json:"limit,omitempty"` + + // The amount of guaranteed memory. Default is 0. + // Units: bytes. + Reservation uint64 `json:"reservation,omitempty"` + + // The amount of swap space requested. Default is unlimited (-1). + // Units: bytes. + SwapLimit uint64 `json:"swap_limit,omitempty"` +} + +type ContainerSpec struct { + // Time at which the container was created. + CreationTime time.Time `json:"creation_time,omitempty"` + + // Metadata labels associated with this container. + Labels map[string]string `json:"labels,omitempty"` + // Metadata envs associated with this container. Only whitelisted envs are added. + Envs map[string]string `json:"envs,omitempty"` + + HasCpu bool `json:"has_cpu"` + Cpu CpuSpec `json:"cpu,omitempty"` + + HasMemory bool `json:"has_memory"` + Memory MemorySpec `json:"memory,omitempty"` + + HasNetwork bool `json:"has_network"` + + HasFilesystem bool `json:"has_filesystem"` + + // HasDiskIo when true, indicates that DiskIo stats will be available. + HasDiskIo bool `json:"has_diskio"` + + HasCustomMetrics bool `json:"has_custom_metrics"` + CustomMetrics []MetricSpec `json:"custom_metrics,omitempty"` + + // Image name used for this container. + Image string `json:"image,omitempty"` +} + +// Container reference contains enough information to uniquely identify a container +type ContainerReference struct { + // The container id + Id string `json:"id,omitempty"` + + // The absolute name of the container. This is unique on the machine. + Name string `json:"name"` + + // Other names by which the container is known within a certain namespace. + // This is unique within that namespace. + Aliases []string `json:"aliases,omitempty"` + + // Namespace under which the aliases of a container are unique. + // An example of a namespace is "docker" for Docker containers. + Namespace string `json:"namespace,omitempty"` + + Labels map[string]string `json:"labels,omitempty"` +} + +// Sorts by container name. +type ContainerReferenceSlice []ContainerReference + +func (self ContainerReferenceSlice) Len() int { return len(self) } +func (self ContainerReferenceSlice) Swap(i, j int) { self[i], self[j] = self[j], self[i] } +func (self ContainerReferenceSlice) Less(i, j int) bool { return self[i].Name < self[j].Name } + +// ContainerInfoRequest is used when users check a container info from the REST API. +// It specifies how much data users want to get about a container +type ContainerInfoRequest struct { + // Max number of stats to return. Specify -1 for all stats currently available. + // Default: 60 + NumStats int `json:"num_stats,omitempty"` + + // Start time for which to query information. + // If ommitted, the beginning of time is assumed. + Start time.Time `json:"start,omitempty"` + + // End time for which to query information. + // If ommitted, current time is assumed. + End time.Time `json:"end,omitempty"` +} + +// Returns a ContainerInfoRequest with all default values specified. +func DefaultContainerInfoRequest() ContainerInfoRequest { + return ContainerInfoRequest{ + NumStats: 60, + } +} + +func (self *ContainerInfoRequest) Equals(other ContainerInfoRequest) bool { + return self.NumStats == other.NumStats && + self.Start.Equal(other.Start) && + self.End.Equal(other.End) +} + +type ContainerInfo struct { + ContainerReference + + // The direct subcontainers of the current container. + Subcontainers []ContainerReference `json:"subcontainers,omitempty"` + + // The isolation used in the container. + Spec ContainerSpec `json:"spec,omitempty"` + + // Historical statistics gathered from the container. + Stats []*ContainerStats `json:"stats,omitempty"` +} + +// TODO(vmarmol): Refactor to not need this equality comparison. +// ContainerInfo may be (un)marshaled by json or other en/decoder. In that +// case, the Timestamp field in each stats/sample may not be precisely +// en/decoded. This will lead to small but acceptable differences between a +// ContainerInfo and its encode-then-decode version. Eq() is used to compare +// two ContainerInfo accepting small difference (<10ms) of Time fields. +func (self *ContainerInfo) Eq(b *ContainerInfo) bool { + + // If both self and b are nil, then Eq() returns true + if self == nil { + return b == nil + } + if b == nil { + return self == nil + } + + // For fields other than time.Time, we will compare them precisely. + // This would require that any slice should have same order. + if !reflect.DeepEqual(self.ContainerReference, b.ContainerReference) { + return false + } + if !reflect.DeepEqual(self.Subcontainers, b.Subcontainers) { + return false + } + if !self.Spec.Eq(&b.Spec) { + return false + } + + for i, expectedStats := range b.Stats { + selfStats := self.Stats[i] + if !expectedStats.Eq(selfStats) { + return false + } + } + + return true +} + +func (self *ContainerSpec) Eq(b *ContainerSpec) bool { + // Creation within 1s of each other. + diff := self.CreationTime.Sub(b.CreationTime) + if (diff > time.Second) || (diff < -time.Second) { + return false + } + + if self.HasCpu != b.HasCpu { + return false + } + if !reflect.DeepEqual(self.Cpu, b.Cpu) { + return false + } + if self.HasMemory != b.HasMemory { + return false + } + if !reflect.DeepEqual(self.Memory, b.Memory) { + return false + } + if self.HasNetwork != b.HasNetwork { + return false + } + if self.HasFilesystem != b.HasFilesystem { + return false + } + if self.HasDiskIo != b.HasDiskIo { + return false + } + if self.HasCustomMetrics != b.HasCustomMetrics { + return false + } + return true +} + +func (self *ContainerInfo) StatsAfter(ref time.Time) []*ContainerStats { + n := len(self.Stats) + 1 + for i, s := range self.Stats { + if s.Timestamp.After(ref) { + n = i + break + } + } + if n > len(self.Stats) { + return nil + } + return self.Stats[n:] +} + +func (self *ContainerInfo) StatsStartTime() time.Time { + var ret time.Time + for _, s := range self.Stats { + if s.Timestamp.Before(ret) || ret.IsZero() { + ret = s.Timestamp + } + } + return ret +} + +func (self *ContainerInfo) StatsEndTime() time.Time { + var ret time.Time + for i := len(self.Stats) - 1; i >= 0; i-- { + s := self.Stats[i] + if s.Timestamp.After(ret) { + ret = s.Timestamp + } + } + return ret +} + +// This mirrors kernel internal structure. +type LoadStats struct { + // Number of sleeping tasks. + NrSleeping uint64 `json:"nr_sleeping"` + + // Number of running tasks. + NrRunning uint64 `json:"nr_running"` + + // Number of tasks in stopped state + NrStopped uint64 `json:"nr_stopped"` + + // Number of tasks in uninterruptible state + NrUninterruptible uint64 `json:"nr_uninterruptible"` + + // Number of tasks waiting on IO + NrIoWait uint64 `json:"nr_io_wait"` +} + +// CPU usage time statistics. +type CpuUsage struct { + // Total CPU usage. + // Units: nanoseconds + Total uint64 `json:"total"` + + // Per CPU/core usage of the container. + // Unit: nanoseconds. + PerCpu []uint64 `json:"per_cpu_usage,omitempty"` + + // Time spent in user space. + // Unit: nanoseconds + User uint64 `json:"user"` + + // Time spent in kernel space. + // Unit: nanoseconds + System uint64 `json:"system"` +} + +// All CPU usage metrics are cumulative from the creation of the container +type CpuStats struct { + Usage CpuUsage `json:"usage"` + // Smoothed average of number of runnable threads x 1000. + // We multiply by thousand to avoid using floats, but preserving precision. + // Load is smoothed over the last 10 seconds. Instantaneous value can be read + // from LoadStats.NrRunning. + LoadAverage int32 `json:"load_average"` +} + +type PerDiskStats struct { + Major uint64 `json:"major"` + Minor uint64 `json:"minor"` + Stats map[string]uint64 `json:"stats"` +} + +type DiskIoStats struct { + IoServiceBytes []PerDiskStats `json:"io_service_bytes,omitempty"` + IoServiced []PerDiskStats `json:"io_serviced,omitempty"` + IoQueued []PerDiskStats `json:"io_queued,omitempty"` + Sectors []PerDiskStats `json:"sectors,omitempty"` + IoServiceTime []PerDiskStats `json:"io_service_time,omitempty"` + IoWaitTime []PerDiskStats `json:"io_wait_time,omitempty"` + IoMerged []PerDiskStats `json:"io_merged,omitempty"` + IoTime []PerDiskStats `json:"io_time,omitempty"` +} + +type MemoryStats struct { + // Current memory usage, this includes all memory regardless of when it was + // accessed. + // Units: Bytes. + Usage uint64 `json:"usage"` + + // Number of bytes of page cache memory. + // Units: Bytes. + Cache uint64 `json:"cache"` + + // The amount of anonymous and swap cache memory (includes transparent + // hugepages). + // Units: Bytes. + RSS uint64 `json:"rss"` + + // The amount of working set memory, this includes recently accessed memory, + // dirty memory, and kernel memory. Working set is <= "usage". + // Units: Bytes. + WorkingSet uint64 `json:"working_set"` + + Failcnt uint64 `json:"failcnt"` + + ContainerData MemoryStatsMemoryData `json:"container_data,omitempty"` + HierarchicalData MemoryStatsMemoryData `json:"hierarchical_data,omitempty"` +} + +type MemoryStatsMemoryData struct { + Pgfault uint64 `json:"pgfault"` + Pgmajfault uint64 `json:"pgmajfault"` +} + +type InterfaceStats struct { + // The name of the interface. + Name string `json:"name"` + // Cumulative count of bytes received. + RxBytes uint64 `json:"rx_bytes"` + // Cumulative count of packets received. + RxPackets uint64 `json:"rx_packets"` + // Cumulative count of receive errors encountered. + RxErrors uint64 `json:"rx_errors"` + // Cumulative count of packets dropped while receiving. + RxDropped uint64 `json:"rx_dropped"` + // Cumulative count of bytes transmitted. + TxBytes uint64 `json:"tx_bytes"` + // Cumulative count of packets transmitted. + TxPackets uint64 `json:"tx_packets"` + // Cumulative count of transmit errors encountered. + TxErrors uint64 `json:"tx_errors"` + // Cumulative count of packets dropped while transmitting. + TxDropped uint64 `json:"tx_dropped"` +} + +type NetworkStats struct { + InterfaceStats `json:",inline"` + Interfaces []InterfaceStats `json:"interfaces,omitempty"` + // TCP connection stats (Established, Listen...) + Tcp TcpStat `json:"tcp"` + // TCP6 connection stats (Established, Listen...) + Tcp6 TcpStat `json:"tcp6"` +} + +type TcpStat struct { + //Count of TCP connections in state "Established" + Established uint64 + //Count of TCP connections in state "Syn_Sent" + SynSent uint64 + //Count of TCP connections in state "Syn_Recv" + SynRecv uint64 + //Count of TCP connections in state "Fin_Wait1" + FinWait1 uint64 + //Count of TCP connections in state "Fin_Wait2" + FinWait2 uint64 + //Count of TCP connections in state "Time_Wait + TimeWait uint64 + //Count of TCP connections in state "Close" + Close uint64 + //Count of TCP connections in state "Close_Wait" + CloseWait uint64 + //Count of TCP connections in state "Listen_Ack" + LastAck uint64 + //Count of TCP connections in state "Listen" + Listen uint64 + //Count of TCP connections in state "Closing" + Closing uint64 +} + +type FsStats struct { + // The block device name associated with the filesystem. + Device string `json:"device,omitempty"` + + // Type of the filesytem. + Type string `json:"type"` + + // Number of bytes that can be consumed by the container on this filesystem. + Limit uint64 `json:"capacity"` + + // Number of bytes that is consumed by the container on this filesystem. + Usage uint64 `json:"usage"` + + // Base Usage that is consumed by the container's writable layer. + // This field is only applicable for docker container's as of now. + BaseUsage uint64 `json:"base_usage"` + + // Number of bytes available for non-root user. + Available uint64 `json:"available"` + + // Number of available Inodes + InodesFree uint64 `json:"inodes_free"` + + // Number of reads completed + // This is the total number of reads completed successfully. + ReadsCompleted uint64 `json:"reads_completed"` + + // Number of reads merged + // Reads and writes which are adjacent to each other may be merged for + // efficiency. Thus two 4K reads may become one 8K read before it is + // ultimately handed to the disk, and so it will be counted (and queued) + // as only one I/O. This field lets you know how often this was done. + ReadsMerged uint64 `json:"reads_merged"` + + // Number of sectors read + // This is the total number of sectors read successfully. + SectorsRead uint64 `json:"sectors_read"` + + // Number of milliseconds spent reading + // This is the total number of milliseconds spent by all reads (as + // measured from __make_request() to end_that_request_last()). + ReadTime uint64 `json:"read_time"` + + // Number of writes completed + // This is the total number of writes completed successfully. + WritesCompleted uint64 `json:"writes_completed"` + + // Number of writes merged + // See the description of reads merged. + WritesMerged uint64 `json:"writes_merged"` + + // Number of sectors written + // This is the total number of sectors written successfully. + SectorsWritten uint64 `json:"sectors_written"` + + // Number of milliseconds spent writing + // This is the total number of milliseconds spent by all writes (as + // measured from __make_request() to end_that_request_last()). + WriteTime uint64 `json:"write_time"` + + // Number of I/Os currently in progress + // The only field that should go to zero. Incremented as requests are + // given to appropriate struct request_queue and decremented as they finish. + IoInProgress uint64 `json:"io_in_progress"` + + // Number of milliseconds spent doing I/Os + // This field increases so long as field 9 is nonzero. + IoTime uint64 `json:"io_time"` + + // weighted number of milliseconds spent doing I/Os + // This field is incremented at each I/O start, I/O completion, I/O + // merge, or read of these stats by the number of I/Os in progress + // (field 9) times the number of milliseconds spent doing I/O since the + // last update of this field. This can provide an easy measure of both + // I/O completion time and the backlog that may be accumulating. + WeightedIoTime uint64 `json:"weighted_io_time"` +} + +type ContainerStats struct { + // The time of this stat point. + Timestamp time.Time `json:"timestamp"` + Cpu CpuStats `json:"cpu,omitempty"` + DiskIo DiskIoStats `json:"diskio,omitempty"` + Memory MemoryStats `json:"memory,omitempty"` + Network NetworkStats `json:"network,omitempty"` + + // Filesystem statistics + Filesystem []FsStats `json:"filesystem,omitempty"` + + // Task load stats + TaskStats LoadStats `json:"task_stats,omitempty"` + + //Custom metrics from all collectors + CustomMetrics map[string][]MetricVal `json:"custom_metrics,omitempty"` +} + +func timeEq(t1, t2 time.Time, tolerance time.Duration) bool { + // t1 should not be later than t2 + if t1.After(t2) { + t1, t2 = t2, t1 + } + diff := t2.Sub(t1) + if diff <= tolerance { + return true + } + return false +} + +const ( + // 10ms, i.e. 0.01s + timePrecision time.Duration = 10 * time.Millisecond +) + +// This function is useful because we do not require precise time +// representation. +func (a *ContainerStats) Eq(b *ContainerStats) bool { + if !timeEq(a.Timestamp, b.Timestamp, timePrecision) { + return false + } + return a.StatsEq(b) +} + +// Checks equality of the stats values. +func (a *ContainerStats) StatsEq(b *ContainerStats) bool { + // TODO(vmarmol): Consider using this through reflection. + if !reflect.DeepEqual(a.Cpu, b.Cpu) { + return false + } + if !reflect.DeepEqual(a.Memory, b.Memory) { + return false + } + if !reflect.DeepEqual(a.DiskIo, b.DiskIo) { + return false + } + if !reflect.DeepEqual(a.Network, b.Network) { + return false + } + if !reflect.DeepEqual(a.Filesystem, b.Filesystem) { + return false + } + return true +} + +// Event contains information general to events such as the time at which they +// occurred, their specific type, and the actual event. Event types are +// differentiated by the EventType field of Event. +type Event struct { + // the absolute container name for which the event occurred + ContainerName string `json:"container_name"` + + // the time at which the event occurred + Timestamp time.Time `json:"timestamp"` + + // the type of event. EventType is an enumerated type + EventType EventType `json:"event_type"` + + // the original event object and all of its extraneous data, ex. an + // OomInstance + EventData EventData `json:"event_data,omitempty"` +} + +// EventType is an enumerated type which lists the categories under which +// events may fall. The Event field EventType is populated by this enum. +type EventType string + +const ( + EventOom EventType = "oom" + EventOomKill = "oomKill" + EventContainerCreation = "containerCreation" + EventContainerDeletion = "containerDeletion" +) + +// Extra information about an event. Only one type will be set. +type EventData struct { + // Information about an OOM kill event. + OomKill *OomKillEventData `json:"oom,omitempty"` +} + +// Information related to an OOM kill instance +type OomKillEventData struct { + // process id of the killed process + Pid int `json:"pid"` + + // The name of the killed process + ProcessName string `json:"process_name"` +} diff --git a/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/docker.go b/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/docker.go new file mode 100644 index 0000000..2703c53 --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/docker.go @@ -0,0 +1,37 @@ +// Copyright 2016 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Types used for docker containers. +package v1 + +type DockerStatus struct { + Version string `json:"version"` + KernelVersion string `json:"kernel_version"` + OS string `json:"os"` + Hostname string `json:"hostname"` + RootDir string `json:"root_dir"` + Driver string `json:"driver"` + DriverStatus map[string]string `json:"driver_status"` + ExecDriver string `json:"exec_driver"` + NumImages int `json:"num_images"` + NumContainers int `json:"num_containers"` +} + +type DockerImage struct { + ID string `json:"id"` + RepoTags []string `json:"repo_tags"` // repository name and tags. + Created int64 `json:"created"` // unix time since creation. + VirtualSize int64 `json:"virtual_size"` + Size int64 `json:"size"` +} diff --git a/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/machine.go b/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/machine.go new file mode 100644 index 0000000..74a5df4 --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/machine.go @@ -0,0 +1,205 @@ +// Copyright 2014 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +type FsInfo struct { + // Block device associated with the filesystem. + Device string `json:"device"` + + // Total number of bytes available on the filesystem. + Capacity uint64 `json:"capacity"` + + // Type of device. + Type string `json:"type"` + + // Total number of inodes available on the filesystem. + Inodes uint64 `json:"inodes"` +} + +type Node struct { + Id int `json:"node_id"` + // Per-node memory + Memory uint64 `json:"memory"` + Cores []Core `json:"cores"` + Caches []Cache `json:"caches"` +} + +type Core struct { + Id int `json:"core_id"` + Threads []int `json:"thread_ids"` + Caches []Cache `json:"caches"` +} + +type Cache struct { + // Size of memory cache in bytes. + Size uint64 `json:"size"` + // Type of memory cache: data, instruction, or unified. + Type string `json:"type"` + // Level (distance from cpus) in a multi-level cache hierarchy. + Level int `json:"level"` +} + +func (self *Node) FindCore(id int) (bool, int) { + for i, n := range self.Cores { + if n.Id == id { + return true, i + } + } + return false, -1 +} + +func (self *Node) AddThread(thread int, core int) { + var coreIdx int + if core == -1 { + // Assume one hyperthread per core when topology data is missing. + core = thread + } + ok, coreIdx := self.FindCore(core) + + if !ok { + // New core + core := Core{Id: core} + self.Cores = append(self.Cores, core) + coreIdx = len(self.Cores) - 1 + } + self.Cores[coreIdx].Threads = append(self.Cores[coreIdx].Threads, thread) +} + +func (self *Node) AddNodeCache(c Cache) { + self.Caches = append(self.Caches, c) +} + +func (self *Node) AddPerCoreCache(c Cache) { + for idx := range self.Cores { + self.Cores[idx].Caches = append(self.Cores[idx].Caches, c) + } +} + +type DiskInfo struct { + // device name + Name string `json:"name"` + + // Major number + Major uint64 `json:"major"` + + // Minor number + Minor uint64 `json:"minor"` + + // Size in bytes + Size uint64 `json:"size"` + + // I/O Scheduler - one of "none", "noop", "cfq", "deadline" + Scheduler string `json:"scheduler"` +} + +type NetInfo struct { + // Device name + Name string `json:"name"` + + // Mac Address + MacAddress string `json:"mac_address"` + + // Speed in MBits/s + Speed int64 `json:"speed"` + + // Maximum Transmission Unit + Mtu int64 `json:"mtu"` +} + +type CloudProvider string + +const ( + GCE CloudProvider = "GCE" + AWS = "AWS" + Azure = "Azure" + Baremetal = "Baremetal" + UnknownProvider = "Unknown" +) + +type InstanceType string + +const ( + NoInstance InstanceType = "None" + UnknownInstance = "Unknown" +) + +type InstanceID string + +const ( + UnNamedInstance InstanceID = "None" +) + +type MachineInfo struct { + // The number of cores in this machine. + NumCores int `json:"num_cores"` + + // Maximum clock speed for the cores, in KHz. + CpuFrequency uint64 `json:"cpu_frequency_khz"` + + // The amount of memory (in bytes) in this machine + MemoryCapacity uint64 `json:"memory_capacity"` + + // The machine id + MachineID string `json:"machine_id"` + + // The system uuid + SystemUUID string `json:"system_uuid"` + + // The boot id + BootID string `json:"boot_id"` + + // Filesystems on this machine. + Filesystems []FsInfo `json:"filesystems"` + + // Disk map + DiskMap map[string]DiskInfo `json:"disk_map"` + + // Network devices + NetworkDevices []NetInfo `json:"network_devices"` + + // Machine Topology + // Describes cpu/memory layout and hierarchy. + Topology []Node `json:"topology"` + + // Cloud provider the machine belongs to. + CloudProvider CloudProvider `json:"cloud_provider"` + + // Type of cloud instance (e.g. GCE standard) the machine is. + InstanceType InstanceType `json:"instance_type"` + + // ID of cloud instance (e.g. instance-1) given to it by the cloud provider. + InstanceID InstanceID `json:"instance_id"` +} + +type VersionInfo struct { + // Kernel version. + KernelVersion string `json:"kernel_version"` + + // OS image being used for cadvisor container, or host image if running on host directly. + ContainerOsVersion string `json:"container_os_version"` + + // Docker version. + DockerVersion string `json:"docker_version"` + + // cAdvisor version. + CadvisorVersion string `json:"cadvisor_version"` + // cAdvisor git revision. + CadvisorRevision string `json:"cadvisor_revision"` +} + +type MachineInfoFactory interface { + GetMachineInfo() (*MachineInfo, error) + GetVersionInfo() (*VersionInfo, error) +} diff --git a/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/metric.go b/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/metric.go new file mode 100644 index 0000000..90fd9e4 --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/cadvisor/info/v1/metric.go @@ -0,0 +1,79 @@ +// Copyright 2015 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +import ( + "time" +) + +// Type of metric being exported. +type MetricType string + +const ( + // Instantaneous value. May increase or decrease. + MetricGauge MetricType = "gauge" + + // A counter-like value that is only expected to increase. + MetricCumulative = "cumulative" + + // Rate over a time period. + MetricDelta = "delta" +) + +// DataType for metric being exported. +type DataType string + +const ( + IntType DataType = "int" + FloatType = "float" +) + +// Spec for custom metric. +type MetricSpec struct { + // The name of the metric. + Name string `json:"name"` + + // Type of the metric. + Type MetricType `json:"type"` + + // Data Type for the stats. + Format DataType `json:"format"` + + // Display Units for the stats. + Units string `json:"units"` +} + +// An exported metric. +type MetricValBasic struct { + // Time at which the metric was queried + Timestamp time.Time `json:"timestamp"` + + // The value of the metric at this point. + IntValue int64 `json:"int_value,omitempty"` + FloatValue float64 `json:"float_value,omitempty"` +} + +// An exported metric. +type MetricVal struct { + // Label associated with a metric + Label string `json:"label,omitempty"` + + // Time at which the metric was queried + Timestamp time.Time `json:"timestamp"` + + // The value of the metric at this point. + IntValue int64 `json:"int_value,omitempty"` + FloatValue float64 `json:"float_value,omitempty"` +} diff --git a/src/kube2msb/vendor/github.com/google/gofuzz/CONTRIBUTING.md b/src/kube2msb/vendor/github.com/google/gofuzz/CONTRIBUTING.md new file mode 100644 index 0000000..51cf5cd --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/gofuzz/CONTRIBUTING.md @@ -0,0 +1,67 @@ +# How to contribute # + +We'd love to accept your patches and contributions to this project. There are +a just a few small guidelines you need to follow. + + +## Contributor License Agreement ## + +Contributions to any Google project must be accompanied by a Contributor +License Agreement. This is not a copyright **assignment**, it simply gives +Google permission to use and redistribute your contributions as part of the +project. + + * If you are an individual writing original source code and you're sure you + own the intellectual property, then you'll need to sign an [individual + CLA][]. + + * If you work for a company that wants to allow you to contribute your work, + then you'll need to sign a [corporate CLA][]. + +You generally only need to submit a CLA once, so if you've already submitted +one (even if it was for a different project), you probably don't need to do it +again. + +[individual CLA]: https://developers.google.com/open-source/cla/individual +[corporate CLA]: https://developers.google.com/open-source/cla/corporate + + +## Submitting a patch ## + + 1. It's generally best to start by opening a new issue describing the bug or + feature you're intending to fix. Even if you think it's relatively minor, + it's helpful to know what people are working on. Mention in the initial + issue that you are planning to work on that bug or feature so that it can + be assigned to you. + + 1. Follow the normal process of [forking][] the project, and setup a new + branch to work in. It's important that each group of changes be done in + separate branches in order to ensure that a pull request only includes the + commits related to that bug or feature. + + 1. Go makes it very simple to ensure properly formatted code, so always run + `go fmt` on your code before committing it. You should also run + [golint][] over your code. As noted in the [golint readme][], it's not + strictly necessary that your code be completely "lint-free", but this will + help you find common style issues. + + 1. Any significant changes should almost always be accompanied by tests. The + project already has good test coverage, so look at some of the existing + tests if you're unsure how to go about it. [gocov][] and [gocov-html][] + are invaluable tools for seeing which parts of your code aren't being + exercised by your tests. + + 1. Do your best to have [well-formed commit messages][] for each change. + This provides consistency throughout the project, and ensures that commit + messages are able to be formatted properly by various git tools. + + 1. Finally, push the commits to your fork and submit a [pull request][]. + +[forking]: https://help.github.com/articles/fork-a-repo +[golint]: https://github.com/golang/lint +[golint readme]: https://github.com/golang/lint/blob/master/README +[gocov]: https://github.com/axw/gocov +[gocov-html]: https://github.com/matm/gocov-html +[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html +[squash]: http://git-scm.com/book/en/Git-Tools-Rewriting-History#Squashing-Commits +[pull request]: https://help.github.com/articles/creating-a-pull-request diff --git a/src/kube2msb/vendor/github.com/google/gofuzz/LICENSE b/src/kube2msb/vendor/github.com/google/gofuzz/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/gofuzz/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/kube2msb/vendor/github.com/google/gofuzz/README.md b/src/kube2msb/vendor/github.com/google/gofuzz/README.md new file mode 100644 index 0000000..68fcf2c --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/gofuzz/README.md @@ -0,0 +1,71 @@ +gofuzz +====== + +gofuzz is a library for populating go objects with random values. + +[![GoDoc](https://godoc.org/github.com/google/gofuzz?status.png)](https://godoc.org/github.com/google/gofuzz) +[![Travis](https://travis-ci.org/google/gofuzz.svg?branch=master)](https://travis-ci.org/google/gofuzz) + +This is useful for testing: + +* Do your project's objects really serialize/unserialize correctly in all cases? +* Is there an incorrectly formatted object that will cause your project to panic? + +Import with ```import "github.com/google/gofuzz"``` + +You can use it on single variables: +``` +f := fuzz.New() +var myInt int +f.Fuzz(&myInt) // myInt gets a random value. +``` + +You can use it on maps: +``` +f := fuzz.New().NilChance(0).NumElements(1, 1) +var myMap map[ComplexKeyType]string +f.Fuzz(&myMap) // myMap will have exactly one element. +``` + +Customize the chance of getting a nil pointer: +``` +f := fuzz.New().NilChance(.5) +var fancyStruct struct { + A, B, C, D *string +} +f.Fuzz(&fancyStruct) // About half the pointers should be set. +``` + +You can even customize the randomization completely if needed: +``` +type MyEnum string +const ( + A MyEnum = "A" + B MyEnum = "B" +) +type MyInfo struct { + Type MyEnum + AInfo *string + BInfo *string +} + +f := fuzz.New().NilChance(0).Funcs( + func(e *MyInfo, c fuzz.Continue) { + switch c.Intn(2) { + case 0: + e.Type = A + c.Fuzz(&e.AInfo) + case 1: + e.Type = B + c.Fuzz(&e.BInfo) + } + }, +) + +var myObject MyInfo +f.Fuzz(&myObject) // Type will correspond to whether A or B info is set. +``` + +See more examples in ```example_test.go```. + +Happy testing! diff --git a/src/kube2msb/vendor/github.com/google/gofuzz/doc.go b/src/kube2msb/vendor/github.com/google/gofuzz/doc.go new file mode 100644 index 0000000..9f9956d --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/gofuzz/doc.go @@ -0,0 +1,18 @@ +/* +Copyright 2014 Google Inc. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package fuzz is a library for populating go objects with random values. +package fuzz diff --git a/src/kube2msb/vendor/github.com/google/gofuzz/fuzz.go b/src/kube2msb/vendor/github.com/google/gofuzz/fuzz.go new file mode 100644 index 0000000..42d9a48 --- /dev/null +++ b/src/kube2msb/vendor/github.com/google/gofuzz/fuzz.go @@ -0,0 +1,446 @@ +/* +Copyright 2014 Google Inc. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package fuzz + +import ( + "fmt" + "math/rand" + "reflect" + "time" +) + +// fuzzFuncMap is a map from a type to a fuzzFunc that handles that type. +type fuzzFuncMap map[reflect.Type]reflect.Value + +// Fuzzer knows how to fill any object with random fields. +type Fuzzer struct { + fuzzFuncs fuzzFuncMap + defaultFuzzFuncs fuzzFuncMap + r *rand.Rand + nilChance float64 + minElements int + maxElements int +} + +// New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs, +// RandSource, NilChance, or NumElements in any order. +func New() *Fuzzer { + f := &Fuzzer{ + defaultFuzzFuncs: fuzzFuncMap{ + reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime), + }, + + fuzzFuncs: fuzzFuncMap{}, + r: rand.New(rand.NewSource(time.Now().UnixNano())), + nilChance: .2, + minElements: 1, + maxElements: 10, + } + return f +} + +// Funcs adds each entry in fuzzFuncs as a custom fuzzing function. +// +// Each entry in fuzzFuncs must be a function taking two parameters. +// The first parameter must be a pointer or map. It is the variable that +// function will fill with random data. The second parameter must be a +// fuzz.Continue, which will provide a source of randomness and a way +// to automatically continue fuzzing smaller pieces of the first parameter. +// +// These functions are called sensibly, e.g., if you wanted custom string +// fuzzing, the function `func(s *string, c fuzz.Continue)` would get +// called and passed the address of strings. Maps and pointers will always +// be made/new'd for you, ignoring the NilChange option. For slices, it +// doesn't make much sense to pre-create them--Fuzzer doesn't know how +// long you want your slice--so take a pointer to a slice, and make it +// yourself. (If you don't want your map/pointer type pre-made, take a +// pointer to it, and make it yourself.) See the examples for a range of +// custom functions. +func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer { + for i := range fuzzFuncs { + v := reflect.ValueOf(fuzzFuncs[i]) + if v.Kind() != reflect.Func { + panic("Need only funcs!") + } + t := v.Type() + if t.NumIn() != 2 || t.NumOut() != 0 { + panic("Need 2 in and 0 out params!") + } + argT := t.In(0) + switch argT.Kind() { + case reflect.Ptr, reflect.Map: + default: + panic("fuzzFunc must take pointer or map type") + } + if t.In(1) != reflect.TypeOf(Continue{}) { + panic("fuzzFunc's second parameter must be type fuzz.Continue") + } + f.fuzzFuncs[argT] = v + } + return f +} + +// RandSource causes f to get values from the given source of randomness. +// Use if you want deterministic fuzzing. +func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer { + f.r = rand.New(s) + return f +} + +// NilChance sets the probability of creating a nil pointer, map, or slice to +// 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive. +func (f *Fuzzer) NilChance(p float64) *Fuzzer { + if p < 0 || p > 1 { + panic("p should be between 0 and 1, inclusive.") + } + f.nilChance = p + return f +} + +// NumElements sets the minimum and maximum number of elements that will be +// added to a non-nil map or slice. +func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer { + if atLeast > atMost { + panic("atLeast must be <= atMost") + } + if atLeast < 0 { + panic("atLeast must be >= 0") + } + f.minElements = atLeast + f.maxElements = atMost + return f +} + +func (f *Fuzzer) genElementCount() int { + if f.minElements == f.maxElements { + return f.minElements + } + return f.minElements + f.r.Intn(f.maxElements-f.minElements) +} + +func (f *Fuzzer) genShouldFill() bool { + return f.r.Float64() > f.nilChance +} + +// Fuzz recursively fills all of obj's fields with something random. First +// this tries to find a custom fuzz function (see Funcs). If there is no +// custom function this tests whether the object implements fuzz.Interface and, +// if so, calls Fuzz on it to fuzz itself. If that fails, this will see if +// there is a default fuzz function provided by this package. If all of that +// fails, this will generate random values for all primitive fields and then +// recurse for all non-primitives. +// +// Not safe for cyclic or tree-like structs! +// +// obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ ) +// Intended for tests, so will panic on bad input or unimplemented fields. +func (f *Fuzzer) Fuzz(obj interface{}) { + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("needed ptr!") + } + v = v.Elem() + f.doFuzz(v, 0) +} + +// FuzzNoCustom is just like Fuzz, except that any custom fuzz function for +// obj's type will not be called and obj will not be tested for fuzz.Interface +// conformance. This applies only to obj and not other instances of obj's +// type. +// Not safe for cyclic or tree-like structs! +// obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ ) +// Intended for tests, so will panic on bad input or unimplemented fields. +func (f *Fuzzer) FuzzNoCustom(obj interface{}) { + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("needed ptr!") + } + v = v.Elem() + f.doFuzz(v, flagNoCustomFuzz) +} + +const ( + // Do not try to find a custom fuzz function. Does not apply recursively. + flagNoCustomFuzz uint64 = 1 << iota +) + +func (f *Fuzzer) doFuzz(v reflect.Value, flags uint64) { + if !v.CanSet() { + return + } + + if flags&flagNoCustomFuzz == 0 { + // Check for both pointer and non-pointer custom functions. + if v.CanAddr() && f.tryCustom(v.Addr()) { + return + } + if f.tryCustom(v) { + return + } + } + + if fn, ok := fillFuncMap[v.Kind()]; ok { + fn(v, f.r) + return + } + switch v.Kind() { + case reflect.Map: + if f.genShouldFill() { + v.Set(reflect.MakeMap(v.Type())) + n := f.genElementCount() + for i := 0; i < n; i++ { + key := reflect.New(v.Type().Key()).Elem() + f.doFuzz(key, 0) + val := reflect.New(v.Type().Elem()).Elem() + f.doFuzz(val, 0) + v.SetMapIndex(key, val) + } + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Ptr: + if f.genShouldFill() { + v.Set(reflect.New(v.Type().Elem())) + f.doFuzz(v.Elem(), 0) + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Slice: + if f.genShouldFill() { + n := f.genElementCount() + v.Set(reflect.MakeSlice(v.Type(), n, n)) + for i := 0; i < n; i++ { + f.doFuzz(v.Index(i), 0) + } + return + } + v.Set(reflect.Zero(v.Type())) + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + f.doFuzz(v.Field(i), 0) + } + case reflect.Array: + fallthrough + case reflect.Chan: + fallthrough + case reflect.Func: + fallthrough + case reflect.Interface: + fallthrough + default: + panic(fmt.Sprintf("Can't handle %#v", v.Interface())) + } +} + +// tryCustom searches for custom handlers, and returns true iff it finds a match +// and successfully randomizes v. +func (f *Fuzzer) tryCustom(v reflect.Value) bool { + // First: see if we have a fuzz function for it. + doCustom, ok := f.fuzzFuncs[v.Type()] + if !ok { + // Second: see if it can fuzz itself. + if v.CanInterface() { + intf := v.Interface() + if fuzzable, ok := intf.(Interface); ok { + fuzzable.Fuzz(Continue{f: f, Rand: f.r}) + return true + } + } + // Finally: see if there is a default fuzz function. + doCustom, ok = f.defaultFuzzFuncs[v.Type()] + if !ok { + return false + } + } + + switch v.Kind() { + case reflect.Ptr: + if v.IsNil() { + if !v.CanSet() { + return false + } + v.Set(reflect.New(v.Type().Elem())) + } + case reflect.Map: + if v.IsNil() { + if !v.CanSet() { + return false + } + v.Set(reflect.MakeMap(v.Type())) + } + default: + return false + } + + doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{ + f: f, + Rand: f.r, + })}) + return true +} + +// Interface represents an object that knows how to fuzz itself. Any time we +// find a type that implements this interface we will delegate the act of +// fuzzing itself. +type Interface interface { + Fuzz(c Continue) +} + +// Continue can be passed to custom fuzzing functions to allow them to use +// the correct source of randomness and to continue fuzzing their members. +type Continue struct { + f *Fuzzer + + // For convenience, Continue implements rand.Rand via embedding. + // Use this for generating any randomness if you want your fuzzing + // to be repeatable for a given seed. + *rand.Rand +} + +// Fuzz continues fuzzing obj. obj must be a pointer. +func (c Continue) Fuzz(obj interface{}) { + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("needed ptr!") + } + v = v.Elem() + c.f.doFuzz(v, 0) +} + +// FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for +// obj's type will not be called and obj will not be tested for fuzz.Interface +// conformance. This applies only to obj and not other instances of obj's +// type. +func (c Continue) FuzzNoCustom(obj interface{}) { + v := reflect.ValueOf(obj) + if v.Kind() != reflect.Ptr { + panic("needed ptr!") + } + v = v.Elem() + c.f.doFuzz(v, flagNoCustomFuzz) +} + +// RandString makes a random string up to 20 characters long. The returned string +// may include a variety of (valid) UTF-8 encodings. +func (c Continue) RandString() string { + return randString(c.Rand) +} + +// RandUint64 makes random 64 bit numbers. +// Weirdly, rand doesn't have a function that gives you 64 random bits. +func (c Continue) RandUint64() uint64 { + return randUint64(c.Rand) +} + +// RandBool returns true or false randomly. +func (c Continue) RandBool() bool { + return randBool(c.Rand) +} + +func fuzzInt(v reflect.Value, r *rand.Rand) { + v.SetInt(int64(randUint64(r))) +} + +func fuzzUint(v reflect.Value, r *rand.Rand) { + v.SetUint(randUint64(r)) +} + +func fuzzTime(t *time.Time, c Continue) { + var sec, nsec int64 + // Allow for about 1000 years of random time values, which keeps things + // like JSON parsing reasonably happy. + sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60) + c.Fuzz(&nsec) + *t = time.Unix(sec, nsec) +} + +var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){ + reflect.Bool: func(v reflect.Value, r *rand.Rand) { + v.SetBool(randBool(r)) + }, + reflect.Int: fuzzInt, + reflect.Int8: fuzzInt, + reflect.Int16: fuzzInt, + reflect.Int32: fuzzInt, + reflect.Int64: fuzzInt, + reflect.Uint: fuzzUint, + reflect.Uint8: fuzzUint, + reflect.Uint16: fuzzUint, + reflect.Uint32: fuzzUint, + reflect.Uint64: fuzzUint, + reflect.Uintptr: fuzzUint, + reflect.Float32: func(v reflect.Value, r *rand.Rand) { + v.SetFloat(float64(r.Float32())) + }, + reflect.Float64: func(v reflect.Value, r *rand.Rand) { + v.SetFloat(r.Float64()) + }, + reflect.Complex64: func(v reflect.Value, r *rand.Rand) { + panic("unimplemented") + }, + reflect.Complex128: func(v reflect.Value, r *rand.Rand) { + panic("unimplemented") + }, + reflect.String: func(v reflect.Value, r *rand.Rand) { + v.SetString(randString(r)) + }, + reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) { + panic("unimplemented") + }, +} + +// randBool returns true or false randomly. +func randBool(r *rand.Rand) bool { + if r.Int()&1 == 1 { + return true + } + return false +} + +type charRange struct { + first, last rune +} + +// choose returns a random unicode character from the given range, using the +// given randomness source. +func (r *charRange) choose(rand *rand.Rand) rune { + count := int64(r.last - r.first) + return r.first + rune(rand.Int63n(count)) +} + +var unicodeRanges = []charRange{ + {' ', '~'}, // ASCII characters + {'\u00a0', '\u02af'}, // Multi-byte encoded characters + {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings) +} + +// randString makes a random string up to 20 characters long. The returned string +// may include a variety of (valid) UTF-8 encodings. +func randString(r *rand.Rand) string { + n := r.Intn(20) + runes := make([]rune, n) + for i := range runes { + runes[i] = unicodeRanges[r.Intn(len(unicodeRanges))].choose(r) + } + return string(runes) +} + +// randUint64 makes random 64 bit numbers. +// Weirdly, rand doesn't have a function that gives you 64 random bits. +func randUint64(r *rand.Rand) uint64 { + return uint64(r.Uint32())<<32 | uint64(r.Uint32()) +} |