utils

package
v0.1.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 6, 2017 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Copyright 2017 Rackspace

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 utils provides various utility functions and construct.

Most are designed to be usable even outside of the poller project.

Index

Constants

View Source
const BuildDir = "build"
View Source
const (
	// ReadKeepaliveTolerance is the division of ReadKeepalive that will be added when computing the read deadline.
	// It's a divisor because of durations being integer.
	ReadKeepaliveTolerance = 2
)

Variables

View Source
var IntegrationTestCA = []byte(`-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAIMtTD12XoEmMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV
BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
aWRnaXRzIFB0eSBMdGQwHhcNMTcwMTEyMTYyNzQyWhcNMjIwMTExMTYyNzQyWjBF
MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEArCoS/pJSCWRaqZOTDgbFcup5/EIHe4gGbK9i6FpESWXpcl9Tebb+gkDV
uDfBdrjZhIrLx+jGqhaMLedAS0xGYeWt0IZPYgQ1jw5Jv34mapmCVGclvkNNPY0y
KUxl8O11yy5rOPwmlI7hMQXzgy26laOrzviqyetYs3CaFUrRHQmb6LoexnnylxdS
sArRzm4mHJA6crWf7cqd7iLiqZ9gDBLjBuBXeAOPHXCOKW6aqP9JqiFge/3G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TCgwx395s8fsySclPudpk10kx6UCguoAn4/WHSlFE
DURRpMzews9k3D2lFdpA7VyUaMrI6IioUOs4rOK65g68xlr5uW685ODQWPkz1oQX
OsojMgC+zWb7T08SL7zDiQu2sWr8upWbBfi5epqWY+PqqxVUuQ1Uowcfgi91xq8O
R86QdFWPcHgWRQ2mn05SlAsFV/hTAgMBAAGjKDAmMA8GA1UdEQQIMAaHBH8AAAEw
EwYDVR0lBAwwCgYIKwYBBQUHAwEwDQYJKoZIhvcNAQELBQADggEBABiNlbjqJV86
fJO6WDCQuUXypeEdWxE2bB/IoRTsz4Br9N56Mhk0isdDhd7Iix7nmhiR9thIXzng
uAO+WUmbyTfT7O5aJU62bVRqU+k+OhjVD8DlE7+rftr7w7+LIFUKfO9nb/ogbaZa
wE7tUA+hBvuOFx/GK/bz9WOBTNmfGqx1RoioDOSZZzJag2IoKgu/k84b5jQ3MwAX
SRaoY+e0wptuMPl2te/K9U+0Pe767fll+Vq/NzJxWVCvuyoTGu8AKcO1wZPVIu9d
Pps9FPwZB2Qio9XrjuQyn/PfYrKId+wl9MEC8n+PxVhP8DskWZI5PW9E3uyMn8Nu
TbbKwFgzDuE=
-----END CERTIFICATE-----`)
View Source
var IntegrationTestKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA5hvy3jum+nTuYn7W9r1sKJV+AjN71L02Wa9aHKuu8lFnh+cX
QlMCHKAcH8s4vAw79sTy6H7Ql5OVoZqcM2wHg8eFIjeURWh7BefKZC49HYIrFA3/
ZXE+LealnmWS9rmrPjexqE6Akqb6CHbo0woMMd/ebPH7MknJT7naZNdJMelAoLqA
J+P1h0pRRA1EUaTM3sLPZNw9pRXaQO1clGjKyOiIqFDrOKziuuYOvMZa+bluvOTg
0Fj5M9aEFzrKIzIAvs1m+09PEi+8w4kLtrFq/LqVmwX4uXqalmPj6qsVVLkNVKMH
H4IvdcavDkfOkHRVj3B4FkUNpp9OUpQLBVf4UwIDAQABAoIBACzlmR55P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rtG7LOoZ3PB8Y+xzvEg54vIxx0tb+xHY+TsDwFykQ64OC0W
KYHCMCMEpEOlwGcOm6mTh1uE8TRxn8En4zWlsVo1DSdOiCya7LUp1Vhp4ED2eZlc
kUw0dOqL+1istTBjzQGIjZ6W1+VGhTGbfPubms6Bxml2zIKs924ymA==
-----END RSA PRIVATE KEY-----`)
View Source
var LocalhostCert = []byte(`-----BEGIN CERTIFICATE-----
MIICEzCCAXygAwIBAgIQMIMChMLGrR+QvmQvpwAU6zANBgkqhkiG9w0BAQsFADAS
MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw
MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
iQKBgQDuLnQAI3mDgey3VBzWnB2L39JUU4txjeVE6myuDqkM/uGlfjb9SjY1bIw4
iA5sBBZzHi3z0h1YV8QPuxEbi4nW91IJm2gsvvZhIrCHS3l6afab4pZBl2+XsDul
rKBxKKtD1rGxlG4LjncdabFn9gvLZad2bSysqz/qTAUStTvqJQIDAQABo2gwZjAO
BgNVHQ8BAf8EBAMCAqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUw
AwEB/zAuBgNVHREEJzAlggtleGFtcGxlLmNvbYcEfwAAAYcQAAAAAAAAAAAAAAAA
AAAAATANBgkqhkiG9w0BAQsFAAOBgQCEcetwO59EWk7WiJsG4x8SY+UIAA+flUI9
tyC4lNhbcF2Idq9greZwbYCqTTTr2XiRNSMLCOjKyI7ukPoPjo16ocHj+P3vZGfs
h1fIw3cSS2OolhloGw/XM6RWPWtPAlGykKLciQrBru5NAPvCMsb/I1DAceTiotQM
fblo6RBxUQ==
-----END CERTIFICATE-----`)

LocalhostCert is a PEM-encoded TLS cert with SAN IPs "127.0.0.1" and "[::1]", expiring at Jan 29 16:00:00 2084 GMT. generated from src/crypto/tls: go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h

View Source
var LocalhostKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDuLnQAI3mDgey3VBzWnB2L39JUU4txjeVE6myuDqkM/uGlfjb9
SjY1bIw4iA5sBBZzHi3z0h1YV8QPuxEbi4nW91IJm2gsvvZhIrCHS3l6afab4pZB
l2+XsDulrKBxKKtD1rGxlG4LjncdabFn9gvLZad2bSysqz/qTAUStTvqJQIDAQAB
AoGAGRzwwir7XvBOAy5tM/uV6e+Zf6anZzus1s1Y1ClbjbE6HXbnWWF/wbZGOpet
3Zm4vD6MXc7jpTLryzTQIvVdfQbRc6+MUVeLKwZatTXtdZrhu+Jk7hx0nTPy8Jcb
uJqFk541aEw+mMogY/xEcfbWd6IOkp+4xqjlFLBEDytgbIECQQDvH/E6nk+hgN4H
qzzVtxxr397vWrjrIgPbJpQvBsafG7b0dA4AFjwVbFLmQcj2PprIMmPcQrooz8vp
jy4SHEg1AkEA/v13/5M47K9vCxmb8QeD/asydfsgS5TeuNi8DoUBEmiSJwma7FXY
fFUtxuvL7XvjwjN5B30pNEbc6Iuyt7y4MQJBAIt21su4b3sjXNueLKH85Q+phy2U
fQtuUE9txblTu14q3N7gHRZB4ZMhFYyDy8CKrN2cPg/Fvyt0Xlp/DoCzjA0CQQDU
y2ptGsuSmgUtWj3NM9xuwYPm+Z/F84K6+ARYiZ6PYj013sovGKUFfYAqVXVlxtIX
qyUBnu3X9ps8ZfjLZO7BAkEAlT4R5Yl6cGhaJQYZHOde3JEMhNRcVFMO8dJDaFeo
f9Oeos0UUothgiDktdQHxdNEwLjQf7lJJBzV+5OtwswCWA==
-----END RSA PRIVATE KEY-----`)

LocalhostKey is the private key for localhostCert.

View Source
var PollerCommand = fmt.Sprintf("%s/src/github.com/racker/rackspace-monitoring-poller/%s/rackspace-monitoring-poller_%s_%s",
	os.Getenv("GOPATH"),
	BuildDir,
	runtime.GOOS,
	runtime.GOARCH,
)

PollerCommand is the program name for the poller. Used for integration tests

Functions

func ChannelOfTimer

func ChannelOfTimer(timer *time.Timer) <-chan time.Time

ChannelOfTimer is a nil-safe channel getter which becomes useful when needing to "select on a timer" that may not always be activated. For example,

  select {
  	case t := <- utils.ChannelOfTimer(timer) :
  		... do something with timeout
	case f := <- frames:
  		timer = time.NewTimer(d)
  }

func ContainsAllKeys

func ContainsAllKeys(v map[string]interface{}, keys ...string) bool

func Die

func Die(err error, messages ...string)

Die prints messages and an error to stderr and then exit the process with status code 1. It is intended for failures early in startup that need to be reported to a human.

messages is zero or many messages that will each be printed on a line before the err

func GetDNFromCert

func GetDNFromCert(namespace pkix.Name, sep string) (string, error)

Convert a DN to a String return the string, or and error

func HandleInterrupts

func HandleInterrupts() chan os.Signal

HandleInterrupts returns a channel that will get notified when a SIGTERM signal occurs

func IdentifierSafe

func IdentifierSafe(r rune) rune

IdentifierSafe can be passed to strings.Map to convert all non-alphanumeric characters to underscores

func RunCommand

func RunCommand(result *Result)

func ScaleFractionalDuration

func ScaleFractionalDuration(duration time.Duration, targetUnits time.Duration) float64

ScaleFractionalDuration is primarily useful when scaling durations that are "sub second", but more generally it's when duration is smaller than targetUnits. In that case, a fractional value is much more meangingful than a 0, which is what would happen with plain duration (i.e. integer) division. targetUnits should really be one of the Duration constants, such as time.Second.

func StartCommand

func StartCommand(result *Result)

StartCommand attempts to start the command. Sets the result error if start fails

func TestTimebox_Quick

func TestTimebox_Quick(t *testing.T)

func TestTimebox_TimesOut

func TestTimebox_TimesOut(t *testing.T)

func Timebox

func Timebox(t *testing.T, d time.Duration, boxed func(t *testing.T)) bool

Timebox is used for putting a time bounds around a chunk of code, given as the function boxed. NOTE that if the duration d elapses, then boxed will be left to run off in its go-routine...it can't be forcefully terminated. This function can be used outside of a unit test context by passing nil for t Returns true if boxed finished before duration d elapsed.

func TimeboxNamed

func TimeboxNamed(t *testing.T, name string, d time.Duration, boxed func(t *testing.T)) bool

Timebox is used for putting a time bounds around a chunk of code, given as the function boxed. NOTE that if the duration d elapses, then boxed will be left to run off in its go-routine...it can't be forcefully terminated. This function can be used outside of a unit test context by passing nil for t Returns true if boxed finished before duration d elapsed.

Types

type BannerServer

type BannerServer struct {
	HandleConnection func(conn net.Conn)
	// contains filtered or unexported fields
}

func NewBannerServer

func NewBannerServer() *BannerServer

func (*BannerServer) Serve

func (s *BannerServer) Serve(listener net.Listener)

func (*BannerServer) ServeTLS

func (s *BannerServer) ServeTLS(listener net.Listener)

func (*BannerServer) Stop

func (s *BannerServer) Stop()

type BlockingReadBuffer

type BlockingReadBuffer struct {
	bytes.Buffer
	// contains filtered or unexported fields
}

BlockingReadBuffer implements the io.ReadWriteCloser interface and extends a bytes.Buffer by altering the Read operation to block when the buffer is empty.

func NewBlockingReadBuffer

func NewBlockingReadBuffer() *BlockingReadBuffer

NewBlockingReadBuffer instantiates a BlockingReadBuffer ready for ReadWriteCloser operations.

func (*BlockingReadBuffer) Close

func (bb *BlockingReadBuffer) Close() error

Close marks the buffer closed and unblocks any current or future Read operations.

func (*BlockingReadBuffer) Read

func (bb *BlockingReadBuffer) Read(p []byte) (n int, err error)

Read reads from the internal buffer, but blocks if content is not yet ready. If this buffer is closed, then this will immediately return 0, io.EOF

func (*BlockingReadBuffer) ReadReady

func (bb *BlockingReadBuffer) ReadReady() bool

ReadReady is a non-blocking operation to see if any bytes are ready to be read.

func (*BlockingReadBuffer) Write

func (bb *BlockingReadBuffer) Write(p []byte) (n int, err error)

Write places more content in the internal buffer and

type BoundAddress

type BoundAddress struct {
	IP   string
	Port int
	Zone string
}

type Commander

type Commander interface {
	Start() error
	Wait() error
	GetProcess() *os.Process
	GetProcessState() *os.ProcessState
	GetArgs() []string
}

Commander interface is a wrapper around *exec.Cmd. Mainly utilized for testing subprocesses without executing code

type NowTimestampMillisFunc

type NowTimestampMillisFunc func() int64
var NowTimestampMillis NowTimestampMillisFunc = func() int64 {
	return time.Now().UnixNano() / int64(time.Millisecond)
}

func InstallAlternateTimestampFunc

func InstallAlternateTimestampFunc(newFunc NowTimestampMillisFunc) (priorFunc NowTimestampMillisFunc)

InstallAlternateTimestampFunc is intended for unit testing where a deterministic timestamp needs to be temporarily enabled. Be sure to defer re-invoke this function to re-install the prior one.

type OutputMessage

type OutputMessage struct {
	Level     string
	Msg       string
	Address   string
	BoundAddr *BoundAddress
}

func BufferToStringSlice

func BufferToStringSlice(buf *bytes.Buffer) []*OutputMessage

type PollerCmd

type PollerCmd struct {
	*exec.Cmd
}

func (*PollerCmd) GetArgs

func (c *PollerCmd) GetArgs() []string

func (*PollerCmd) GetProcess

func (c *PollerCmd) GetProcess() *os.Process

func (*PollerCmd) GetProcessState

func (c *PollerCmd) GetProcessState() *os.ProcessState

type Result

type Result struct {
	Command        Commander
	Error          error
	ErrorOnTimeout bool
	Timeout        time.Duration
	StdOut         *bytes.Buffer
	StdErr         *bytes.Buffer
}

Result is used to wrap integration test results It wraps the command struct that sets up the required timeout It also wraps STDOUT and STDERR for output validation, exit codes for validation, and timeout that will either kill your process and report error or kill your process and allow you to validate outputs

func SetupCommand

func SetupCommand(commandList []string,
	errorOnTimeout bool, timeout time.Duration) *Result

SetupCommand sets up Result with passed in command list, and timeouts. timeout for erroring takes preference over timeout success

type SmartConn

type SmartConn struct {

	// Specifies how long each Write (or helper thereof) is allowed to execute before triggering the channel deadline
	WriteAllowance time.Duration
	ReadKeepalive  time.Duration

	// An optional function that will get invoked according to HeartbeatSendInterval
	HeartbeatSender       func(sconn *SmartConn)
	HeartbeatSendInterval time.Duration
	// contains filtered or unexported fields
}

SmartConn wraps a net.Conn with auto-logic for managing the read and write deadlines

This implements the io.WriterCloser interface, so it can be used accordingly. It also partially implements the net.Conn interface.

func NewSmartConn

func NewSmartConn(c net.Conn) *SmartConn

NewSmartConn creates a SmartConn that manages the connection c. The object can be further configured, but Start MUST be called before it is fully usable.

func (*SmartConn) Close

func (c *SmartConn) Close() error

func (*SmartConn) Read

func (c *SmartConn) Read(b []byte) (n int, err error)

func (*SmartConn) RemoteAddr

func (c *SmartConn) RemoteAddr() net.Addr

func (*SmartConn) Start

func (c *SmartConn) Start() error

Start initiates the read keepalive/deadline management and heartbeat sending. Returns any error from the connection deadline setting.

func (*SmartConn) Write

func (c *SmartConn) Write(p []byte) (n int, err error)

func (*SmartConn) WriteJSON

func (c *SmartConn) WriteJSON(v interface{}) error

WriteJSON is a convenience method to write line-oriented JSON to the connection.

type StatusLine

type StatusLine struct {
	// contains filtered or unexported fields
}

StatusLine structure

func NewStatusLine

func NewStatusLine() *StatusLine

NewStatusLine constructor

func (*StatusLine) Add

func (sl *StatusLine) Add(key string, value interface{})

Add adds a key/value to the statusline

func (*StatusLine) AddOption

func (sl *StatusLine) AddOption(key string)

AddOption adds an option to the statusline

func (*StatusLine) Clear

func (sl *StatusLine) Clear()

Clear the lines within the statusline

func (*StatusLine) String

func (sl *StatusLine) String() string

String stringifies the object

type TimeLatencyTracking

type TimeLatencyTracking struct {
	// PollerSendTimestamp is when the poller sent a heartbeat
	PollerSendTimestamp int64
	// PollerRecvTimestamp is when the poller received the heartbeat ack from the server
	PollerRecvTimestamp int64
	// ServerRecvTimestamp is when the server/endpoint recorded receiving our heartbeat
	ServerRecvTimestamp int64
	// ServerRespTimestamp is when the server/endpoint sent its heartbeat ack
	ServerRespTimestamp int64
}

TimeLatencyTracking is used for tracking observations of poller<->endpoint server latency.

func (*TimeLatencyTracking) ComputeSkew

func (tt *TimeLatencyTracking) ComputeSkew() (offset int64, latency int64, _ error)

ComputeSkew uses the NTP algorithm documented here 1 to compute the poller-endpoint/server time offset and transit latency.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL