diff --git a/cmd/f5-ipam-controller/main.go b/cmd/f5-ipam-controller/main.go index e536fbd..370b036 100644 --- a/cmd/f5-ipam-controller/main.go +++ b/cmd/f5-ipam-controller/main.go @@ -2,22 +2,24 @@ package main import ( "fmt" - "golang.org/x/crypto/ssh/terminal" "os" "os/signal" "strings" "syscall" - flag "github.com/spf13/pflag" + "golang.org/x/crypto/ssh/terminal" + "github.com/f5devcentral/f5-ipam-controller/pkg/controller" "github.com/f5devcentral/f5-ipam-controller/pkg/manager" "github.com/f5devcentral/f5-ipam-controller/pkg/orchestration" log "github.com/f5devcentral/f5-ipam-controller/pkg/vlogger" clog "github.com/f5devcentral/f5-ipam-controller/pkg/vlogger/console" + flag "github.com/spf13/pflag" ) const ( - DefaultProvider = manager.F5IPAMProvider + DefaultProvider = manager.F5IPAMProvider + InfobloxProvider = manager.INFOBLOXProvider ) var ( @@ -25,6 +27,7 @@ var ( flags *flag.FlagSet globalFlags *flag.FlagSet providerFlags *flag.FlagSet + infobloxFlags *flag.FlagSet // Global logLevel *string @@ -32,13 +35,20 @@ var ( provider *string // Provider - iprange *string + iprange *string + infobloxHost *string + infobloxUsername *string + infobloxPassword *string + infobloxVersion *string + infobloxPort *string + infobloxSSLVerify *string ) func init() { flags = flag.NewFlagSet("main", flag.ContinueOnError) globalFlags = flag.NewFlagSet("Global", flag.ContinueOnError) providerFlags = flag.NewFlagSet("Provider", flag.ContinueOnError) + infobloxFlags = flag.NewFlagSet("Infoblox", flag.ContinueOnError) //Flag terminal wrapping var err error @@ -61,6 +71,24 @@ func init() { iprange = providerFlags.String("ip-range", "", "Optional, the Default Provider needs iprange to build pools of IP Addresses") + infobloxHost = infobloxFlags.String("infoblox-host", "", + "Optional, the Infoblox Provider needs infoblox-host") + + infobloxPort = infobloxFlags.String("wapi-port", "", + "Optional, the Infoblox Provider needs infoblox-port") + + infobloxUsername = infobloxFlags.String("wapi-username", "", + "Optional, the Infoblox Provider needs infoblox-UserName") + + infobloxPassword = infobloxFlags.String("wapi-password", "", + "Optional, the Infoblox Provider needs infoblox-Password") + + infobloxVersion = infobloxFlags.String("wapi-version", "", + "Optional, the Infoblox Provider needs infoblox-version") + + infobloxSSLVerify = infobloxFlags.String("ssl-verify", "false", + "Optional, the Infoblox Provider to enable verification of server certificate") + globalFlags.Usage = func() { _, _ = fmt.Fprintf(os.Stderr, " Global:\n%s\n", globalFlags.FlagUsagesWrapped(width)) } @@ -116,24 +144,34 @@ func main() { flags.Usage() os.Exit(1) } - orcr := orchestration.NewOrchestrator() if orcr == nil { log.Error("Unable to create IPAM Client") os.Exit(1) } - mgrParams := manager.Params{ - Provider: *provider, - IPAMManagerParams: manager.IPAMManagerParams{Range: *iprange}, + var mgrParams manager.Params + if *provider == InfobloxProvider { // Infoblox Provider + mgrParams.InfobloxParams = manager.InfobloxParams{ + Host: *infobloxHost, + Version: *infobloxVersion, + Port: *infobloxPort, + Username: *infobloxUsername, + Password: *infobloxPassword, + SSLVerify: *infobloxSSLVerify, + } + mgrParams.Provider = InfobloxProvider + } else { + //Default Provider Static Approach + mgrParams.IPAMManagerParams = manager.IPAMManagerParams{Range: *iprange} + mgrParams.Provider = DefaultProvider } - mgrParams.Range = *iprange - mgr := manager.NewManager(mgrParams) + stopCh := make(chan struct{}) ctlr := controller.NewController( controller.Spec{ Orchestrator: orcr, - Manager: mgr, + Manager: manager.NewManager(mgrParams), StopCh: stopCh, }, ) diff --git a/go.mod b/go.mod index 6a156d2..4da6720 100644 --- a/go.mod +++ b/go.mod @@ -3,15 +3,15 @@ module github.com/f5devcentral/f5-ipam-controller go 1.15 require ( + github.com/F5Networks/f5-ipam-ctlr v0.1.0 + github.com/infobloxopen/infoblox-go-client v1.1.0 github.com/mattn/go-sqlite3 v1.14.6 - github.com/mattn/goveralls v0.0.7 // indirect github.com/onsi/ginkgo v1.14.2 // indirect github.com/onsi/gomega v1.10.4 // indirect github.com/spf13/pflag v1.0.5 - github.com/wadey/gocovmerge v0.0.0-20160331181800-b5bfa59ec0ad // indirect golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 // indirect - golang.org/x/tools v0.0.0-20210104081019-d8d6ddbec6ee // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect k8s.io/apiextensions-apiserver v0.16.14 k8s.io/apimachinery v0.16.14 k8s.io/client-go v0.16.14 diff --git a/go.sum b/go.sum index ab27688..3622e6b 100644 --- a/go.sum +++ b/go.sum @@ -11,6 +11,8 @@ github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6L github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/F5Networks/f5-ipam-ctlr v0.1.0 h1:MurA7g55XxDU5gPRWihsjyIJwG9t/o3o424czJb84+A= +github.com/F5Networks/f5-ipam-ctlr v0.1.0/go.mod h1:GfniqGTE6kV1mxr2+fAbXra5yGnKMSKG/Zbrk0ylO8Y= github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= github.com/PuerkitoBio/purell v1.1.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= @@ -137,6 +139,8 @@ github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/infobloxopen/infoblox-go-client v1.1.0 h1:fw8q8USnngsoZxLploJ0LomBN+1SAhSyEjUZrSibKX4= +github.com/infobloxopen/infoblox-go-client v1.1.0/go.mod h1:BXiw7S2b9qJoM8MS40vfgCNB2NLHGusk1DtO16BD9zI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/json-iterator/go v0.0.0-20180612202835-f2b4162afba3/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= @@ -146,6 +150,7 @@ github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/u github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -161,7 +166,6 @@ github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg= github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= -github.com/mattn/goveralls v0.0.7/go.mod h1:h8b4ow6FxSPMQHF6o2ve3qsclnffZjYTNEKmLesRwqw= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= @@ -203,6 +207,7 @@ github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7q github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/remyoudompheng/bigfft v0.0.0-20170806203942-52369c62f446/go.mod h1:uYEyJGbgTkfkS4+E/PavXkNJcbFIpEtjt2B0KDQ5+9M= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/soheilhy/cmux v0.1.3/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= @@ -224,11 +229,8 @@ github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0 github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= -github.com/wadey/gocovmerge v0.0.0-20160331181800-b5bfa59ec0ad/go.mod h1:Hy8o65+MXnS6EwGElrSRjUzQDLXreJlzYLlWiHtt8hM= github.com/xiang90/probing v0.0.0-20160813154853-07dd2e8dfe18/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.uber.org/atomic v0.0.0-20181018215023-8dc6146f7569/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= @@ -239,7 +241,6 @@ golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY= @@ -253,8 +254,6 @@ golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvx golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -269,9 +268,7 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb h1:eBmm0M9fYhWpKZLjQUUKka/LtIxf46G4fxeEz5KJr9U= golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -283,8 +280,6 @@ golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -329,11 +324,7 @@ golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190920225731-5eefd052ad72/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200522201501-cb1345f3a375/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20210104081019-d8d6ddbec6ee/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/next-version.txt b/next-version.txt index 6e8bf73..17e51c3 100644 --- a/next-version.txt +++ b/next-version.txt @@ -1 +1 @@ -0.1.0 +0.1.1 diff --git a/pkg/manager/f5ipammanager.go b/pkg/manager/f5ipammanager.go index dcf9fa8..9c48c1f 100644 --- a/pkg/manager/f5ipammanager.go +++ b/pkg/manager/f5ipammanager.go @@ -27,7 +27,13 @@ func NewIPAMManager(params IPAMManagerParams) *IPAMManager { } // Creates an A record -func (ipMgr *IPAMManager) CreateARecord(hostname, ipAddr string) bool { +func (ipMgr *IPAMManager) CreateARecord(params ...interface{}) bool { + if len(params) != 2 { + log.Errorf("[IPMG] Correct no. of arguments not passed") + return false + } + hostname := params[0].(string) + ipAddr := params[1].(string) if !isIPV4Addr(ipAddr) { log.Errorf("[IPMG] Invalid IP Address Provided") return false @@ -38,7 +44,14 @@ func (ipMgr *IPAMManager) CreateARecord(hostname, ipAddr string) bool { } // Deletes an A record and releases the IP address -func (ipMgr *IPAMManager) DeleteARecord(hostname, ipAddr string) { +func (ipMgr *IPAMManager) DeleteARecord(params ...interface{}) { + if len(params) != 2 { + log.Errorf("[IPMG] Correct no. of arguments not passed") + return + } + hostname := params[0].(string) + ipAddr := params[1].(string) + if !isIPV4Addr(ipAddr) { log.Errorf("[IPMG] Invalid IP Address Provided") return diff --git a/pkg/manager/infoblox.go b/pkg/manager/infoblox.go new file mode 100644 index 0000000..317887a --- /dev/null +++ b/pkg/manager/infoblox.go @@ -0,0 +1,538 @@ +/*- + * Copyright (c) 2018, F5 Networks, Inc. + * + * 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 manager + +import ( + "bytes" + "fmt" + "net" + "net/http" + "net/url" + "strings" + + log "github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger" + + store "github.com/F5Networks/f5-ipam-ctlr/pkg/store" + + ibclient "github.com/infobloxopen/infoblox-go-client" +) + +const EAKey = "F5-IPAM" +const EAVal = "managed" +const httpRequestTimeout = 20 +const httpPoolConnections = 10 + +// Map of host records to their Infoblox "ref" strings +type recordRef map[string]string + +// Convert ibclient.ObjectManager to interface for unit testing +type objectManager interface { + AllocateIP(netview, cidr, ipAddr, macAddress, vmID string) (*ibclient.FixedAddress, error) + ReleaseIP(netview, cidr, ipAddr, macAddr string) (string, error) +} + +// IBloxClient that the controller uses to talk to Infoblox +type IBloxClient struct { + conn ibclient.IBConnector + objMgr *ibclient.ObjectManager + recordRef recordRef + ea ibclient.EA +} + +// InfobloxParams allows NewInfobloxManager to receive all or some parameters +type InfobloxParams struct { + Host string + Version string + Port string + Username string + Password string + SSLVerify string +} + +// NewInfobloxManager sets up an interface with Infoblox +func NewInfobloxManager( + params *InfobloxParams, + cmpType string, +) (*IBloxClient, error) { + hostConfig := ibclient.HostConfig{ + Host: params.Host, + Version: params.Version, + Port: params.Port, + Username: params.Username, + Password: params.Password, + } + // TransportConfig params: sslVerify, httpRequestsTimeout, httpPoolConnections + // These are the common values + transportConfig := ibclient.NewTransportConfig(params.SSLVerify, httpRequestTimeout, httpPoolConnections) + requestBuilder := &ibclient.WapiRequestBuilder{} + requestor := &ibclient.WapiHttpRequestor{} + conn, err := ibclient.NewConnector(hostConfig, transportConfig, requestBuilder, requestor) + if err != nil { + return nil, err + } + objMgr := ibclient.NewObjectManager(conn, cmpType, "0") + // Create an Extensible Attribute for resource tracking + if eaDef, _ := objMgr.GetEADefinition(EAKey); eaDef == nil { + eaDef := ibclient.EADefinition{ + Name: EAKey, + Type: "STRING", + Comment: "Managed by the F5 IPAM Controller", + } + _, err = objMgr.CreateEADefinition(eaDef) + if err != nil { + return nil, err + } + } + + iClient := &IBloxClient{ + conn: conn, + objMgr: objMgr, + recordRef: make(recordRef), + ea: ibclient.EA{EAKey: EAVal}, + } + + return iClient, nil +} + +// CreateARecord creates a new A record in Infoblox +func (iClient *IBloxClient) CreateARecord(params ...interface{}) bool { + name := params[0].(string) + ipAddr := params[1].(string) + netview := params[2].(string) + obj := ibclient.NewRecordA( + ibclient.RecordA{ + Name: name, + Ipv4Addr: ipAddr, + View: netview, + Ea: iClient.ea, + }, + ) + res, err := iClient.getARecord(obj) + // If error or record already exists, return + if err != nil || (res != nil && len(res) > 0) { + return false + } + + log.Infof("Creating A record for '%s' as '%s'.", name, ipAddr) + ref, _ := iClient.conn.CreateObject(obj) + iClient.recordRef[name] = ref + return true +} + +// DeleteARecord deletes an A record and releases the IP address +func (iClient *IBloxClient) DeleteARecord(params ...interface{}) { + name := params[0].(string) + ipAddr := params[1].(string) + netview := params[2].(string) + cidr := params[3].(string) + obj := ibclient.NewRecordA( + ibclient.RecordA{ + Name: name, + Ipv4Addr: ipAddr, + View: netview, + Ea: iClient.ea, + }, + ) + res, err := iClient.getARecord(obj) + if err != nil { + return + } + // If record doesn't exist, release IP and return + if res == nil || len(res) == 0 { + log.Infof("Releasing IP address '%s'.", ipAddr) + iClient.ReleaseAddr(netview, cidr, ipAddr) + return + } + + for _, record := range res { + netCidr := iClient.getNetworkCIDR(netview, record.Ipv4Addr) + if netCidr == cidr { + log.Infof("Deleting A record for '%s'.", name) + iClient.conn.DeleteObject(record.Ref) + delete(iClient.recordRef, name) + } + } + + log.Infof("Releasing IP address '%s'.", ipAddr) + iClient.ReleaseAddr(netview, cidr, ipAddr) +} + +// CreateCNAMERecord creates a new CNAME record in Infoblox +func (iClient *IBloxClient) CreateCNAMERecord(name, canonical, netview string) { + obj := ibclient.NewRecordCNAME( + ibclient.RecordCNAME{ + Name: name, + Canonical: canonical, + View: netview, + Ea: iClient.ea, + }, + ) + res, err := iClient.getCNAMERecord(obj) + // If error or record already exists, return + if err != nil || (res != nil && len(res) > 0) { + return + } + + log.Infof("Creating CNAME record for '%s' as '%s'.", name, canonical) + ref, _ := iClient.conn.CreateObject(obj) + iClient.recordRef[name] = ref +} + +// DeleteCNAMERecord deletes a CNAME record from Infoblox +func (iClient *IBloxClient) DeleteCNAMERecord(name, ipAddr, netview, cidr string) { + obj := ibclient.NewRecordCNAME( + ibclient.RecordCNAME{ + Name: name, + View: netview, + Ea: iClient.ea, + }, + ) + res, err := iClient.getCNAMERecord(obj) + // If error or record doesn't exist, return + if err != nil || res == nil || len(res) == 0 { + return + } + + for _, record := range res { + netCidr := iClient.getNetworkCIDR(netview, ipAddr) + if netCidr == cidr { + log.Infof("Deleting CNAME record for '%s'.", name) + iClient.conn.DeleteObject(record.Ref) + delete(iClient.recordRef, name) + } + } +} + +// CNAMEToA changes an available CNAME to an A record, updates all ensuing CNAMEs +// in the list to point to the new record +func (iClient *IBloxClient) CNAMEToA( + availHosts []string, + delHost, + ipAddr, + netview, + cidr string, +) (string, error) { + var aRecord string + for i, host := range availHosts { + if i == 0 { + // Make the first available host the new A record + obj := ibclient.NewRecordA( + ibclient.RecordA{ + Name: host, + Ipv4Addr: ipAddr, + Ea: iClient.ea, + }, + ) + oldRef, found := iClient.recordRef[delHost] + if !found { + iClient.DeleteARecord(delHost, ipAddr, netview, cidr) + return "", fmt.Errorf( + "Couldn't find reference to host '%s' "+ + "while trying to update CNAME to A record.", delHost) + } + aRecord = host + // Delete the CNAME record first + iClient.DeleteCNAMERecord(host, ipAddr, netview, cidr) + // Update the A record + log.Infof("Updating A record for '%s' to be '%s'.", delHost, host) + newRef, _ := iClient.conn.UpdateObject(obj, oldRef) + iClient.recordRef[host] = newRef + } else { + // Update all subsequent CNAMEs to point to new A record + obj := ibclient.NewRecordCNAME( + ibclient.RecordCNAME{ + Name: host, + Canonical: aRecord, + View: netview, + Ea: iClient.ea, + }, + ) + oldRef, found := iClient.recordRef[host] + if !found { + return "", fmt.Errorf( + "Couldn't find reference to host '%s' "+ + "while trying to update CNAME.", host) + } + log.Infof("Updating CNAME record for '%s' to point at '%s'.", host, aRecord) + newRef, _ := iClient.conn.UpdateObject(obj, oldRef) + iClient.recordRef[host] = newRef + } + } + return aRecord, nil +} + +// GetNextAddr reserves and returns the next available address in the network +func (iClient *IBloxClient) GetNextAddr(netview, cidr string) string { + nextAddr, err := iClient.objMgr.AllocateIP(netview, cidr, "", "", "", iClient.ea) + if err != nil { + return "" + } + return ipFromRef(nextAddr.IPAddress) +} + +// ReleaseAddr releases an IP address back to Infoblox +func (iClient *IBloxClient) ReleaseAddr(netview, cidr, ipAddr string) { + iClient.objMgr.ReleaseIP(netview, cidr, ipAddr, "") +} + +// AllocateIPAddress an IP address back to Infoblox +func (iClient *IBloxClient) AllocateIPAddress(cidr, ipAddr string) bool { + return true +} + +// GetIPAddress an IP address back to Infoblox +func (iClient *IBloxClient) GetIPAddress(hostname string) string { + return "PASS" +} + +// GetNextIPAddress an IP address back to Infoblox +func (iClient *IBloxClient) GetNextIPAddress(cidr string) string { + return "PASS" +} + +// ReleaseIPAddress an IP address back to Infoblox +func (iClient *IBloxClient) ReleaseIPAddress(ipAddr string) { + return +} + +// GetRecords returns the current Infoblox records +func (iClient *IBloxClient) GetRecords() *store.Store { + st := store.NewStore() + var zones []ibclient.ZoneAuth + var err error + + obj := ibclient.NewZoneAuth(ibclient.ZoneAuth{}) + err = iClient.conn.GetObject(obj, "", &zones) + if err != nil { + return st + } + + for _, zone := range zones { + // Get A records + var resA []ibclient.RecordA + objA := ibclient.NewRecordA( + ibclient.RecordA{ + Zone: zone.Fqdn, + }, + ) + resA, err = iClient.getARecord(objA) + if err != nil { + return st + } + for _, res := range resA { + cidr := iClient.getNetworkCIDR(res.View, res.Ipv4Addr) + st.AddRecord(res.Ipv4Addr, res.Name, "A", res.View, cidr) + } + + // Get CNAME records + var resC []ibclient.RecordCNAME + objC := ibclient.NewRecordCNAME( + ibclient.RecordCNAME{ + Zone: zone.Fqdn, + }, + ) + resC, err = iClient.getCNAMERecord(objC) + if err != nil { + return st + } + for _, res := range resC { + var ipAddr string + // Find the A record for this CNAME; get its IP address + for _, aRec := range resA { + if aRec.Name == res.Canonical { + ipAddr = aRec.Ipv4Addr + } + } + cidr := iClient.getNetworkCIDR(res.View, ipAddr) + st.AddRecord(ipAddr, res.Name, "CNAME", res.View, cidr) + } + } + return st +} + +// FIXME (berman): +// The following methods call GetObject on a specific Record object. However, since we +// had to override infoblox-go-client's API request URL, we get back all objects with +// our configured Extensible Attribute, rather than just the single object. The functions +// will loop through all returned objects until we find the matching object. + +// Returns an A record from Infoblox +func (iClient *IBloxClient) getARecord( + obj *ibclient.RecordA, +) ([]ibclient.RecordA, error) { + var res, ret []ibclient.RecordA + err := iClient.conn.GetObject(obj, "", &res) + if err != nil { + return nil, err + } + for _, o := range res { + if o.Name == obj.Name && o.Ipv4Addr == obj.Ipv4Addr && o.View == obj.View { + ret = append(ret, o) + } else if obj.Name == "" && o.Zone == obj.Zone { + ret = append(ret, o) + } + } + return ret, nil +} + +// Returns a CNAME record from Infoblox +func (iClient *IBloxClient) getCNAMERecord( + obj *ibclient.RecordCNAME, +) ([]ibclient.RecordCNAME, error) { + var res, ret []ibclient.RecordCNAME + err := iClient.conn.GetObject(obj, "", &res) + if err != nil { + return nil, err + } + + for _, o := range res { + if o.Name == obj.Name && o.View == obj.View { + ret = append(ret, o) + } else if obj.Name == "" && o.Zone == obj.Zone { + ret = append(ret, o) + } + } + return ret, nil +} + +// Returns the network CIDR for an IP in a netview +func (iClient *IBloxClient) getNetworkCIDR(netview, ip string) string { + var res []ibclient.Network + var cidr string + network := ibclient.NewNetwork(ibclient.Network{NetviewName: netview}) + iClient.conn.GetObject(network, "", &res) + + for _, n := range res { + _, netCidr, _ := net.ParseCIDR(n.Cidr) + addr := net.ParseIP(ip) + if netCidr.Contains(addr) { + cidr = n.Cidr + break + } + } + return cidr +} + +// Extracts the IP address from a Fixed Address reference +func ipFromRef(ref string) string { + split := strings.Split(ref, ":") + ipAndNetview := split[len(split)-1] + ip := strings.Split(ipAndNetview, "/")[0] + return ip +} + +// FIXME (berman): +// infoblox-go-client does not properly create the URL string when we need +// to request a resource that has an extattr. This code is here to format the URL +// how we need it to be formatted. We also needed to override BuildRequest from infoblox-go-client +// in order to ensure that OUR BuildUrl function is called, rather than the +// WapiRequestBuilder.BuildUrl that would be called if we were to use the go-client's method + +// Wrapper around WapiRequestBuilder +type requestBuilder struct { + *ibclient.WapiRequestBuilder + HostConfig ibclient.HostConfig +} + +func (rb *requestBuilder) Init(cfg ibclient.HostConfig) { + rb.HostConfig = cfg +} + +// Override function to pass in Extensible Attribute to request +func (rb *requestBuilder) BuildUrl( + r ibclient.RequestType, + objType, + ref string, + returnFields []string, +) string { + aRec := "record:a" + cnameRec := "record:cname" + + path := []string{"wapi", "v" + rb.HostConfig.Version} + if len(ref) > 0 { + path = append(path, ref) + } else { + path = append(path, objType) + } + + qry := "" + vals := url.Values{} + if r == ibclient.GET { + if objType == aRec || objType == cnameRec { + vals.Set("*"+EAKey+"~", EAVal) + } + if len(returnFields) > 0 { + vals.Set("_return_fields", strings.Join(returnFields, ",")) + } + qry = vals.Encode() + } + + u := url.URL{ + Scheme: "https", + Host: rb.HostConfig.Host + ":" + rb.HostConfig.Port, + Path: strings.Join(path, "/"), + RawQuery: qry, + } + return u.String() +} + +// Override function to call our version of BuildUrl +func (rb *requestBuilder) BuildRequest( + r ibclient.RequestType, + obj ibclient.IBObject, + ref string, +) (*http.Request, error) { + var objType string + var returnFields []string + if obj != nil { + objType = obj.ObjectType() + returnFields = obj.ReturnFields() + } + url := rb.BuildUrl(r, objType, ref, returnFields) + + var body []byte + if obj != nil { + // Uses ibclient.WapiRequestBuilder method + body = rb.BuildBody(r, obj) + } + + req, err := http.NewRequest(toString(r), url, bytes.NewBuffer(body)) + if err != nil { + log.Errorf("Error building HTTP request: %v", err) + return req, err + } + req.Header.Set("Content-Type", "application/json") + req.SetBasicAuth(rb.HostConfig.Username, rb.HostConfig.Password) + + return req, nil +} + +// Converts an ibclient.RequestType to its string representation +func toString(r ibclient.RequestType) string { + switch r { + case ibclient.CREATE: + return "POST" + case ibclient.GET: + return "GET" + case ibclient.DELETE: + return "DELETE" + case ibclient.UPDATE: + return "PUT" + } + + return "" +} diff --git a/pkg/manager/manager.go b/pkg/manager/manager.go index 33a513e..917c7c8 100644 --- a/pkg/manager/manager.go +++ b/pkg/manager/manager.go @@ -5,9 +5,9 @@ import log "github.com/f5devcentral/f5-ipam-controller/pkg/vlogger" // Manager defines the interface that the IPAM system should implement type Manager interface { // Creates an A record - CreateARecord(hostname, ipAddr string) bool + CreateARecord(params ...interface{}) bool // Deletes an A record and releases the IP address - DeleteARecord(hostname, ipAddr string) + DeleteARecord(params ...interface{}) // Gets IP Address associated with hostname GetIPAddress(hostname string) string // Gets and reserves the next available IP address @@ -18,11 +18,17 @@ type Manager interface { ReleaseIPAddress(ipAddr string) } -const F5IPAMProvider = "f5-ip-provider" +// Search String for Default Static IP Approach +const F5IPAMProvider = "f5" + +// search string for Infoblox Provider +const INFOBLOXProvider = "infoblox" +const INFOBLOXcmpType = "f5" type Params struct { Provider string IPAMManagerParams + InfobloxParams } func NewManager(params Params) Manager { @@ -31,6 +37,12 @@ func NewManager(params Params) Manager { log.Debugf("[MGR] Creating Manager with Provider: %v", F5IPAMProvider) f5IPAMParams := IPAMManagerParams{Range: params.Range} return NewIPAMManager(f5IPAMParams) + case INFOBLOXProvider: + log.Debugf("[MGR] Creating Manager with Provider: %v", INFOBLOXProvider) + ibclient, err := NewInfobloxManager(¶ms.InfobloxParams, INFOBLOXcmpType) + if err == nil { + return ibclient + } default: log.Errorf("[MGR] Unknown Provider: %v", params.Provider) } diff --git a/vendor/github.com/F5Networks/f5-ipam-ctlr/LICENSE b/vendor/github.com/F5Networks/f5-ipam-ctlr/LICENSE new file mode 100644 index 0000000..08fec80 --- /dev/null +++ b/vendor/github.com/F5Networks/f5-ipam-ctlr/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 2018 F5 Networks + + 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/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/store/store.go b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/store/store.go new file mode 100644 index 0000000..53a086c --- /dev/null +++ b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/store/store.go @@ -0,0 +1,118 @@ +/*- + * Copyright (c) 2018, F5 Networks, Inc. + * + * 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 store + +import "sort" + +// Store is a map of all IP addresses and their corresponding hostnames, netviews, and CIDRs +type Store struct { + Records map[string]HostSet + Netviews map[string]string + Cidrs map[string]string +} + +// HostSet is a map of hosts (value is record type) +type HostSet map[string]string + +// NewStore allocates a new store for the controller +func NewStore() *Store { + var st Store + st.Records = make(map[string]HostSet) + st.Netviews = make(map[string]string) + st.Cidrs = make(map[string]string) + return &st +} + +// AddRecord adds/updates a record for an IP and hosts +func (st *Store) AddRecord(ip, host, recordType, netview, cidr string) { + if _, found := st.Records[ip]; found { + if _, ok := st.Records[ip][host]; !ok { + st.Records[ip][host] = recordType + st.Netviews[ip] = netview + st.Cidrs[ip] = cidr + } + } else { + st.overwriteRecord(ip, host, recordType, netview, cidr) + } +} + +// Overwrites the contents of a record +func (st *Store) overwriteRecord(ip, host, recordType, netview, cidr string) { + st.Records[ip] = make(HostSet) + st.Records[ip][host] = recordType + st.Netviews[ip] = netview + st.Cidrs[ip] = cidr +} + +// Deletes a record for an IP address +func (st *Store) deleteRecord(ip string) { + delete(st.Records, ip) + delete(st.Netviews, ip) + delete(st.Cidrs, ip) +} + +// Deletes a host from a record +func (st *Store) deleteHost(delHost string) { + for ip, hosts := range st.Records { + if _, ok := hosts[delHost]; ok { + delete(hosts, delHost) + if len(hosts) == 0 { + st.deleteRecord(ip) + } + return + } + } +} + +// DeleteHosts deletes hosts from records +func (st *Store) DeleteHosts(delHosts []string) { + for _, delHost := range delHosts { + st.deleteHost(delHost) + } +} + +// Returns the hosts for a given IP address +func (st *Store) getHosts(ip string) []string { + var hosts []string + if _, found := st.Records[ip]; found { + for host := range st.Records[ip] { + hosts = append(hosts, host) + } + sort.Strings(hosts) + return hosts + } + return []string{} +} + +// GetIP returns the IP address for a given host +func (st *Store) GetIP(host string) string { + for ip, hosts := range st.Records { + if _, ok := hosts[host]; ok { + return ip + } + } + return "" +} + +func contains(slice []string, val string) bool { + for _, s := range slice { + if s == val { + return true + } + } + return false +} diff --git a/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/README.md b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/README.md new file mode 100644 index 0000000..a172046 --- /dev/null +++ b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/README.md @@ -0,0 +1,353 @@ +# vlogger + + import "github.com/F5Networks/k8s-bigip-ctlr/pkg/vlogger" + +Package vlogger implements an interface around basic logging features so that +end-user and library writers can code to the interface without worrying about +the specific type of logging package that is being used. + + +### LIBRARY USAGE + +To support logging in a user-defined library, you need to include the vlogger +package. Once that is included, you can simply call one of the following +package-level functions: + + func Debug(msg string) + func Debugf(format string, params ... interface{}) + func Info(msg string) + func Infof(format string, params ... interface{}) + func Warning(msg string) + func Warningf(format string, params ... interface{}) + func Error(msg string) + func Errorf(format string, params ... interface{}) + func Critical(msg string) + func Criticalf(format string, params ... interface{}) + func Fatal(msg string) + func Fatalf(format string, params ... interface{}) + func Panic(msg string) + func Panicf(format string, params ... interface{}) + + +### APPLICATION USAGE + +Logging in the main application is similar to logging in a library. However, +additional steps must be taken to setup and breakdown the vlogger. + +When creating an application, you should specify the concrete vlogger that you +would like to use in your main module's init function. This will guarantee that +the vlogger will be available for any library that supports vlogger (otherwise +logging will default to the console). + +The following types of loggers are currently provided as subpackages: + + func NewConsoleLogger() Logger + func NewSyslogLogger(facility syslog.Priority, progname string) Logger + func NewSeelogLogger(filename string) Logger + func NewLogrusLogger() Logger + +The first two use standard GO packages to implement logging. The last two +uses more sophisticated third-party library that supports features such +as multiple logging streams and various levels of filtering. Logging using +these last two packages can be directed to any combination of outputs including +syslog. Users can also provide their own implementations by adhering to the +vlogger interface. + +Some logging subpackages have an extended version of the New function that +provides additional customization of that particular logger. These functions +end with an 'Ext' suffix (for instance, NewConsoleLoggerExt). + +Logger types need to be registered for use by the vlogger package-level +functions using the following call: + + func RegisterLogger(minLogLevel, maxLogLevel, Logger) + +The RegisterLogger function allows you to use different loggers for different +log levels (for instance, sending critical messages to a blocking logger while +sending all other messages to a non-blocking version). + +For proper cleanup, the main routine should have a defer statement that calls +the vlogger Close() function: + + func Close() + + +### LOG LEVELS + +To control the global logging level, several package level functions are +provided: + + SetLogLevel(level LogLevel) + GetLogLevel() LogLevel + +The following log levels are currently defined (do not make an assumption of the +values assigned to these constants): + + LL_DEBUG + LL_INFO + LL_WARNING + LL_ERROR + LL_CRITICAL + +Two related defines can also be used (mainly as a convenience for logger registration): + + LL_MIN_LEVEL + LL_MAX_LEVEL + +Note that certain concrete packages will have their own fine-grained filtering +for logging. However, the package-level controls will supercede these finer +controls. + + +### COMPATIBILITY ISSUES + +Log levels do not always map 1-to-1 with the underlying 3rd-party logging library. +The issues mainly involve the LL_CRITICAL level. Packages that do not provide this +level will be mapped to LL_ERROR. + + +### EXAMPLE + +The following is a simple example of an application that sends several log +statements to the console: + +```go + package main + + import ( + log "github.com/F5Networks/k8s-bigip-ctlr/pkg/vlogger" + "github.com/F5Networks/k8s-bigip-ctlr/pkg/vlogger/console" + + func init() { + // Log all messages to the user's console + log.RegisterLogger(log.LL_MIN_LEVEL, log.LL_MAX_LEVEL, console.NewConsoleLogger()) + // only report errors at the LL_INFO level and above + log.SetLogLevel(log.LL_INFO) + } + + func main() { + defer log.Close() + + log.Debug("This debug message won't print"); + log.Info("This is an info message") + log.Warning("This is a warning message") + log.Errorf("This is an error message with %v", "formatting") + log.Criticalf("This is a critical message %v formatting", "with") + log.Fatal("This is a fatal message") + log.Info("This will never print due to log.Fatal() causing the application to exit") + } +``` + + +### MODULES + +log.go: + + This module provides the generic interface that end-user libraries and apps should program to. + +## Usage + +#### func RegisterLogger + +```go +func RegisterLogger(minLogLevel, maxLogLevel LogLevel, log Logger) +``` +RegisterLogger must be called to map a concrete logger object with each log +level. + +#### func Close + +```go +func Close() +``` +Close informs the configured loggers that they are being closed and should +cleanup (for instance, flushing any queued log messages) + +#### func Panic + +```go +func Panic(msg string) +``` +Panic sends a CRITICAL message to the logger object and then calls panic. **NOTE: +This call should not be made in packages that are meant to serve as libraries +for other developers.** + +#### func Panicf + +```go +func Panicf(format string, params ...interface{}) +``` +Panicf sends a formatted CRITICAL message to the logger object and then calls +panic. **NOTE: This call should not be made in packages that are meant to serve as +libraries for other developers.** + +#### func Fatal + +```go +func Fatal(msg string) +``` +Fatal sends a CRITICAL message to the logger object and then exits. **NOTE: This +call should not be made in packages that are meant to serve as libraries for +other developers.** + +#### func Fatalf + +```go +func Fatalf(format string, params ...interface{}) +``` +Fatalf sends a formatted CRITICAL message to the logger object and then exits. +**NOTE: This call should not be made in packages that are meant to serve as +libraries for other developers.** + +#### func Critical + +```go +func Critical(msg string) +``` +Critical sends a message to the logger object to record critical level +statements (these indicate conditions that should never occur and might cause a +failure/crash of the executing program or unexpected outcome from the +requested action). + +#### func Criticalf + +```go +func Criticalf(format string, params ...interface{}) +``` +Criticalf formats a message before sending it to the logger object to record +critical level statements (these indicate conditions that should never occur and +might cause a failure/crash of the executing program or unexpected outcome +from the requested action). + +#### func Error + +```go +func Error(msg string) +``` +Error sends a message to the logger object to record error level statements +(these indicate conditions that should not occur and may indicate a failure in +performing the requested action). + +#### func Errorf + +```go +func Errorf(format string, params ...interface{}) +``` +Errorf formats a message before sending it to the logger object to record error +level statements (these indicate conditions that should not occur and may +indicate a failure in performing the requested action). + +#### func Warning + +```go +func Warning(msg string) +``` +Warning sends a message to the logger object to record warning level statements +(these indication conditions that are unexpected or may cause issues but are not +normally going to affect the program execution). + +#### func Warningf + +```go +func Warningf(format string, params ...interface{}) +``` +Warningf formats a message before sending it to the logger object to record +warning level statements (these indication conditions that are unexpected or may +cause issues but are not normally going to affect the program execution). + +#### func Info + +```go +func Info(msg string) +``` +Info sends a message to the logger object to record informational level +statements (these should be statements that can normally be logged without +causing performance issues). + +#### func Infof + +```go +func Infof(format string, params ...interface{}) +``` +Infof formats a message before sending it to the logger object to record +informational level statements (there should be statements that can normally be +logged without causing performance issues). + +#### func Debug + +```go +func Debug(msg string) +``` +Debug sends a message to the logger object to record debug/trace level +statements + +#### func Debugf + +```go +func Debugf(format string, params ...interface{}) +``` +Debugf formats a message before sending it to the logger object to record +debug/trace level statements + +#### func SetLogLevel + +```go +func SetLogLevel(level LogLevel) +``` +SetLogLevel sets the current package-level filtering + +#### func GetLogLevel + +```go +func GetLogLevel() LogLevel +``` +GetLogLevel returns the current package-level filtering + +#### type LogLevel + +```go +type LogLevel int +``` + +LogLevel is used for global (package-level) filtering of log messages based on +their priority (this filtering is applied before all other filtering which might +be provided by the concrete logger). + +```go +const ( + // Must be in sequential ascending order based on priority + // (higher priorities have higher numeric values) + LL_DEBUG LogLevel = iota + LL_INFO + LL_WARNING + LL_ERROR + LL_CRITICAL + LL_LOGLEVEL_SIZE + LL_MIN_LEVEL = LL_DEBUG + LL_MAX_LEVEL = LL_LOGLEVEL_SIZE - 1 +) +``` + +#### type Logger + +```go +type Logger interface { + Debug(string) + Debugf(string, ...interface{}) + Info(string) + Infof(string, ...interface{}) + Warning(string) + Warningf(string, ...interface{}) + Error(string) + Errorf(string, ...interface{}) + Critical(string) + Criticalf(string, ...interface{}) + GetLogLevel() syslog.Priority + SetLogLevel(syslog.Priority) + Close() +} +``` + +Generic interface that all concrete loggers must implement. Using this interface +directly isolates user code from a particular logger implementation. + diff --git a/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/doc.go b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/doc.go new file mode 100644 index 0000000..442c62e --- /dev/null +++ b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/doc.go @@ -0,0 +1,146 @@ +// Copyright 2018 F5 Networks +// +// 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 vlogger implements an interface around basic logging features +so that end-user and library writers can code to the interface without +worrying about the specific type of logging package that is being used. + +LIBRARY USAGE + +To support logging in a user-defined library, you need to include the +vlogger package. Once that is included, you can simply call one of the +following package-level functions: + + func Debug(msg string) + func Debugf(format string, params ... interface{}) + func Info(msg string) + func Infof(format string, params ... interface{}) + func Warning(msg string) + func Warningf(format string, params ... interface{}) + func Error(msg string) + func Errorf(format string, params ... interface{}) + func Critical(msg string) + func Criticalf(format string, params ... interface{}) + func Fatal(msg string) + func Fatalf(format string, params ... interface{}) + func Panic(msg string) + func Panicf(format string, params ... interface{}) + +APPLICATION USAGE + +Logging in the main application is similar to logging in a library. However, +additional steps must be taken to setup and breakdown the vlogger. + +When creating an application, you should specify the concrete vlogger that +you would like to use in your main module's init function. This will +guarantee that the vlogger will be available for any library that supports +vlogger (otherwise logging will default to the console). + +The following types of loggers are currently provided as subpackages: + + func NewConsoleLogger() Logger + func NewSyslogLogger(facility syslog.Priority, progname string) Logger + func NewSeelogLogger(filename string) Logger + func NewLogrusLogger() Logger + +The first two use standard GO packages to implement logging. The last two +uses more sophisticated third-party library that supports features such +as multiple logging streams and various levels of filtering. Logging using +these last two packages can be directed to any combination of outputs including +syslog. Users can provide their own implementations by adhering to the +vlogger interface. + +Some logging subpackages have an extended version of the New function that +provides additional customization of that particular logger. These functions +end with an 'Ext' suffix (for instance, NewConsoleLoggerExt). + +Logger types need to be registered for use by the vlogger package-level +functions using the following call: + + func RegisterLogger(minLogLevel, maxLogLevel, Logger) + +The RegisterLogger function allows you to use different loggers for +different log levels (for instance, sending critical messages to a +blocking logger while sending all other messages to a non-blocking version). + +For proper cleanup, the main routine should have a defer statement that calls the +vlogger Close() function: + + func Close() + +LOG LEVELS + +To control the global logging level, several package level functions are provided: + + SetLogLevel(level LogLevel) + GetLogLevel() LogLevel + +The following log levels are currently defined (do not make an assumption of the +values assigned to these constants): + + LL_DEBUG + LL_INFO + LL_WARNING + LL_ERROR + LL_CRITICAL + +Two related defines can also be used (mainly as a convenience for logger registration): + + LL_MIN_LEVEL + LL_MAX_LEVEL + +Note that certain concrete packages will have their own fine-grained filtering for +logging. However, the package-level controls will supercede these finer controls. + +COMPATIBILITY ISSUES + +Log levels do not always map 1-to-1 with the underlying 3rd-party logging library. +The issues mainly involve the LL_CRITICAL level. Packages that do not provide this +level will be mapped to LL_ERROR. + +EXAMPLE + +The following is a simple example of an application that sends several log statements +to the console: + + package main + + import ( + log "github.com/F5Networks/k8s-bigip-ctlr/pkg/vlogger" + "github.com/F5Networks/k8s-bigip-ctlr/pkg/vlogger/console" + + func init() { + // Log all messages to the user's console + log.RegisterLogger(log.LL_MIN_LEVEL, log.LL_MAX_LEVEL, console.NewConsoleLogger()) + // only report errors at the LL_INFO level and above + log.SetLogLevel(log.LL_INFO) + } + + func main() { + defer log.Close() + + log.Debug("This debug message won't print"); + log.Info("This is an info message") + log.Warning("This is a warning message") + log.Errorf("This is an error message with %v", "formatting") + log.Criticalf("This is a critical message %v formatting", "with") + log.Fatal("This is a fatal message") + log.Info("This will never print due to log.Fatal() causing the application to exit") + } + +MODULES + +*/ +package vlogger diff --git a/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/log.go b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/log.go new file mode 100644 index 0000000..b65e933 --- /dev/null +++ b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/log.go @@ -0,0 +1,278 @@ +// Copyright 2018 F5 Networks +// +// 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. + +//log.go: +// This module provides the generic interface that end-user libraries and apps should program to. +// +package vlogger + +import ( + "fmt" + "log/syslog" // For LOG level definitions + "os" + "strings" +) + +// LogLevel is used for global (package-level) filtering of log messages based on their priority +// (this filtering is applied before all other filtering which might be provided by the concrete logger). +type LogLevel int + +const ( + // Must be in sequential ascending order based on priority + // (higher priorities have higher numeric values) + LL_DEBUG = iota + LL_INFO + LL_WARNING + LL_ERROR + LL_CRITICAL + LL_LOGLEVEL_SIZE + + LL_MIN_LEVEL = LL_DEBUG + LL_MAX_LEVEL = LL_LOGLEVEL_SIZE - 1 +) + +// String converts a LogLevel to a string for serializing. +func (ll LogLevel) String() string { + switch ll { + case LL_DEBUG: + return "debug" + case LL_INFO: + return "info" + case LL_WARNING: + return "warning" + case LL_ERROR: + return "error" + case LL_CRITICAL: + return "critical" + default: + return "invalid" + } +} + +// NewLogLevel converts a string to a log level. +func NewLogLevel(s string) *LogLevel { + var r LogLevel + s = strings.ToLower(s) + switch s { + case "": + return nil + case "debug": + r = LL_DEBUG + case "info": + r = LL_INFO + case "warning": + r = LL_WARNING + case "error": + r = LL_ERROR + case "critical": + r = LL_CRITICAL + default: + return nil + } + return &r +} + +// MarshalJSON converts a LogLevel to a quoted string for JSON output. +func (ll LogLevel) MarshalJSON() ([]byte, error) { + s := ll.String() + return []byte("\"" + s + "\""), nil +} + +func (ll *LogLevel) UnmarshalJSON(data []byte) error { + s := string(data) + s = strings.Trim(s, "\"") + newll := NewLogLevel(s) + if newll == nil { + return fmt.Errorf("Unable to unmarshal %s to Log Level.", string(data)) + } + *ll = *newll + return nil +} + +// Generic interface that all concrete loggers must implement. Using this interface directly +// isolates user code from a particular logger implementation. +type ( + Logger interface { + Debug(string) + Debugf(string, ...interface{}) + Info(string) + Infof(string, ...interface{}) + Warning(string) + Warningf(string, ...interface{}) + Error(string) + Errorf(string, ...interface{}) + Critical(string) + Criticalf(string, ...interface{}) + GetLogLevel() syslog.Priority + SetLogLevel(syslog.Priority) + Close() + } +) + +var ( + // vlog specifies loggers associated with each log level (could all be the same logger). + vlog [LL_LOGLEVEL_SIZE]Logger + + // logLevel indicates the current package-level filtering being applied + // (may be further restricted by specific concrete loggers). + logLevel LogLevel = LL_DEBUG + + // logLevelToSyslogLevel maps vlogger log levels to the internal representation used + // by the implementations (which use syslog's definitions). + logLevelToSyslogLevel = [LL_LOGLEVEL_SIZE]syslog.Priority{ + syslog.LOG_DEBUG, + syslog.LOG_INFO, + syslog.LOG_WARNING, + syslog.LOG_ERR, + syslog.LOG_CRIT, + } +) + +// RegisterLogger must be called to map a concrete logger object with each log level. +func RegisterLogger(minLogLevel, maxLogLevel LogLevel, log Logger) { + for level := minLogLevel; level <= maxLogLevel; level++ { + vlog[level] = log + } +} + +// Debug sends a message to the logger object to record debug/trace level statements +func Debug(msg string) { + vlog[LL_DEBUG].Debug(msg) +} + +// Debugf formats a message before sending it to the logger object to record +// debug/trace level statements +func Debugf(format string, params ...interface{}) { + vlog[LL_DEBUG].Debugf(format, params...) +} + +// Info sends a message to the logger object to record informational level statements +// (these should be statements that can normally be logged without causing performance +// issues). +func Info(msg string) { + vlog[LL_INFO].Info(msg) +} + +// Infof formats a message before sending it to the logger object to record +// informational level statements (there should be statements that can normally +// be logged without causing performance issues). +func Infof(format string, params ...interface{}) { + vlog[LL_INFO].Infof(format, params...) +} + +// Warning sends a message to the logger object to record warning level statements +// (these indication conditions that are unexpected or may cause issues but are not +// normally going to affect the program execution). +func Warning(msg string) { + vlog[LL_WARNING].Warning(msg) +} + +// Warningf formats a message before sending it to the logger object to record +// warning level statements (these indication conditions that are unexpected or +// may cause issues but are not normally going to affect the program execution). +func Warningf(format string, params ...interface{}) { + vlog[LL_WARNING].Warningf(format, params...) +} + +// Error sends a message to the logger object to record error level statements +// (these indicate conditions that should not occur and may indicate a failure +// in performing the requested action). +func Error(msg string) { + vlog[LL_ERROR].Error(msg) +} + +// Errorf formats a message before sending it to the logger object to record +// error level statements (these indicate conditions that should not occur +// and may indicate a failure in performing the requested action). +func Errorf(format string, params ...interface{}) { + vlog[LL_ERROR].Errorf(format, params...) +} + +// Critical sends a message to the logger object to record critical level statements +// (these indicate conditions that should never occur and might cause a failure/crash +// of the executing program or unexpected outcome from the requested action). +func Critical(msg string) { + vlog[LL_CRITICAL].Critical(msg) +} + +// Criticalf formats a message before sending it to the logger object to record +// critical level statements (these indicate conditions that should never occur +// and might cause a failure/crash of the executing program or unexpected +// outcome from the requested action). +func Criticalf(format string, params ...interface{}) { + vlog[LL_CRITICAL].Criticalf(format, params...) +} + +// Fatal sends a CRITICAL message to the logger object and then exits. +// NOTE: This call should not be made in packages that are meant to serve +// as libraries for other developers. +func Fatal(msg string) { + vlog[LL_CRITICAL].Critical(msg) + Close() + os.Exit(1) +} + +// Fatalf sends a formatted CRITICAL message to the logger object and then exits. +// NOTE: This call should not be made in packages that are meant to serve +// as libraries for other developers. +func Fatalf(format string, params ...interface{}) { + vlog[LL_CRITICAL].Criticalf(format, params...) + Close() + os.Exit(1) +} + +// Panic sends a CRITICAL message to the logger object and then calls panic. +// NOTE: This call should not be made in packages that are meant to serve +// as libraries for other developers. +func Panic(msg string) { + vlog[LL_CRITICAL].Critical(msg) + panic(msg) +} + +// Panicf sends a formatted CRITICAL message to the logger object and then calls panic. +// NOTE: This call should not be made in packages that are meant to serve +// as libraries for other developers. +func Panicf(format string, params ...interface{}) { + msg := fmt.Sprintf(format, params...) + vlog[LL_CRITICAL].Critical(msg) + panic(msg) +} + +// SetLogLevel sets the current package-level filtering +func SetLogLevel(level LogLevel) { + logLevel = level + + // Update all loggers to the new level + slLogLevel := logLevelToSyslogLevel[logLevel] + for i, _ := range vlog { + if vlog[i] != nil { + vlog[i].SetLogLevel(slLogLevel) + } + } +} + +// GetLogLevel returns the current package-level filtering +func GetLogLevel() LogLevel { + return logLevel +} + +// Close informs the configured loggers that they are being closed and +// should cleanup (for instance, flushing any queued log messages) +func Close() { + for i, _ := range vlog { + if vlog[i] != nil { + vlog[i].Close() + } + } +} diff --git a/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/log_null.go b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/log_null.go new file mode 100644 index 0000000..188f490 --- /dev/null +++ b/vendor/github.com/F5Networks/f5-ipam-ctlr/pkg/vlogger/log_null.go @@ -0,0 +1,57 @@ +// Copyright 2018 F5 Networks +// +// 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. + +//log_null.go: +// Turns off all logging. +// +package vlogger + +import "log/syslog" + +type ( + nullLogger struct { + slLogLevel syslog.Priority + } +) + +// newNullLogger creates a logger object that drops all log messages. +func newNullLogger() *nullLogger { + return &nullLogger{ + slLogLevel: syslog.LOG_DEBUG, + } +} + +func init() { + // Keeps the global interface from starting out with an + // undefined implementation. + RegisterLogger(LL_MIN_LEVEL, LL_MAX_LEVEL, newNullLogger()) +} + +func (cl *nullLogger) Debug(msg string) {} +func (cl *nullLogger) Debugf(format string, params ...interface{}) {} +func (cl *nullLogger) Info(msg string) {} +func (cl *nullLogger) Infof(format string, params ...interface{}) {} +func (cl *nullLogger) Warning(msg string) {} +func (cl *nullLogger) Warningf(format string, params ...interface{}) {} +func (cl *nullLogger) Error(msg string) {} +func (cl *nullLogger) Errorf(format string, params ...interface{}) {} +func (cl *nullLogger) Critical(msg string) {} +func (cl *nullLogger) Criticalf(format string, params ...interface{}) {} +func (cl *nullLogger) Close() {} +func (cl *nullLogger) SetLogLevel(slLogLevel syslog.Priority) { + cl.slLogLevel = slLogLevel +} +func (cl *nullLogger) GetLogLevel() syslog.Priority { + return cl.slLogLevel +} diff --git a/vendor/github.com/infobloxopen/infoblox-go-client/.gitignore b/vendor/github.com/infobloxopen/infoblox-go-client/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/vendor/github.com/infobloxopen/infoblox-go-client/.travis.yml b/vendor/github.com/infobloxopen/infoblox-go-client/.travis.yml new file mode 100644 index 0000000..3153273 --- /dev/null +++ b/vendor/github.com/infobloxopen/infoblox-go-client/.travis.yml @@ -0,0 +1,13 @@ +language: go + +go: + - 1.7.x + - 1.8 + - 1.9 + +env: + - GO111MODULE=on + +install: true + +script: go test -v ./... diff --git a/vendor/github.com/infobloxopen/infoblox-go-client/Gopkg.lock b/vendor/github.com/infobloxopen/infoblox-go-client/Gopkg.lock new file mode 100644 index 0000000..8ee9637 --- /dev/null +++ b/vendor/github.com/infobloxopen/infoblox-go-client/Gopkg.lock @@ -0,0 +1,183 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + branch = "master" + digest = "1:59392ed8afb901aab4287d4894df8191722e34f3957716f4350c8c133ce99046" + name = "github.com/hpcloud/tail" + packages = [ + ".", + "ratelimiter", + "util", + "watch", + "winfile", + ] + pruneopts = "UT" + revision = "a1dbeea552b7c8df4b542c66073e393de198a800" + +[[projects]] + digest = "1:0a69a1c0db3591fcefb47f115b224592c8dfa4368b7ba9fae509d5e16cdc95c8" + name = "github.com/konsorten/go-windows-terminal-sequences" + packages = ["."] + pruneopts = "UT" + revision = "5c8c8bd35d3832f5d134ae1e1e375b69a4d25242" + version = "v1.0.1" + +[[projects]] + digest = "1:5f4b78246f0bcb105b1e3b2b9e22b52a57cd02f57a8078572fe27c62f4a75ff7" + name = "github.com/onsi/ginkgo" + packages = [ + ".", + "config", + "internal/codelocation", + "internal/containernode", + "internal/failer", + "internal/leafnodes", + "internal/remote", + "internal/spec", + "internal/spec_iterator", + "internal/specrunner", + "internal/suite", + "internal/testingtproxy", + "internal/writer", + "reporters", + "reporters/stenographer", + "reporters/stenographer/support/go-colorable", + "reporters/stenographer/support/go-isatty", + "types", + ] + pruneopts = "UT" + revision = "2e1be8f7d90e9d3e3e58b0ce470f2f14d075406f" + version = "v1.7.0" + +[[projects]] + digest = "1:7a137fb7718928e473b7d805434ae563ec41790d3d227cdc64e8b14d1cab8a1f" + name = "github.com/onsi/gomega" + packages = [ + ".", + "format", + "internal/assertion", + "internal/asyncassertion", + "internal/oraclematcher", + "internal/testingtsupport", + "matchers", + "matchers/support/goraph/bipartitegraph", + "matchers/support/goraph/edge", + "matchers/support/goraph/node", + "matchers/support/goraph/util", + "types", + ] + pruneopts = "UT" + revision = "65fb64232476ad9046e57c26cd0bff3d3a8dc6cd" + version = "v1.4.3" + +[[projects]] + digest = "1:87c2e02fb01c27060ccc5ba7c5a407cc91147726f8f40b70cceeedbc52b1f3a8" + name = "github.com/sirupsen/logrus" + packages = ["."] + pruneopts = "UT" + revision = "e1e72e9de974bd926e5c56f83753fba2df402ce5" + version = "v1.3.0" + +[[projects]] + branch = "master" + digest = "1:38f553aff0273ad6f367cb0a0f8b6eecbaef8dc6cb8b50e57b6a81c1d5b1e332" + name = "golang.org/x/crypto" + packages = ["ssh/terminal"] + pruneopts = "UT" + revision = "64072686203f69e3fd20143576b27200f18ab0fa" + +[[projects]] + branch = "master" + digest = "1:3d6c20b6e507bfdc8c5fafdaf797e6573e66fd9efcd5b48798b93ad2c3176ef3" + name = "golang.org/x/net" + packages = [ + "html", + "html/atom", + "html/charset", + "idna", + "publicsuffix", + ] + pruneopts = "UT" + revision = "ed066c81e75eba56dd9bd2139ade88125b855585" + +[[projects]] + branch = "master" + digest = "1:9d6fee48d0bab077ed9cc08f69e902615f02b3e30f945334bdf902abb9e2af7c" + name = "golang.org/x/sys" + packages = [ + "unix", + "windows", + ] + pruneopts = "UT" + revision = "054c452bb702e465e95ce8e7a3d9a6cf0cd1188d" + +[[projects]] + digest = "1:436b24586f8fee329e0dd65fd67c817681420cda1d7f934345c13fe78c212a73" + name = "golang.org/x/text" + packages = [ + "collate", + "collate/build", + "encoding", + "encoding/charmap", + "encoding/htmlindex", + "encoding/internal", + "encoding/internal/identifier", + "encoding/japanese", + "encoding/korean", + "encoding/simplifiedchinese", + "encoding/traditionalchinese", + "encoding/unicode", + "internal/colltab", + "internal/gen", + "internal/tag", + "internal/triegen", + "internal/ucd", + "internal/utf8internal", + "language", + "runes", + "secure/bidirule", + "transform", + "unicode/bidi", + "unicode/cldr", + "unicode/norm", + "unicode/rangetable", + ] + pruneopts = "UT" + revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" + version = "v0.3.0" + +[[projects]] + digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" + name = "gopkg.in/fsnotify/fsnotify.v1" + packages = ["."] + pruneopts = "UT" + revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" + version = "v1.4.7" + +[[projects]] + digest = "1:3c839a777de0e6da035c9de900b60cbec463b0a89351192c1ea083eaf9e0fce0" + name = "gopkg.in/tomb.v1" + packages = ["."] + pruneopts = "UT" + revision = "c131134a1947e9afd9cecfe11f4c6dff0732ae58" + +[[projects]] + digest = "1:4d2e5a73dc1500038e504a8d78b986630e3626dc027bc030ba5c75da257cdb96" + name = "gopkg.in/yaml.v2" + packages = ["."] + pruneopts = "UT" + revision = "51d6538a90f86fe93ac480b35f37b2be17fef232" + version = "v2.2.2" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + input-imports = [ + "github.com/onsi/ginkgo", + "github.com/onsi/gomega", + "github.com/sirupsen/logrus", + "golang.org/x/net/publicsuffix", + ] + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/vendor/github.com/infobloxopen/infoblox-go-client/Gopkg.toml b/vendor/github.com/infobloxopen/infoblox-go-client/Gopkg.toml new file mode 100644 index 0000000..67c481a --- /dev/null +++ b/vendor/github.com/infobloxopen/infoblox-go-client/Gopkg.toml @@ -0,0 +1,19 @@ +[[constraint]] + name = "github.com/onsi/ginkgo" + version = "1.7.0" + +[[constraint]] + name = "github.com/onsi/gomega" + version = "1.4.3" + +[[constraint]] + name = "github.com/sirupsen/logrus" + version = "1.3.0" + +[[constraint]] + branch = "master" + name = "golang.org/x/net" + +[prune] + go-tests = true + unused-packages = true diff --git a/vendor/github.com/infobloxopen/infoblox-go-client/LICENSE b/vendor/github.com/infobloxopen/infoblox-go-client/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/vendor/github.com/infobloxopen/infoblox-go-client/LICENSE @@ -0,0 +1,201 @@ + 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/vendor/github.com/infobloxopen/infoblox-go-client/README.md b/vendor/github.com/infobloxopen/infoblox-go-client/README.md new file mode 100644 index 0000000..de74e9c --- /dev/null +++ b/vendor/github.com/infobloxopen/infoblox-go-client/README.md @@ -0,0 +1,68 @@ +# Infoblox Go Client + +An Infoblox Client library for Go. + +This library is compatible with Go 1.2+ + +- [Prerequisites](#Prerequisites) +- [Installation](#Installation) +- [Usage](#Usage) + +## Prerequisites + * Infoblox GRID with 2.5 or above WAPI support + * Go 1.2 or above + +## Installation + go get github.com/infobloxopen/infoblox-go-client + +## Usage + + The following is a very simple example for the client usage: + + package main + import ( + "fmt" + ibclient "github.com/infobloxopen/infoblox-go-client" + ) + + func main() { + hostConfig := ibclient.HostConfig{ + Host: "", + Version: "", + Port: "PORT", + Username: "username", + Password: "password", + } + transportConfig := ibclient.NewTransportConfig("false", 20, 10) + requestBuilder := &ibclient.WapiRequestBuilder{} + requestor := &ibclient.WapiHttpRequestor{} + conn, err := ibclient.NewConnector(hostConfig, transportConfig, requestBuilder, requestor) + if err != nil { + fmt.Println(err) + } + defer conn.Logout() + objMgr := ibclient.NewObjectManager(conn, "myclient", "") + //Fetches grid information + fmt.Println(objMgr.GetLicense()) + } + +## Supported NIOS operations + + * CreateNetworkView + * CreateDefaultNetviews + * CreateNetwork + * CreateNetworkContainer + * GetNetworkView + * GetNetwork + * GetNetworkContainer + * AllocateNetwork + * UpdateFixedAddress + * GetFixedAddress + * ReleaseIP + * DeleteNetwork + * GetEADefinition + * CreateEADefinition + * UpdateNetworkViewEA + * GetCapacityReport + * GetAllMembers + * GetUpgradeStatus (2.7 or above) diff --git a/vendor/github.com/infobloxopen/infoblox-go-client/connector.go b/vendor/github.com/infobloxopen/infoblox-go-client/connector.go new file mode 100644 index 0000000..0d8bdf7 --- /dev/null +++ b/vendor/github.com/infobloxopen/infoblox-go-client/connector.go @@ -0,0 +1,392 @@ +package ibclient + +import ( + "bytes" + "crypto/tls" + "crypto/x509" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "log" + "net/http" + "net/http/cookiejar" + "net/url" + "reflect" + "strings" + "time" + + "golang.org/x/net/publicsuffix" +) + +type HostConfig struct { + Host string + Version string + Port string + Username string + Password string +} + +type TransportConfig struct { + SslVerify bool + certPool *x509.CertPool + HttpRequestTimeout time.Duration // in seconds + HttpPoolConnections int +} + +func NewTransportConfig(sslVerify string, httpRequestTimeout int, httpPoolConnections int) (cfg TransportConfig) { + switch { + case "false" == strings.ToLower(sslVerify): + cfg.SslVerify = false + case "true" == strings.ToLower(sslVerify): + cfg.SslVerify = true + default: + caPool := x509.NewCertPool() + cert, err := ioutil.ReadFile(sslVerify) + if err != nil { + log.Printf("Cannot load certificate file '%s'", sslVerify) + return + } + if !caPool.AppendCertsFromPEM(cert) { + err = fmt.Errorf("Cannot append certificate from file '%s'", sslVerify) + return + } + cfg.certPool = caPool + cfg.SslVerify = true + } + + cfg.HttpPoolConnections = httpPoolConnections + cfg.HttpRequestTimeout = time.Duration(httpRequestTimeout) + return +} + +type HttpRequestBuilder interface { + Init(HostConfig) + BuildUrl(r RequestType, objType string, ref string, returnFields []string, queryParams QueryParams) (urlStr string) + BuildBody(r RequestType, obj IBObject) (jsonStr []byte) + BuildRequest(r RequestType, obj IBObject, ref string, queryParams QueryParams) (req *http.Request, err error) +} + +type HttpRequestor interface { + Init(TransportConfig) + SendRequest(*http.Request) ([]byte, error) +} + +type WapiRequestBuilder struct { + HostConfig HostConfig +} + +type WapiHttpRequestor struct { + client http.Client +} + +type IBConnector interface { + CreateObject(obj IBObject) (ref string, err error) + GetObject(obj IBObject, ref string, res interface{}) error + DeleteObject(ref string) (refRes string, err error) + UpdateObject(obj IBObject, ref string) (refRes string, err error) +} + +type Connector struct { + HostConfig HostConfig + TransportConfig TransportConfig + RequestBuilder HttpRequestBuilder + Requestor HttpRequestor +} + +type RequestType int + +const ( + CREATE RequestType = iota + GET + DELETE + UPDATE +) + +func (r RequestType) toMethod() string { + switch r { + case CREATE: + return "POST" + case GET: + return "GET" + case DELETE: + return "DELETE" + case UPDATE: + return "PUT" + } + + return "" +} + +func getHTTPResponseError(resp *http.Response) error { + defer resp.Body.Close() + content, _ := ioutil.ReadAll(resp.Body) + msg := fmt.Sprintf("WAPI request error: %d('%s')\nContents:\n%s\n", resp.StatusCode, resp.Status, content) + log.Printf(msg) + return errors.New(msg) +} + +func (whr *WapiHttpRequestor) Init(cfg TransportConfig) { + tr := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: !cfg.SslVerify, + RootCAs: cfg.certPool}, + MaxIdleConnsPerHost: cfg.HttpPoolConnections, + } + + // All users of cookiejar should import "golang.org/x/net/publicsuffix" + jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) + if err != nil { + log.Fatal(err) + } + + whr.client = http.Client{Jar: jar, Transport: tr, Timeout: cfg.HttpRequestTimeout * time.Second} +} + +func (whr *WapiHttpRequestor) SendRequest(req *http.Request) (res []byte, err error) { + var resp *http.Response + resp, err = whr.client.Do(req) + if err != nil { + return + } else if !(resp.StatusCode == http.StatusOK || + (resp.StatusCode == http.StatusCreated && + req.Method == RequestType(CREATE).toMethod())) { + err := getHTTPResponseError(resp) + return nil, err + } + defer resp.Body.Close() + res, err = ioutil.ReadAll(resp.Body) + if err != nil { + log.Printf("Http Reponse ioutil.ReadAll() Error: '%s'", err) + return + } + + return +} + +func (wrb *WapiRequestBuilder) Init(cfg HostConfig) { + wrb.HostConfig = cfg +} + +func (wrb *WapiRequestBuilder) BuildUrl(t RequestType, objType string, ref string, returnFields []string, queryParams QueryParams) (urlStr string) { + path := []string{"wapi", "v" + wrb.HostConfig.Version} + if len(ref) > 0 { + path = append(path, ref) + } else { + path = append(path, objType) + } + + qry := "" + vals := url.Values{} + if t == GET { + if len(returnFields) > 0 { + vals.Set("_return_fields", strings.Join(returnFields, ",")) + } + // TODO need to get this from individual objects in future + if queryParams.forceProxy { + vals.Set("_proxy_search", "GM") + } + qry = vals.Encode() + } + + u := url.URL{ + Scheme: "https", + Host: wrb.HostConfig.Host + ":" + wrb.HostConfig.Port, + Path: strings.Join(path, "/"), + RawQuery: qry, + } + + return u.String() +} + +func (wrb *WapiRequestBuilder) BuildBody(t RequestType, obj IBObject) []byte { + var objJSON []byte + var err error + + objJSON, err = json.Marshal(obj) + if err != nil { + log.Printf("Cannot marshal object '%s': %s", obj, err) + return nil + } + + eaSearch := obj.EaSearch() + if t == GET && len(eaSearch) > 0 { + eaSearchJSON, err := json.Marshal(eaSearch) + if err != nil { + log.Printf("Cannot marshal EA Search attributes. '%s'\n", err) + return nil + } + objJSON = append(append(objJSON[:len(objJSON)-1], byte(',')), eaSearchJSON[1:]...) + } + + return objJSON +} + +func (wrb *WapiRequestBuilder) BuildRequest(t RequestType, obj IBObject, ref string, queryParams QueryParams) (req *http.Request, err error) { + var ( + objType string + returnFields []string + ) + if obj != nil { + objType = obj.ObjectType() + returnFields = obj.ReturnFields() + } + urlStr := wrb.BuildUrl(t, objType, ref, returnFields, queryParams) + + var bodyStr []byte + if obj != nil { + bodyStr = wrb.BuildBody(t, obj) + } + + req, err = http.NewRequest(t.toMethod(), urlStr, bytes.NewBuffer(bodyStr)) + if err != nil { + log.Printf("err1: '%s'", err) + return + } + req.Header.Set("Content-Type", "application/json") + req.SetBasicAuth(wrb.HostConfig.Username, wrb.HostConfig.Password) + + return +} + +func (c *Connector) makeRequest(t RequestType, obj IBObject, ref string, queryParams QueryParams) (res []byte, err error) { + var req *http.Request + req, err = c.RequestBuilder.BuildRequest(t, obj, ref, queryParams) + res, err = c.Requestor.SendRequest(req) + if err != nil { + /* Forcing the request to redirect to Grid Master by making forcedProxy=true */ + queryParams.forceProxy = true + req, err = c.RequestBuilder.BuildRequest(t, obj, ref, queryParams) + res, err = c.Requestor.SendRequest(req) + } + + return +} + +func (c *Connector) CreateObject(obj IBObject) (ref string, err error) { + ref = "" + queryParams := QueryParams{forceProxy: false} + resp, err := c.makeRequest(CREATE, obj, "", queryParams) + if err != nil || len(resp) == 0 { + log.Printf("CreateObject request error: '%s'\n", err) + return + } + + err = json.Unmarshal(resp, &ref) + if err != nil { + log.Printf("Cannot unmarshall '%s', err: '%s'\n", string(resp), err) + return + } + + return +} + +func (c *Connector) GetObject(obj IBObject, ref string, res interface{}) (err error) { + queryParams := QueryParams{forceProxy: false} + resp, err := c.makeRequest(GET, obj, ref, queryParams) + //to check empty underlying value of interface + var result interface{} + err = json.Unmarshal(resp, &result) + if err != nil { + log.Printf("Cannot unmarshall to check empty value '%s', err: '%s'\n", string(resp), err) + } + + var data []interface{} + if resp == nil || (reflect.TypeOf(result) == reflect.TypeOf(data) && len(result.([]interface{})) == 0) { + queryParams.forceProxy = true + resp, err = c.makeRequest(GET, obj, ref, queryParams) + } + if err != nil { + log.Printf("GetObject request error: '%s'\n", err) + } + if len(resp) == 0 { + return + } + err = json.Unmarshal(resp, res) + if err != nil { + log.Printf("Cannot unmarshall '%s', err: '%s'\n", string(resp), err) + return + } + return +} + +func (c *Connector) DeleteObject(ref string) (refRes string, err error) { + refRes = "" + queryParams := QueryParams{forceProxy: false} + resp, err := c.makeRequest(DELETE, nil, ref, queryParams) + if err != nil { + log.Printf("DeleteObject request error: '%s'\n", err) + return + } + + err = json.Unmarshal(resp, &refRes) + if err != nil { + log.Printf("Cannot unmarshall '%s', err: '%s'\n", string(resp), err) + return + } + + return +} + +func (c *Connector) UpdateObject(obj IBObject, ref string) (refRes string, err error) { + queryParams := QueryParams{forceProxy: false} + refRes = "" + resp, err := c.makeRequest(UPDATE, obj, ref, queryParams) + if err != nil { + log.Printf("Failed to update object %s: %s", obj.ObjectType(), err) + return + } + + err = json.Unmarshal(resp, &refRes) + if err != nil { + log.Printf("Cannot unmarshall update object response'%s', err: '%s'\n", string(resp), err) + return + } + return +} + +// Logout sends a request to invalidate the ibapauth cookie and should +// be used in a defer statement after the Connector has been successfully +// initialized. +func (c *Connector) Logout() (err error) { + queryParams := QueryParams{forceProxy: false} + _, err = c.makeRequest(CREATE, nil, "logout", queryParams) + if err != nil { + log.Printf("Logout request error: '%s'\n", err) + } + + return +} + +var ValidateConnector = validateConnector + +func validateConnector(c *Connector) (err error) { + // GET UserProfile request is used here to validate connector's basic auth and reachability. + var response []UserProfile + userprofile := NewUserProfile(UserProfile{}) + err = c.GetObject(userprofile, "", &response) + if err != nil { + log.Printf("Failed to connect to the Grid, err: %s \n", err) + } + return +} + +func NewConnector(hostConfig HostConfig, transportConfig TransportConfig, + requestBuilder HttpRequestBuilder, requestor HttpRequestor) (res *Connector, err error) { + res = nil + + connector := &Connector{ + HostConfig: hostConfig, + TransportConfig: transportConfig, + } + + //connector.RequestBuilder = WapiRequestBuilder{WaipHostConfig: connector.HostConfig} + connector.RequestBuilder = requestBuilder + connector.RequestBuilder.Init(connector.HostConfig) + + connector.Requestor = requestor + connector.Requestor.Init(connector.TransportConfig) + + res = connector + err = ValidateConnector(connector) + return +} diff --git a/vendor/github.com/infobloxopen/infoblox-go-client/lock.go b/vendor/github.com/infobloxopen/infoblox-go-client/lock.go new file mode 100644 index 0000000..b4d6705 --- /dev/null +++ b/vendor/github.com/infobloxopen/infoblox-go-client/lock.go @@ -0,0 +1,247 @@ +package ibclient + +import ( + "fmt" + "math/rand" + "time" + + "github.com/sirupsen/logrus" +) + +const ( + timeout int32 = 60 // in seconds + freeLockVal string = "Available" +) + +type Lock interface { + Lock() error + UnLock(force bool) error +} + +type NetworkViewLock struct { + Name string + ObjMgr *ObjectManager + LockEA string + LockTimeoutEA string +} + +func (l *NetworkViewLock) createLockRequest() *MultiRequest { + + req := NewMultiRequest( + []*RequestBody{ + &RequestBody{ + Method: "GET", + Object: "networkview", + Data: map[string]interface{}{ + "name": l.Name, + "*" + l.LockEA: freeLockVal, + }, + Args: map[string]string{ + "_return_fields": "extattrs", + }, + AssignState: map[string]string{ + "NET_VIEW_REF": "_ref", + }, + Discard: true, + }, + &RequestBody{ + Method: "PUT", + Object: "##STATE:NET_VIEW_REF:##", + Data: map[string]interface{}{ + "extattrs+": map[string]interface{}{ + l.LockEA: map[string]string{ + "value": l.ObjMgr.tenantID, + }, + l.LockTimeoutEA: map[string]int32{ + "value": int32(time.Now().Unix()), + }, + }, + }, + EnableSubstitution: true, + Discard: true, + }, + &RequestBody{ + Method: "GET", + Object: "##STATE:NET_VIEW_REF:##", + Args: map[string]string{ + "_return_fields": "extattrs", + }, + AssignState: map[string]string{ + "DOCKER-ID": "*" + l.LockEA, + }, + EnableSubstitution: true, + Discard: true, + }, + &RequestBody{ + Method: "STATE:DISPLAY", + }, + }, + ) + + return req +} + +func (l *NetworkViewLock) createUnlockRequest(force bool) *MultiRequest { + + getData := map[string]interface{}{"name": l.Name} + if !force { + getData["*"+l.LockEA] = l.ObjMgr.tenantID + } + + req := NewMultiRequest( + []*RequestBody{ + &RequestBody{ + Method: "GET", + Object: "networkview", + Data: getData, + Args: map[string]string{ + "_return_fields": "extattrs", + }, + AssignState: map[string]string{ + "NET_VIEW_REF": "_ref", + }, + Discard: true, + }, + &RequestBody{ + Method: "PUT", + Object: "##STATE:NET_VIEW_REF:##", + Data: map[string]interface{}{ + "extattrs+": map[string]interface{}{ + l.LockEA: map[string]string{ + "value": freeLockVal, + }, + }, + }, + EnableSubstitution: true, + Discard: true, + }, + &RequestBody{ + Method: "PUT", + Object: "##STATE:NET_VIEW_REF:##", + Data: map[string]interface{}{ + "extattrs-": map[string]interface{}{ + l.LockTimeoutEA: map[string]interface{}{}, + }, + }, + EnableSubstitution: true, + Discard: true, + }, + &RequestBody{ + Method: "GET", + Object: "##STATE:NET_VIEW_REF:##", + Args: map[string]string{ + "_return_fields": "extattrs", + }, + AssignState: map[string]string{ + "DOCKER-ID": "*" + l.LockEA, + }, + EnableSubstitution: true, + Discard: true, + }, + &RequestBody{ + Method: "STATE:DISPLAY", + }, + }, + ) + + return req +} + +func (l *NetworkViewLock) getLock() bool { + logrus.Debugf("Creating lock on network niew %s\n", l.Name) + req := l.createLockRequest() + res, err := l.ObjMgr.CreateMultiObject(req) + + if err != nil { + logrus.Debugf("Failed to create lock on network view %s: %s\n", l.Name, err) + + //Check for Lock Timeout + nw, err := l.ObjMgr.GetNetworkView(l.Name) + if err != nil { + logrus.Debugf("Failed to get the network view object for %s : %s\n", l.Name, err) + return false + } + + if t, ok := nw.Ea[l.LockTimeoutEA]; ok { + if int32(time.Now().Unix())-int32(t.(int)) > timeout { + logrus.Debugln("Lock is timed out. Forcefully acquiring it.") + //remove the lock forcefully and acquire it + l.UnLock(true) + // try to get lock again + return l.getLock() + } + } + return false + } + + dockerID := res[0]["DOCKER-ID"] + if dockerID == l.ObjMgr.tenantID { + logrus.Debugln("Got the lock !!!") + return true + } + + return false +} + +func (l *NetworkViewLock) Lock() error { + + // verify if network view exists and has EA for the lock + nw, err := l.ObjMgr.GetNetworkView(l.Name) + if err != nil { + msg := fmt.Sprintf("Failed to get the network view object for %s : %s\n", l.Name, err) + logrus.Debugf(msg) + return fmt.Errorf(msg) + } + + if _, ok := nw.Ea[l.LockEA]; !ok { + err = l.ObjMgr.UpdateNetworkViewEA(nw.Ref, EA{l.LockEA: freeLockVal}, nil) + if err != nil { + return fmt.Errorf("Failed to Update Network view with Lock EA") + } + } + + retryCount := 0 + for { + // Get lock on the network view + lock := l.getLock() + if lock == true { + // Got the lock. + logrus.Debugf("Got the lock on Network View %s\n", l.Name) + return nil + } + + // Lock is held by some other agent. Wait for some time and retry it again + if retryCount >= 10 { + return fmt.Errorf("Failed to get Lock on Network View %s", l.Name) + } + + retryCount++ + logrus.Debugf("Lock on Network View %s not free. Retrying again %d out of 10.\n", l.Name, retryCount) + // sleep for random time (between 1 - 10 seconds) to reduce collisions + time.Sleep(time.Duration(rand.Intn(9)+1) * time.Second) + continue + } +} + +func (l *NetworkViewLock) UnLock(force bool) error { + // To unlock set the Docker-Plugin-Lock EA of network view to Available and + // remove the Docker-Plugin-Lock-Time EA + req := l.createUnlockRequest(force) + res, err := l.ObjMgr.CreateMultiObject(req) + + if err != nil { + msg := fmt.Sprintf("Failed to release lock from Network View %s: %s\n", l.Name, err) + logrus.Errorf(msg) + return fmt.Errorf(msg) + } + + dockerID := res[0]["DOCKER-ID"] + if dockerID == freeLockVal { + logrus.Debugln("Removed the lock!") + return nil + } + + msg := fmt.Sprintf("Failed to release lock from Network View %s\n", l.Name) + logrus.Errorf(msg) + return fmt.Errorf(msg) +} diff --git a/vendor/github.com/infobloxopen/infoblox-go-client/object_manager.go b/vendor/github.com/infobloxopen/infoblox-go-client/object_manager.go new file mode 100644 index 0000000..0f49b58 --- /dev/null +++ b/vendor/github.com/infobloxopen/infoblox-go-client/object_manager.go @@ -0,0 +1,802 @@ +package ibclient + +import ( + "encoding/json" + "errors" + "fmt" + "regexp" +) + +type IBObjectManager interface { + AllocateIP(netview string, cidr string, ipAddr string, macAddress string, name string, ea EA) (*FixedAddress, error) + AllocateNetwork(netview string, cidr string, prefixLen uint, name string) (network *Network, err error) + CreateARecord(netview string, dnsview string, recordname string, cidr string, ipAddr string, ea EA) (*RecordA, error) + CreateCNAMERecord(canonical string, recordname string, dnsview string, ea EA) (*RecordCNAME, error) + CreateDefaultNetviews(globalNetview string, localNetview string) (globalNetviewRef string, localNetviewRef string, err error) + CreateEADefinition(eadef EADefinition) (*EADefinition, error) + CreateHostRecord(enabledns bool, recordName string, netview string, dnsview string, cidr string, ipAddr string, macAddress string, ea EA) (*HostRecord, error) + CreateNetwork(netview string, cidr string, name string) (*Network, error) + CreateNetworkContainer(netview string, cidr string) (*NetworkContainer, error) + CreateNetworkView(name string) (*NetworkView, error) + CreatePTRRecord(netview string, dnsview string, recordname string, cidr string, ipAddr string, ea EA) (*RecordPTR, error) + DeleteARecord(ref string) (string, error) + DeleteCNAMERecord(ref string) (string, error) + DeleteFixedAddress(ref string) (string, error) + DeleteHostRecord(ref string) (string, error) + DeleteNetwork(ref string, netview string) (string, error) + DeleteNetworkView(ref string) (string, error) + DeletePTRRecord(ref string) (string, error) + GetARecordByRef(ref string) (*RecordA, error) + GetCNAMERecordByRef(ref string) (*RecordA, error) + GetEADefinition(name string) (*EADefinition, error) + GetFixedAddress(netview string, cidr string, ipAddr string, macAddr string) (*FixedAddress, error) + GetFixedAddressByRef(ref string) (*FixedAddress, error) + GetHostRecord(recordName string, netview string, cidr string, ipAddr string) (*HostRecord, error) + GetHostRecordByRef(ref string) (*HostRecord, error) + GetIpAddressFromHostRecord(host HostRecord) (string, error) + GetNetwork(netview string, cidr string, ea EA) (*Network, error) + GetNetworkContainer(netview string, cidr string) (*NetworkContainer, error) + GetNetworkView(name string) (*NetworkView, error) + GetPTRRecordByRef(ref string) (*RecordPTR, error) + ReleaseIP(netview string, cidr string, ipAddr string, macAddr string) (string, error) + UpdateFixedAddress(fixedAddrRef string, matchclient string, macAddress string, vmID string, vmName string) (*FixedAddress, error) + UpdateHostRecord(hostRref string, ipAddr string, macAddress string, vmID string, vmName string) (string, error) + UpdateNetworkViewEA(ref string, addEA EA, removeEA EA) error +} + +type ObjectManager struct { + connector IBConnector + cmpType string + tenantID string +} + +func NewObjectManager(connector IBConnector, cmpType string, tenantID string) *ObjectManager { + objMgr := new(ObjectManager) + + objMgr.connector = connector + objMgr.cmpType = cmpType + objMgr.tenantID = tenantID + + return objMgr +} + +func (objMgr *ObjectManager) getBasicEA(cloudAPIOwned Bool) EA { + ea := make(EA) + ea["Cloud API Owned"] = cloudAPIOwned + ea["CMP Type"] = objMgr.cmpType + ea["Tenant ID"] = objMgr.tenantID + return ea +} + +func (objMgr *ObjectManager) extendEA(ea EA) EA { + eas := objMgr.getBasicEA(true) + for k, v := range ea { + eas[k] = v + } + return eas +} + +func (objMgr *ObjectManager) CreateNetworkView(name string) (*NetworkView, error) { + networkView := NewNetworkView(NetworkView{ + Name: name, + Ea: objMgr.getBasicEA(false)}) + + ref, err := objMgr.connector.CreateObject(networkView) + networkView.Ref = ref + + return networkView, err +} + +func (objMgr *ObjectManager) makeNetworkView(netviewName string) (netviewRef string, err error) { + var netviewObj *NetworkView + if netviewObj, err = objMgr.GetNetworkView(netviewName); err != nil { + return + } + if netviewObj == nil { + if netviewObj, err = objMgr.CreateNetworkView(netviewName); err != nil { + return + } + } + + netviewRef = netviewObj.Ref + + return +} + +func (objMgr *ObjectManager) CreateDefaultNetviews(globalNetview string, localNetview string) (globalNetviewRef string, localNetviewRef string, err error) { + if globalNetviewRef, err = objMgr.makeNetworkView(globalNetview); err != nil { + return + } + + if localNetviewRef, err = objMgr.makeNetworkView(localNetview); err != nil { + return + } + + return +} + +func (objMgr *ObjectManager) CreateNetwork(netview string, cidr string, name string) (*Network, error) { + network := NewNetwork(Network{ + NetviewName: netview, + Cidr: cidr, + Ea: objMgr.getBasicEA(true)}) + + if name != "" { + network.Ea["Network Name"] = name + } + ref, err := objMgr.connector.CreateObject(network) + if err != nil { + return nil, err + } + network.Ref = ref + + return network, err +} + +func (objMgr *ObjectManager) CreateNetworkContainer(netview string, cidr string) (*NetworkContainer, error) { + container := NewNetworkContainer(NetworkContainer{ + NetviewName: netview, + Cidr: cidr, + Ea: objMgr.getBasicEA(true)}) + + ref, err := objMgr.connector.CreateObject(container) + container.Ref = ref + + return container, err +} + +func (objMgr *ObjectManager) GetNetworkView(name string) (*NetworkView, error) { + var res []NetworkView + + netview := NewNetworkView(NetworkView{Name: name}) + + err := objMgr.connector.GetObject(netview, "", &res) + + if err != nil || res == nil || len(res) == 0 { + return nil, err + } + + return &res[0], nil +} + +func (objMgr *ObjectManager) UpdateNetworkViewEA(ref string, addEA EA, removeEA EA) error { + var res NetworkView + + nv := NetworkView{} + nv.returnFields = []string{"extattrs"} + err := objMgr.connector.GetObject(&nv, ref, &res) + + if err != nil { + return err + } + + for k, v := range addEA { + res.Ea[k] = v + } + + for k := range removeEA { + _, ok := res.Ea[k] + if ok { + delete(res.Ea, k) + } + } + + _, err = objMgr.connector.UpdateObject(&res, ref) + return err +} + +func BuildNetworkViewFromRef(ref string) *NetworkView { + // networkview/ZG5zLm5ldHdvcmtfdmlldyQyMw:global_view/false + r := regexp.MustCompile(`networkview/\w+:([^/]+)/\w+`) + m := r.FindStringSubmatch(ref) + + if m == nil { + return nil + } + + return &NetworkView{ + Ref: ref, + Name: m[1], + } +} + +func BuildNetworkFromRef(ref string) *Network { + // network/ZG5zLm5ldHdvcmskODkuMC4wLjAvMjQvMjU:89.0.0.0/24/global_view + r := regexp.MustCompile(`network/\w+:(\d+\.\d+\.\d+\.\d+/\d+)/(.+)`) + m := r.FindStringSubmatch(ref) + + if m == nil { + return nil + } + + return &Network{ + Ref: ref, + NetviewName: m[2], + Cidr: m[1], + } +} + +func (objMgr *ObjectManager) GetNetwork(netview string, cidr string, ea EA) (*Network, error) { + var res []Network + + network := NewNetwork(Network{ + NetviewName: netview}) + + if cidr != "" { + network.Cidr = cidr + } + + if ea != nil && len(ea) > 0 { + network.eaSearch = EASearch(ea) + } + + err := objMgr.connector.GetObject(network, "", &res) + + if err != nil || res == nil || len(res) == 0 { + return nil, err + } + + return &res[0], nil +} + +func (objMgr *ObjectManager) GetNetworkwithref(ref string) (*Network, error) { + network := NewNetwork(Network{}) + err := objMgr.connector.GetObject(network, ref, &network) + return network, err +} + +func (objMgr *ObjectManager) GetNetworkContainer(netview string, cidr string) (*NetworkContainer, error) { + var res []NetworkContainer + + nwcontainer := NewNetworkContainer(NetworkContainer{ + NetviewName: netview, + Cidr: cidr}) + + err := objMgr.connector.GetObject(nwcontainer, "", &res) + + if err != nil || res == nil || len(res) == 0 { + return nil, err + } + + return &res[0], nil +} + +func GetIPAddressFromRef(ref string) string { + // fixedaddress/ZG5zLmJpbmRfY25h:12.0.10.1/external + r := regexp.MustCompile(`fixedaddress/\w+:(\d+\.\d+\.\d+\.\d+)/.+`) + m := r.FindStringSubmatch(ref) + + if m != nil { + return m[1] + } + return "" +} + +func (objMgr *ObjectManager) AllocateIP(netview string, cidr string, ipAddr string, macAddress string, name string, ea EA) (*FixedAddress, error) { + if len(macAddress) == 0 { + macAddress = MACADDR_ZERO + } + + eas := objMgr.extendEA(ea) + + fixedAddr := NewFixedAddress(FixedAddress{ + NetviewName: netview, + Cidr: cidr, + Mac: macAddress, + Name: name, + Ea: eas}) + + if ipAddr == "" { + fixedAddr.IPAddress = fmt.Sprintf("func:nextavailableip:%s,%s", cidr, netview) + } else { + fixedAddr.IPAddress = ipAddr + } + + ref, err := objMgr.connector.CreateObject(fixedAddr) + fixedAddr.Ref = ref + fixedAddr.IPAddress = GetIPAddressFromRef(ref) + + return fixedAddr, err +} + +func (objMgr *ObjectManager) AllocateNetwork(netview string, cidr string, prefixLen uint, name string) (network *Network, err error) { + network = nil + + networkReq := NewNetwork(Network{ + NetviewName: netview, + Cidr: fmt.Sprintf("func:nextavailablenetwork:%s,%s,%d", cidr, netview, prefixLen), + Ea: objMgr.getBasicEA(true)}) + if name != "" { + networkReq.Ea["Network Name"] = name + } + + ref, err := objMgr.connector.CreateObject(networkReq) + if err == nil && len(ref) > 0 { + network = BuildNetworkFromRef(ref) + } + + return +} + +func (objMgr *ObjectManager) GetFixedAddress(netview string, cidr string, ipAddr string, macAddr string) (*FixedAddress, error) { + var res []FixedAddress + + fixedAddr := NewFixedAddress(FixedAddress{ + NetviewName: netview, + Cidr: cidr, + IPAddress: ipAddr}) + + if macAddr != "" { + fixedAddr.Mac = macAddr + } + + err := objMgr.connector.GetObject(fixedAddr, "", &res) + + if err != nil || res == nil || len(res) == 0 { + return nil, err + } + + return &res[0], nil +} + +func (objMgr *ObjectManager) GetFixedAddressByRef(ref string) (*FixedAddress, error) { + fixedAddr := NewFixedAddress(FixedAddress{}) + err := objMgr.connector.GetObject(fixedAddr, ref, &fixedAddr) + return fixedAddr, err +} + +func (objMgr *ObjectManager) DeleteFixedAddress(ref string) (string, error) { + return objMgr.connector.DeleteObject(ref) +} + +// validation for match_client +func validateMatchClient(value string) bool { + match_client := [5]string{"MAC_ADDRESS", "CLIENT_ID", "RESERVED", "CIRCUIT_ID", "REMOTE_ID"} + + for _, val := range match_client { + if val == value { + return true + } + } + return false +} + +func (objMgr *ObjectManager) UpdateFixedAddress(fixedAddrRef string, matchClient string, macAddress string, vmID string, vmName string) (*FixedAddress, error) { + updateFixedAddr := NewFixedAddress(FixedAddress{Ref: fixedAddrRef}) + + if len(macAddress) != 0 { + updateFixedAddr.Mac = macAddress + } + + ea := objMgr.getBasicEA(true) + if vmID != "" { + ea["VM ID"] = vmID + updateFixedAddr.Ea = ea + } + if vmName != "" { + ea["VM Name"] = vmName + updateFixedAddr.Ea = ea + } + if matchClient != "" { + if validateMatchClient(matchClient) { + updateFixedAddr.MatchClient = matchClient + } else { + return nil, fmt.Errorf("wrong value for match_client passed %s \n ", matchClient) + } + } + + refResp, err := objMgr.connector.UpdateObject(updateFixedAddr, fixedAddrRef) + updateFixedAddr.Ref = refResp + return updateFixedAddr, err +} + +func (objMgr *ObjectManager) ReleaseIP(netview string, cidr string, ipAddr string, macAddr string) (string, error) { + fixAddress, _ := objMgr.GetFixedAddress(netview, cidr, ipAddr, macAddr) + if fixAddress == nil { + return "", nil + } + return objMgr.connector.DeleteObject(fixAddress.Ref) +} + +func (objMgr *ObjectManager) DeleteNetwork(ref string, netview string) (string, error) { + network := BuildNetworkFromRef(ref) + if network != nil && network.NetviewName == netview { + return objMgr.connector.DeleteObject(ref) + } + + return "", nil +} + +func (objMgr *ObjectManager) DeleteNetworkView(ref string) (string, error) { + return objMgr.connector.DeleteObject(ref) +} + +func (objMgr *ObjectManager) GetEADefinition(name string) (*EADefinition, error) { + var res []EADefinition + + eadef := NewEADefinition(EADefinition{Name: name}) + + err := objMgr.connector.GetObject(eadef, "", &res) + + if err != nil || res == nil || len(res) == 0 { + return nil, err + } + + return &res[0], nil +} + +func (objMgr *ObjectManager) CreateEADefinition(eadef EADefinition) (*EADefinition, error) { + newEadef := NewEADefinition(eadef) + + ref, err := objMgr.connector.CreateObject(newEadef) + newEadef.Ref = ref + + return newEadef, err +} + +func (objMgr *ObjectManager) CreateHostRecord(enabledns bool, recordName string, netview string, dnsview string, cidr string, ipAddr string, macAddress string, ea EA) (*HostRecord, error) { + + eas := objMgr.extendEA(ea) + + recordHostIpAddr := NewHostRecordIpv4Addr(HostRecordIpv4Addr{Mac: macAddress}) + + if ipAddr == "" { + recordHostIpAddr.Ipv4Addr = fmt.Sprintf("func:nextavailableip:%s,%s", cidr, netview) + } else { + recordHostIpAddr.Ipv4Addr = ipAddr + } + enableDNS := new(bool) + *enableDNS = enabledns + recordHostIpAddrSlice := []HostRecordIpv4Addr{*recordHostIpAddr} + recordHost := NewHostRecord(HostRecord{ + Name: recordName, + EnableDns: enableDNS, + NetworkView: netview, + View: dnsview, + Ipv4Addrs: recordHostIpAddrSlice, + Ea: eas}) + + ref, err := objMgr.connector.CreateObject(recordHost) + recordHost.Ref = ref + err = objMgr.connector.GetObject(recordHost, ref, &recordHost) + return recordHost, err +} + +func (objMgr *ObjectManager) GetHostRecordByRef(ref string) (*HostRecord, error) { + recordHost := NewHostRecord(HostRecord{}) + err := objMgr.connector.GetObject(recordHost, ref, &recordHost) + return recordHost, err +} + +func (objMgr *ObjectManager) GetHostRecord(recordName string, netview string, cidr string, ipAddr string) (*HostRecord, error) { + var res []HostRecord + + recordHost := NewHostRecord(HostRecord{}) + if recordName != "" { + recordHost.Name = recordName + } + + err := objMgr.connector.GetObject(recordHost, "", &res) + + if err != nil || res == nil || len(res) == 0 { + return nil, err + } + return &res[0], err + +} + +func (objMgr *ObjectManager) GetIpAddressFromHostRecord(host HostRecord) (string, error) { + err := objMgr.connector.GetObject(&host, host.Ref, &host) + return host.Ipv4Addrs[0].Ipv4Addr, err +} + +func (objMgr *ObjectManager) UpdateHostRecord(hostRref string, ipAddr string, macAddress string, vmID string, vmName string) (string, error) { + + recordHostIpAddr := NewHostRecordIpv4Addr(HostRecordIpv4Addr{Mac: macAddress, Ipv4Addr: ipAddr}) + recordHostIpAddrSlice := []HostRecordIpv4Addr{*recordHostIpAddr} + updateHostRecord := NewHostRecord(HostRecord{Ipv4Addrs: recordHostIpAddrSlice}) + + ea := objMgr.getBasicEA(true) + if vmID != "" { + ea["VM ID"] = vmID + updateHostRecord.Ea = ea + } + + if vmName != "" { + ea["VM Name"] = vmName + updateHostRecord.Ea = ea + } + ref, err := objMgr.connector.UpdateObject(updateHostRecord, hostRref) + return ref, err +} + +func (objMgr *ObjectManager) DeleteHostRecord(ref string) (string, error) { + return objMgr.connector.DeleteObject(ref) +} + +func (objMgr *ObjectManager) CreateARecord(netview string, dnsview string, recordname string, cidr string, ipAddr string, ea EA) (*RecordA, error) { + + eas := objMgr.extendEA(ea) + + recordA := NewRecordA(RecordA{ + View: dnsview, + Name: recordname, + Ea: eas}) + + if ipAddr == "" { + recordA.Ipv4Addr = fmt.Sprintf("func:nextavailableip:%s,%s", cidr, netview) + } else { + recordA.Ipv4Addr = ipAddr + } + ref, err := objMgr.connector.CreateObject(recordA) + recordA.Ref = ref + return recordA, err +} + +func (objMgr *ObjectManager) GetARecordByRef(ref string) (*RecordA, error) { + recordA := NewRecordA(RecordA{}) + err := objMgr.connector.GetObject(recordA, ref, &recordA) + return recordA, err +} +func (objMgr *ObjectManager) DeleteARecord(ref string) (string, error) { + return objMgr.connector.DeleteObject(ref) +} + +func (objMgr *ObjectManager) CreateCNAMERecord(canonical string, recordname string, dnsview string, ea EA) (*RecordCNAME, error) { + + eas := objMgr.extendEA(ea) + + recordCNAME := NewRecordCNAME(RecordCNAME{ + View: dnsview, + Name: recordname, + Canonical: canonical, + Ea: eas}) + + ref, err := objMgr.connector.CreateObject(recordCNAME) + recordCNAME.Ref = ref + return recordCNAME, err +} + +func (objMgr *ObjectManager) GetCNAMERecordByRef(ref string) (*RecordCNAME, error) { + recordCNAME := NewRecordCNAME(RecordCNAME{}) + err := objMgr.connector.GetObject(recordCNAME, ref, &recordCNAME) + return recordCNAME, err +} + +func (objMgr *ObjectManager) DeleteCNAMERecord(ref string) (string, error) { + return objMgr.connector.DeleteObject(ref) +} + +// Creates TXT Record. Use TTL of 0 to inherit TTL from the Zone +func (objMgr *ObjectManager) CreateTXTRecord(recordname string, text string, ttl int, dnsview string) (*RecordTXT, error) { + + recordTXT := NewRecordTXT(RecordTXT{ + View: dnsview, + Name: recordname, + Text: text, + TTL: ttl, + }) + + ref, err := objMgr.connector.CreateObject(recordTXT) + recordTXT.Ref = ref + return recordTXT, err +} + +func (objMgr *ObjectManager) GetTXTRecordByRef(ref string) (*RecordTXT, error) { + recordTXT := NewRecordTXT(RecordTXT{}) + err := objMgr.connector.GetObject(recordTXT, ref, &recordTXT) + return recordTXT, err +} + +func (objMgr *ObjectManager) GetTXTRecord(name string) (*RecordTXT, error) { + if name == "" { + return nil, fmt.Errorf("name can not be empty") + } + var res []RecordTXT + + recordTXT := NewRecordTXT(RecordTXT{Name: name}) + + err := objMgr.connector.GetObject(recordTXT, "", &res) + + if err != nil || res == nil || len(res) == 0 { + return nil, err + } + + return &res[0], nil +} + +func (objMgr *ObjectManager) UpdateTXTRecord(recordname string, text string) (*RecordTXT, error) { + var res []RecordTXT + + recordTXT := NewRecordTXT(RecordTXT{Name: recordname}) + + err := objMgr.connector.GetObject(recordTXT, "", &res) + + if len(res) == 0 { + return nil, nil + } + + res[0].Text = text + + res[0].Zone = "" // set the Zone value to "" as its a non writable field + + _, err = objMgr.connector.UpdateObject(&res[0], res[0].Ref) + + if err != nil || res == nil || len(res) == 0 { + return nil, err + } + + return &res[0], nil +} + +func (objMgr *ObjectManager) DeleteTXTRecord(ref string) (string, error) { + return objMgr.connector.DeleteObject(ref) +} + +func (objMgr *ObjectManager) CreatePTRRecord(netview string, dnsview string, recordname string, cidr string, ipAddr string, ea EA) (*RecordPTR, error) { + + eas := objMgr.extendEA(ea) + + recordPTR := NewRecordPTR(RecordPTR{ + View: dnsview, + PtrdName: recordname, + Ea: eas}) + + if ipAddr == "" { + recordPTR.Ipv4Addr = fmt.Sprintf("func:nextavailableip:%s,%s", cidr, netview) + } else { + recordPTR.Ipv4Addr = ipAddr + } + ref, err := objMgr.connector.CreateObject(recordPTR) + recordPTR.Ref = ref + return recordPTR, err +} + +func (objMgr *ObjectManager) GetPTRRecordByRef(ref string) (*RecordPTR, error) { + recordPTR := NewRecordPTR(RecordPTR{}) + err := objMgr.connector.GetObject(recordPTR, ref, &recordPTR) + return recordPTR, err +} + +func (objMgr *ObjectManager) DeletePTRRecord(ref string) (string, error) { + return objMgr.connector.DeleteObject(ref) +} + +// CreateMultiObject unmarshals the result into slice of maps +func (objMgr *ObjectManager) CreateMultiObject(req *MultiRequest) ([]map[string]interface{}, error) { + + conn := objMgr.connector.(*Connector) + queryParams := QueryParams{forceProxy: false} + res, err := conn.makeRequest(CREATE, req, "", queryParams) + + if err != nil { + return nil, err + } + + var result []map[string]interface{} + err = json.Unmarshal(res, &result) + + if err != nil { + return nil, err + } + + return result, nil +} + +// GetUpgradeStatus returns the grid upgrade information +func (objMgr *ObjectManager) GetUpgradeStatus(statusType string) ([]UpgradeStatus, error) { + var res []UpgradeStatus + + if statusType == "" { + // TODO option may vary according to the WAPI version, need to + // throw relevant error. + msg := fmt.Sprintf("Status type can not be nil") + return res, errors.New(msg) + } + upgradestatus := NewUpgradeStatus(UpgradeStatus{Type: statusType}) + err := objMgr.connector.GetObject(upgradestatus, "", &res) + + return res, err +} + +// GetAllMembers returns all members information +func (objMgr *ObjectManager) GetAllMembers() ([]Member, error) { + var res []Member + + memberObj := NewMember(Member{}) + err := objMgr.connector.GetObject(memberObj, "", &res) + return res, err +} + +// GetCapacityReport returns all capacity for members +func (objMgr *ObjectManager) GetCapacityReport(name string) ([]CapacityReport, error) { + var res []CapacityReport + + capacityObj := CapacityReport{Name: name} + capacityReport := NewCapcityReport(capacityObj) + err := objMgr.connector.GetObject(capacityReport, "", &res) + return res, err +} + +// GetLicense returns the license details for member +func (objMgr *ObjectManager) GetLicense() ([]License, error) { + var res []License + + licenseObj := NewLicense(License{}) + err := objMgr.connector.GetObject(licenseObj, "", &res) + return res, err +} + +// GetLicense returns the license details for grid +func (objMgr *ObjectManager) GetGridLicense() ([]License, error) { + var res []License + + licenseObj := NewGridLicense(License{}) + err := objMgr.connector.GetObject(licenseObj, "", &res) + return res, err +} + +// GetGridInfo returns the details for grid +func (objMgr *ObjectManager) GetGridInfo() ([]Grid, error) { + var res []Grid + + gridObj := NewGrid(Grid{}) + err := objMgr.connector.GetObject(gridObj, "", &res) + return res, err +} + +// GetZoneAuth returns the authoritatives zones +func (objMgr *ObjectManager) GetZoneAuth() ([]ZoneAuth, error) { + var res []ZoneAuth + + zoneAuth := NewZoneAuth(ZoneAuth{}) + err := objMgr.connector.GetObject(zoneAuth, "", &res) + + return res, err +} + +// GetZoneDelegated returns the delegated zone +func (objMgr *ObjectManager) GetZoneDelegated(fqdn string) (*ZoneDelegated, error) { + if len(fqdn) == 0 { + return nil, nil + } + var res []ZoneDelegated + + zoneDelegated := NewZoneDelegated(ZoneDelegated{Fqdn: fqdn}) + + err := objMgr.connector.GetObject(zoneDelegated, "", &res) + + if err != nil || res == nil || len(res) == 0 { + return nil, err + } + + return &res[0], nil +} + +// CreateZoneDelegated creates delegated zone +func (objMgr *ObjectManager) CreateZoneDelegated(fqdn string, delegate_to []NameServer) (*ZoneDelegated, error) { + zoneDelegated := NewZoneDelegated(ZoneDelegated{ + Fqdn: fqdn, + DelegateTo: delegate_to}) + + ref, err := objMgr.connector.CreateObject(zoneDelegated) + zoneDelegated.Ref = ref + + return zoneDelegated, err +} + +// UpdateZoneDelegated updates delegated zone +func (objMgr *ObjectManager) UpdateZoneDelegated(ref string, delegate_to []NameServer) (*ZoneDelegated, error) { + zoneDelegated := NewZoneDelegated(ZoneDelegated{ + Ref: ref, + DelegateTo: delegate_to}) + + refResp, err := objMgr.connector.UpdateObject(zoneDelegated, ref) + zoneDelegated.Ref = refResp + return zoneDelegated, err +} + +// DeleteZoneDelegated deletes delegated zone +func (objMgr *ObjectManager) DeleteZoneDelegated(ref string) (string, error) { + return objMgr.connector.DeleteObject(ref) +} diff --git a/vendor/github.com/infobloxopen/infoblox-go-client/objects.go b/vendor/github.com/infobloxopen/infoblox-go-client/objects.go new file mode 100644 index 0000000..39436ef --- /dev/null +++ b/vendor/github.com/infobloxopen/infoblox-go-client/objects.go @@ -0,0 +1,623 @@ +package ibclient + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" +) + +const MACADDR_ZERO = "00:00:00:00:00:00" + +type Bool bool + +type EA map[string]interface{} + +type EASearch map[string]interface{} + +type EADefListValue string + +type IBBase struct { + objectType string + returnFields []string + eaSearch EASearch +} + +type IBObject interface { + ObjectType() string + ReturnFields() []string + EaSearch() EASearch + //SetReturnFields([]string) +} + +func (obj *IBBase) ObjectType() string { + return obj.objectType +} + +func (obj *IBBase) ReturnFields() []string { + return obj.returnFields +} + +func (obj *IBBase) EaSearch() EASearch { + return obj.eaSearch +} + +type NetworkView struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Name string `json:"name,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewNetworkView(nv NetworkView) *NetworkView { + res := nv + res.objectType = "networkview" + res.returnFields = []string{"extattrs", "name"} + + return &res +} + +// UpgradeStatus object representation +type UpgradeStatus struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Type string `json:"type"` + SubElementStatus []SubElementsStatus `json:"subelements_status,omitempty"` + UpgradeGroup string `json:"upgrade_group,omitempty"` +} + +func NewUpgradeStatus(upgradeStatus UpgradeStatus) *UpgradeStatus { + result := upgradeStatus + returnFields := []string{"subelements_status", "type"} + result.objectType = "upgradestatus" + result.returnFields = returnFields + return &result +} + +// SubElementsStatus object representation +type SubElementsStatus struct { + Ref string `json:"_ref,omitempty"` + CurrentVersion string `json:"current_version"` + ElementStatus string `json:"element_status"` + Ipv4Address string `json:"ipv4_address"` + Ipv6Address string `json:"ipv6_address"` + StatusValue string `json:"status_value"` + StepsTotal int `json:"steps_total"` + StepsCompleted int `json:"steps_completed"` + NodeType string `json:"type"` + Member string `json:"member"` +} + +type Network struct { + IBBase + Ref string `json:"_ref,omitempty"` + NetviewName string `json:"network_view,omitempty"` + Cidr string `json:"network,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewNetwork(nw Network) *Network { + res := nw + res.objectType = "network" + res.returnFields = []string{"extattrs", "network", "network_view"} + + return &res +} + +type ServiceStatus struct { + Desciption string `json:"description,omitempty"` + Service string `json:"service,omitempty"` + Status string `json:"status,omitempty"` +} + +type LanHaPortSetting struct { + HAIpAddress string `json:"ha_ip_address,omitempty"` + HaPortSetting PhysicalPortSetting `json:"ha_port_setting,omitempty"` + LanPortSetting PhysicalPortSetting `json:"lan_port_setting,omitempty"` + MgmtIpv6addr string `json:"mgmt_ipv6addr,omitempty"` + MgmtLan string `json:"mgmt_lan,omitempty"` +} + +type PhysicalPortSetting struct { + AutoPortSettingEnabled bool `json:"auto_port_setting_enabled"` + Duplex string `json:"duplex,omitempty"` + Speed string `json:"speed,omitempty"` +} + +type NetworkSetting struct { + Address string `json:"address"` + Dscp uint `json:"dscp"` + Gateway string `json:"gateway"` + Primary bool `json:"primary"` + SubnetMask string `json:"subnet_mask"` + UseDscp bool `json:"use_dscp,omiempty"` + VlanId uint `json:"vlan_id,omitempty"` +} +type Ipv6Setting struct { + AutoRouterConfigEnabled bool `json:"auto_router_config_enabled"` + CidrPrefix uint `json:"cidr_prefix,omitempty"` + Dscp uint `json:"dscp,omitempty"` + Enabled bool `json:"enabled,omitempty"` + Gateway string `json:"gateway"` + Primary string `json:"primary,omitempty"` + VirtualIp string `json:"virtual_ip"` + VlanId uint `json:"vlan_id,emitempty"` + UseDscp bool `json:"use_dscp,omitempty"` +} + +type NodeInfo struct { + HaStatus string `json:"ha_status,omitempty"` + HwId string `json:"hwid,omitempty"` + HwModel string `json:"hwmodel,omitempty"` + HwPlatform string `json:"hwplatform,omitempty"` + HwType string `json:"hwtype,omitempty"` + Lan2PhysicalSetting PhysicalPortSetting `json:"lan2_physical_setting,omitempty"` + LanHaPortSetting LanHaPortSetting `json:"lan_ha_Port_Setting,omitempty"` + MgmtNetworkSetting NetworkSetting `json:"mgmt_network_setting,omitempty"` + MgmtPhysicalSetting PhysicalPortSetting `json:"mgmt_physical_setting,omitempty"` + PaidNios bool `json:"paid_nios,omitempty"` + PhysicalOid string `json:"physical_oid,omitempty"` + ServiceStatus []ServiceStatus `json:"service_status,omitempty"` + V6MgmtNetworkSetting Ipv6Setting `json:"v6_mgmt_network_setting,omitempty"` +} + +// Member represents NIOS member +type Member struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + HostName string `json:"host_name,omitempty"` + ConfigAddrType string `json:"config_addr_type,omitempty"` + PLATFORM string `json:"platform,omitempty"` + ServiceTypeConfiguration string `json:"service_type_configuration,omitempty"` + Nodeinfo []NodeInfo `json:"node_info,omitempty"` + TimeZone string `json:"time_zone,omitempty"` +} + +func NewMember(member Member) *Member { + res := member + res.objectType = "member" + returnFields := []string{"host_name", "node_info", "time_zone"} + res.returnFields = returnFields + return &res +} + +// License represents license wapi object +type License struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + ExpirationStatus string `json:"expiration_status,omitempty"` + ExpiryDate int `json:"expiry_date,omitempty"` + HwID string `json:"hwid,omitempty"` + Key string `json:"key,omitempty"` + Kind string `json:"kind,omitempty"` + Limit string `json:"limit,omitempty"` + LimitContext string `json:"limit_context,omitempty"` + Licensetype string `json:"type,omitempty"` +} + +func NewGridLicense(license License) *License { + result := license + result.objectType = "license:gridwide" + returnFields := []string{"expiration_status", + "expiry_date", + "key", + "limit", + "limit_context", + "type"} + result.returnFields = returnFields + return &result +} + +func NewLicense(license License) *License { + result := license + returnFields := []string{"expiration_status", + "expiry_date", + "hwid", + "key", + "kind", + "limit", + "limit_context", + "type"} + result.objectType = "member:license" + result.returnFields = returnFields + return &result +} + +// CapacityReport represents capacityreport object +type CapacityReport struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + + Name string `json:"name,omitempty"` + HardwareType string `json:"hardware_type,omitempty"` + MaxCapacity int `json:"max_capacity,omitempty"` + ObjectCount []map[string]interface{} `json:"object_counts,omitempty"` + PercentUsed int `json:"percent_used,omitempty"` + Role string `json:"role,omitempty"` + TotalObjects int `json:"total_objects,omitempty"` +} + +func NewCapcityReport(capReport CapacityReport) *CapacityReport { + res := capReport + returnFields := []string{"name", "hardware_type", "max_capacity", "object_counts", "percent_used", "role", "total_objects"} + res.objectType = "capacityreport" + res.returnFields = returnFields + return &res +} + +type NTPserver struct { + Address string `json:"address,omitempty"` + Burst bool `json:"burst,omitempty"` + EnableAuthentication bool `json:"enable_authentication,omitempty"` + IBurst bool `json:"iburst,omitempty"` + NTPKeyNumber uint `json:"ntp_key_number,omitempty"` + Preffered bool `json:"preffered,omitempty"` +} + +type NTPSetting struct { + EnableNTP bool `json:"enable_ntp,omitempty"` + NTPAcl map[string]interface{} `json:"ntp_acl,omitempty"` + NTPKeys []string `json:"ntp_keys,omitempty"` + NTPKod bool `json:"ntp_kod,omitempty"` + NTPServers []NTPserver `json:"ntp_servers,omitempty"` +} + +type Grid struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Name string `json:"name,omitempty"` + NTPSetting *NTPSetting `json:"ntp_setting,omitempty"` +} + +func NewGrid(grid Grid) *Grid { + result := grid + result.objectType = "grid" + returnFields := []string{"name", "ntp_setting"} + result.returnFields = returnFields + return &result +} + +type NetworkContainer struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + NetviewName string `json:"network_view,omitempty"` + Cidr string `json:"network,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewNetworkContainer(nc NetworkContainer) *NetworkContainer { + res := nc + res.objectType = "networkcontainer" + res.returnFields = []string{"extattrs", "network", "network_view"} + + return &res +} + +type FixedAddress struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + NetviewName string `json:"network_view,omitempty"` + Cidr string `json:"network,omitempty"` + IPAddress string `json:"ipv4addr,omitempty"` + Mac string `json:"mac,omitempty"` + Name string `json:"name,omitempty"` + MatchClient string `json:"match_client,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +/*This is a general struct to add query params used in makeRequest*/ +type QueryParams struct { + forceProxy bool +} + +func NewFixedAddress(fixedAddr FixedAddress) *FixedAddress { + res := fixedAddr + res.objectType = "fixedaddress" + res.returnFields = []string{"extattrs", "ipv4addr", "mac", "name", "network", "network_view"} + + return &res +} + +type EADefinition struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Comment string `json:"comment,omitempty"` + Flags string `json:"flags,omitempty"` + ListValues []EADefListValue `json:"list_values,omitempty"` + Name string `json:"name,omitempty"` + Type string `json:"type,omitempty"` + AllowedObjectTypes []string `json:"allowed_object_types,omitempty"` +} + +func NewEADefinition(eadef EADefinition) *EADefinition { + res := eadef + res.objectType = "extensibleattributedef" + res.returnFields = []string{"allowed_object_types", "comment", "flags", "list_values", "name", "type"} + + return &res +} + +type UserProfile struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Name string `json:"name,omitempty"` +} + +func NewUserProfile(userprofile UserProfile) *UserProfile { + res := userprofile + res.objectType = "userprofile" + res.returnFields = []string{"name"} + + return &res +} + +type RecordA struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Ipv4Addr string `json:"ipv4addr,omitempty"` + Name string `json:"name,omitempty"` + View string `json:"view,omitempty"` + Zone string `json:"zone,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewRecordA(ra RecordA) *RecordA { + res := ra + res.objectType = "record:a" + res.returnFields = []string{"extattrs", "ipv4addr", "name", "view", "zone"} + + return &res +} + +type RecordPTR struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Ipv4Addr string `json:"ipv4addr,omitempty"` + Name string `json:"name,omitempty"` + PtrdName string `json:"ptrdname,omitempty"` + View string `json:"view,omitempty"` + Zone string `json:"zone,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewRecordPTR(rptr RecordPTR) *RecordPTR { + res := rptr + res.objectType = "record:ptr" + res.returnFields = []string{"extattrs", "ipv4addr", "ptrdname", "view", "zone"} + + return &res +} + +type RecordCNAME struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Canonical string `json:"canonical,omitempty"` + Name string `json:"name,omitempty"` + View string `json:"view,omitempty"` + Zone string `json:"zone,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewRecordCNAME(rc RecordCNAME) *RecordCNAME { + res := rc + res.objectType = "record:cname" + res.returnFields = []string{"extattrs", "canonical", "name", "view", "zone"} + + return &res +} + +type HostRecordIpv4Addr struct { + IBBase `json:"-"` + Ipv4Addr string `json:"ipv4addr,omitempty"` + Ref string `json:"_ref,omitempty"` + Mac string `json:"mac,omitempty"` + View string `json:"view,omitempty"` + Cidr string `json:"network,omitempty"` +} + +func NewHostRecordIpv4Addr(hostAddr HostRecordIpv4Addr) *HostRecordIpv4Addr { + res := hostAddr + res.objectType = "record:host_ipv4addr" + return &res +} + +type HostRecord struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Ipv4Addr string `json:"ipv4addr,omitempty"` + Ipv4Addrs []HostRecordIpv4Addr `json:"ipv4addrs,omitempty"` + Name string `json:"name,omitempty"` + View string `json:"view,omitempty"` + Zone string `json:"zone,omitempty"` + EnableDns *bool `json:"configure_for_dns,omitempty"` + NetworkView string `json:"network_view,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewHostRecord(rh HostRecord) *HostRecord { + res := rh + res.objectType = "record:host" + res.returnFields = []string{"extattrs", "ipv4addrs", "name", "view", "zone"} + + return &res +} + +type RecordTXT struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Name string `json:"name,omitempty"` + Text string `json:"text,omitempty"` + TTL int `json:"ttl,omitempty"` + View string `json:"view,omitempty"` + Zone string `json:"zone,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewRecordTXT(rt RecordTXT) *RecordTXT { + res := rt + res.objectType = "record:txt" + res.returnFields = []string{"extattrs", "name", "text", "view", "zone"} + + return &res +} + +type ZoneAuth struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Fqdn string `json:"fqdn,omitempty"` + View string `json:"view,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewZoneAuth(za ZoneAuth) *ZoneAuth { + res := za + res.objectType = "zone_auth" + res.returnFields = []string{"extattrs", "fqdn", "view"} + + return &res +} + +type NameServer struct { + Address string `json:"address,omitempty"` + Name string `json:"name,omitempty"` +} + +type ZoneDelegated struct { + IBBase `json:"-"` + Ref string `json:"_ref,omitempty"` + Fqdn string `json:"fqdn,omitempty"` + DelegateTo []NameServer `json:"delegate_to,omitempty"` + View string `json:"view,omitempty"` + Ea EA `json:"extattrs,omitempty"` +} + +func NewZoneDelegated(za ZoneDelegated) *ZoneDelegated { + res := za + res.objectType = "zone_delegated" + res.returnFields = []string{"extattrs", "fqdn", "view", "delegate_to"} + + return &res +} + +func (ea EA) MarshalJSON() ([]byte, error) { + m := make(map[string]interface{}) + for k, v := range ea { + value := make(map[string]interface{}) + value["value"] = v + m[k] = value + } + + return json.Marshal(m) +} + +func (eas EASearch) MarshalJSON() ([]byte, error) { + m := make(map[string]interface{}) + for k, v := range eas { + m["*"+k] = v + } + + return json.Marshal(m) +} + +func (v EADefListValue) MarshalJSON() ([]byte, error) { + m := make(map[string]string) + m["value"] = string(v) + + return json.Marshal(m) +} + +func (b Bool) MarshalJSON() ([]byte, error) { + if b { + return json.Marshal("True") + } + + return json.Marshal("False") +} + +func (ea *EA) UnmarshalJSON(b []byte) (err error) { + var m map[string]map[string]interface{} + + decoder := json.NewDecoder(bytes.NewBuffer(b)) + decoder.UseNumber() + err = decoder.Decode(&m) + if err != nil { + return + } + + *ea = make(EA) + for k, v := range m { + val := v["value"] + switch valType := reflect.TypeOf(val).String(); valType { + case "json.Number": + var i64 int64 + i64, err = val.(json.Number).Int64() + val = int(i64) + case "string": + if val.(string) == "True" { + val = Bool(true) + } else if val.(string) == "False" { + val = Bool(false) + } + case "[]interface {}": + nval := val.([]interface{}) + nVals := make([]string, len(nval)) + for i, v := range nval { + nVals[i] = fmt.Sprintf("%v", v) + } + val = nVals + default: + val = fmt.Sprintf("%v", val) + } + + (*ea)[k] = val + } + + return +} + +func (v *EADefListValue) UnmarshalJSON(b []byte) (err error) { + var m map[string]string + err = json.Unmarshal(b, &m) + if err != nil { + return + } + + *v = EADefListValue(m["value"]) + return +} + +type RequestBody struct { + Data map[string]interface{} `json:"data,omitempty"` + Args map[string]string `json:"args,omitempty"` + Method string `json:"method"` + Object string `json:"object,omitempty"` + EnableSubstitution bool `json:"enable_substitution,omitempty"` + AssignState map[string]string `json:"assign_state,omitempty"` + Discard bool `json:"discard,omitempty"` +} + +type SingleRequest struct { + IBBase `json:"-"` + Body *RequestBody +} + +type MultiRequest struct { + IBBase `json:"-"` + Body []*RequestBody +} + +func (r *MultiRequest) MarshalJSON() ([]byte, error) { + return json.Marshal(r.Body) +} + +func NewMultiRequest(body []*RequestBody) *MultiRequest { + req := &MultiRequest{Body: body} + req.objectType = "request" + return req +} + +func NewRequest(body *RequestBody) *SingleRequest { + req := &SingleRequest{Body: body} + req.objectType = "request" + return req +} diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/LICENSE b/vendor/github.com/konsorten/go-windows-terminal-sequences/LICENSE new file mode 100644 index 0000000..14127cd --- /dev/null +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/LICENSE @@ -0,0 +1,9 @@ +(The MIT License) + +Copyright (c) 2017 marvin + konsorten GmbH (open-source@konsorten.de) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +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. diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md b/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md new file mode 100644 index 0000000..949b77e --- /dev/null +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md @@ -0,0 +1,40 @@ +# Windows Terminal Sequences + +This library allow for enabling Windows terminal color support for Go. + +See [Console Virtual Terminal Sequences](https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) for details. + +## Usage + +```go +import ( + "syscall" + + sequences "github.com/konsorten/go-windows-terminal-sequences" +) + +func main() { + sequences.EnableVirtualTerminalProcessing(syscall.Stdout, true) +} + +``` + +## Authors + +The tool is sponsored by the [marvin + konsorten GmbH](http://www.konsorten.de). + +We thank all the authors who provided code to this library: + +* Felix Kollmann + +## License + +(The MIT License) + +Copyright (c) 2018 marvin + konsorten GmbH (open-source@konsorten.de) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +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. diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/go.mod b/vendor/github.com/konsorten/go-windows-terminal-sequences/go.mod new file mode 100644 index 0000000..716c613 --- /dev/null +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/go.mod @@ -0,0 +1 @@ +module github.com/konsorten/go-windows-terminal-sequences diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go new file mode 100644 index 0000000..ef18d8f --- /dev/null +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go @@ -0,0 +1,36 @@ +// +build windows + +package sequences + +import ( + "syscall" + "unsafe" +) + +var ( + kernel32Dll *syscall.LazyDLL = syscall.NewLazyDLL("Kernel32.dll") + setConsoleMode *syscall.LazyProc = kernel32Dll.NewProc("SetConsoleMode") +) + +func EnableVirtualTerminalProcessing(stream syscall.Handle, enable bool) error { + const ENABLE_VIRTUAL_TERMINAL_PROCESSING uint32 = 0x4 + + var mode uint32 + err := syscall.GetConsoleMode(syscall.Stdout, &mode) + if err != nil { + return err + } + + if enable { + mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING + } else { + mode &^= ENABLE_VIRTUAL_TERMINAL_PROCESSING + } + + ret, _, err := setConsoleMode.Call(uintptr(unsafe.Pointer(stream)), uintptr(mode)) + if ret == 0 { + return err + } + + return nil +} diff --git a/vendor/github.com/sirupsen/logrus/.gitignore b/vendor/github.com/sirupsen/logrus/.gitignore new file mode 100644 index 0000000..6b7d7d1 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/.gitignore @@ -0,0 +1,2 @@ +logrus +vendor diff --git a/vendor/github.com/sirupsen/logrus/.travis.yml b/vendor/github.com/sirupsen/logrus/.travis.yml new file mode 100644 index 0000000..848938a --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/.travis.yml @@ -0,0 +1,25 @@ +language: go +go_import_path: github.com/sirupsen/logrus +git: + depth: 1 +env: + - GO111MODULE=on + - GO111MODULE=off +go: [ 1.11.x, 1.12.x ] +os: [ linux, osx ] +matrix: + exclude: + - go: 1.12.x + env: GO111MODULE=off + - go: 1.11.x + os: osx +install: + - ./travis/install.sh + - if [[ "$GO111MODULE" == "on" ]]; then go mod download; fi + - if [[ "$GO111MODULE" == "off" ]]; then go get github.com/stretchr/testify/assert golang.org/x/sys/unix github.com/konsorten/go-windows-terminal-sequences; fi +script: + - ./travis/cross_build.sh + - export GOMAXPROCS=4 + - export GORACE=halt_on_error=1 + - go test -race -v ./... + - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then go test -race -v -tags appengine ./... ; fi diff --git a/vendor/github.com/sirupsen/logrus/CHANGELOG.md b/vendor/github.com/sirupsen/logrus/CHANGELOG.md new file mode 100644 index 0000000..51a7ab0 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/CHANGELOG.md @@ -0,0 +1,200 @@ +# 1.4.2 + * Fixes build break for plan9, nacl, solaris +# 1.4.1 +This new release introduces: + * Enhance TextFormatter to not print caller information when they are empty (#944) + * Remove dependency on golang.org/x/crypto (#932, #943) + +Fixes: + * Fix Entry.WithContext method to return a copy of the initial entry (#941) + +# 1.4.0 +This new release introduces: + * Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848). + * Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter (#909, #911) + * Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919). + +Fixes: + * Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893). + * Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903) + * Fix infinite recursion on unknown `Level.String()` (#907) + * Fix race condition in `getCaller` (#916). + + +# 1.3.0 +This new release introduces: + * Log, Logf, Logln functions for Logger and Entry that take a Level + +Fixes: + * Building prometheus node_exporter on AIX (#840) + * Race condition in TextFormatter (#468) + * Travis CI import path (#868) + * Remove coloured output on Windows (#862) + * Pointer to func as field in JSONFormatter (#870) + * Properly marshal Levels (#873) + +# 1.2.0 +This new release introduces: + * A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued + * A new trace level named `Trace` whose level is below `Debug` + * A configurable exit function to be called upon a Fatal trace + * The `Level` object now implements `encoding.TextUnmarshaler` interface + +# 1.1.1 +This is a bug fix release. + * fix the build break on Solaris + * don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized + +# 1.1.0 +This new release introduces: + * several fixes: + * a fix for a race condition on entry formatting + * proper cleanup of previously used entries before putting them back in the pool + * the extra new line at the end of message in text formatter has been removed + * a new global public API to check if a level is activated: IsLevelEnabled + * the following methods have been added to the Logger object + * IsLevelEnabled + * SetFormatter + * SetOutput + * ReplaceHooks + * introduction of go module + * an indent configuration for the json formatter + * output colour support for windows + * the field sort function is now configurable for text formatter + * the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater + +# 1.0.6 + +This new release introduces: + * a new api WithTime which allows to easily force the time of the log entry + which is mostly useful for logger wrapper + * a fix reverting the immutability of the entry given as parameter to the hooks + a new configuration field of the json formatter in order to put all the fields + in a nested dictionnary + * a new SetOutput method in the Logger + * a new configuration of the textformatter to configure the name of the default keys + * a new configuration of the text formatter to disable the level truncation + +# 1.0.5 + +* Fix hooks race (#707) +* Fix panic deadlock (#695) + +# 1.0.4 + +* Fix race when adding hooks (#612) +* Fix terminal check in AppEngine (#635) + +# 1.0.3 + +* Replace example files with testable examples + +# 1.0.2 + +* bug: quote non-string values in text formatter (#583) +* Make (*Logger) SetLevel a public method + +# 1.0.1 + +* bug: fix escaping in text formatter (#575) + +# 1.0.0 + +* Officially changed name to lower-case +* bug: colors on Windows 10 (#541) +* bug: fix race in accessing level (#512) + +# 0.11.5 + +* feature: add writer and writerlevel to entry (#372) + +# 0.11.4 + +* bug: fix undefined variable on solaris (#493) + +# 0.11.3 + +* formatter: configure quoting of empty values (#484) +* formatter: configure quoting character (default is `"`) (#484) +* bug: fix not importing io correctly in non-linux environments (#481) + +# 0.11.2 + +* bug: fix windows terminal detection (#476) + +# 0.11.1 + +* bug: fix tty detection with custom out (#471) + +# 0.11.0 + +* performance: Use bufferpool to allocate (#370) +* terminal: terminal detection for app-engine (#343) +* feature: exit handler (#375) + +# 0.10.0 + +* feature: Add a test hook (#180) +* feature: `ParseLevel` is now case-insensitive (#326) +* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308) +* performance: avoid re-allocations on `WithFields` (#335) + +# 0.9.0 + +* logrus/text_formatter: don't emit empty msg +* logrus/hooks/airbrake: move out of main repository +* logrus/hooks/sentry: move out of main repository +* logrus/hooks/papertrail: move out of main repository +* logrus/hooks/bugsnag: move out of main repository +* logrus/core: run tests with `-race` +* logrus/core: detect TTY based on `stderr` +* logrus/core: support `WithError` on logger +* logrus/core: Solaris support + +# 0.8.7 + +* logrus/core: fix possible race (#216) +* logrus/doc: small typo fixes and doc improvements + + +# 0.8.6 + +* hooks/raven: allow passing an initialized client + +# 0.8.5 + +* logrus/core: revert #208 + +# 0.8.4 + +* formatter/text: fix data race (#218) + +# 0.8.3 + +* logrus/core: fix entry log level (#208) +* logrus/core: improve performance of text formatter by 40% +* logrus/core: expose `LevelHooks` type +* logrus/core: add support for DragonflyBSD and NetBSD +* formatter/text: print structs more verbosely + +# 0.8.2 + +* logrus: fix more Fatal family functions + +# 0.8.1 + +* logrus: fix not exiting on `Fatalf` and `Fatalln` + +# 0.8.0 + +* logrus: defaults to stderr instead of stdout +* hooks/sentry: add special field for `*http.Request` +* formatter/text: ignore Windows for colors + +# 0.7.3 + +* formatter/\*: allow configuration of timestamp layout + +# 0.7.2 + +* formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/sirupsen/logrus/LICENSE b/vendor/github.com/sirupsen/logrus/LICENSE new file mode 100644 index 0000000..f090cb4 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Simon Eskildsen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +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. diff --git a/vendor/github.com/sirupsen/logrus/README.md b/vendor/github.com/sirupsen/logrus/README.md new file mode 100644 index 0000000..a4796eb --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/README.md @@ -0,0 +1,495 @@ +# Logrus :walrus: [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) + +Logrus is a structured logger for Go (golang), completely API compatible with +the standard library logger. + +**Seeing weird case-sensitive problems?** It's in the past been possible to +import Logrus as both upper- and lower-case. Due to the Go package environment, +this caused issues in the community and we needed a standard. Some environments +experienced problems with the upper-case variant, so the lower-case was decided. +Everything using `logrus` will need to use the lower-case: +`github.com/sirupsen/logrus`. Any package that isn't, should be changed. + +To fix Glide, see [these +comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). +For an in-depth explanation of the casing issue, see [this +comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). + +**Are you interested in assisting in maintaining Logrus?** Currently I have a +lot of obligations, and I am unable to provide Logrus with the maintainership it +needs. If you'd like to help, please reach out to me at `simon at author's +username dot com`. + +Nicely color-coded in development (when a TTY is attached, otherwise just +plain text): + +![Colored](http://i.imgur.com/PY7qMwd.png) + +With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash +or Splunk: + +```json +{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the +ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} + +{"level":"warning","msg":"The group's number increased tremendously!", +"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"A giant walrus appears!", +"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", +"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} + +{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, +"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} +``` + +With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not +attached, the output is compatible with the +[logfmt](http://godoc.org/github.com/kr/logfmt) format: + +```text +time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 +time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 +time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true +time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 +time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 +time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true +``` +To ensure this behaviour even if a TTY is attached, set your formatter as follows: + +```go + log.SetFormatter(&log.TextFormatter{ + DisableColors: true, + FullTimestamp: true, + }) +``` + +#### Logging Method Name + +If you wish to add the calling method as a field, instruct the logger via: +```go +log.SetReportCaller(true) +``` +This adds the caller as 'method' like so: + +```json +{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by", +"time":"2014-03-10 19:57:38.562543129 -0400 EDT"} +``` + +```text +time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin +``` +Note that this does add measurable overhead - the cost will depend on the version of Go, but is +between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your +environment via benchmarks: +``` +go test -bench=.*CallerTracing +``` + + +#### Case-sensitivity + +The organization's name was changed to lower-case--and this will not be changed +back. If you are getting import conflicts due to case sensitivity, please use +the lower-case import: `github.com/sirupsen/logrus`. + +#### Example + +The simplest way to use Logrus is simply the package-level exported logger: + +```go +package main + +import ( + log "github.com/sirupsen/logrus" +) + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + }).Info("A walrus appears") +} +``` + +Note that it's completely api-compatible with the stdlib logger, so you can +replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"` +and you'll now have the flexibility of Logrus. You can customize it all you +want: + +```go +package main + +import ( + "os" + log "github.com/sirupsen/logrus" +) + +func init() { + // Log as JSON instead of the default ASCII formatter. + log.SetFormatter(&log.JSONFormatter{}) + + // Output to stdout instead of the default stderr + // Can be any io.Writer, see below for File example + log.SetOutput(os.Stdout) + + // Only log the warning severity or above. + log.SetLevel(log.WarnLevel) +} + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(log.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(log.Fields{ + "omg": true, + "number": 100, + }).Fatal("The ice breaks!") + + // A common pattern is to re-use fields between logging statements by re-using + // the logrus.Entry returned from WithFields() + contextLogger := log.WithFields(log.Fields{ + "common": "this is a common field", + "other": "I also should be logged always", + }) + + contextLogger.Info("I'll be logged with common and other field") + contextLogger.Info("Me too") +} +``` + +For more advanced usage such as logging to multiple locations from the same +application, you can also create an instance of the `logrus` Logger: + +```go +package main + +import ( + "os" + "github.com/sirupsen/logrus" +) + +// Create a new instance of the logger. You can have any number of instances. +var log = logrus.New() + +func main() { + // The API for setting attributes is a little different than the package level + // exported logger. See Godoc. + log.Out = os.Stdout + + // You could set this to any `io.Writer` such as a file + // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) + // if err == nil { + // log.Out = file + // } else { + // log.Info("Failed to log to file, using default stderr") + // } + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") +} +``` + +#### Fields + +Logrus encourages careful, structured logging through logging fields instead of +long, unparseable error messages. For example, instead of: `log.Fatalf("Failed +to send event %s to topic %s with key %d")`, you should log the much more +discoverable: + +```go +log.WithFields(log.Fields{ + "event": event, + "topic": topic, + "key": key, +}).Fatal("Failed to send event") +``` + +We've found this API forces you to think about logging in a way that produces +much more useful logging messages. We've been in countless situations where just +a single added field to a log statement that was already there would've saved us +hours. The `WithFields` call is optional. + +In general, with Logrus using any of the `printf`-family functions should be +seen as a hint you should add a field, however, you can still use the +`printf`-family functions with Logrus. + +#### Default Fields + +Often it's helpful to have fields _always_ attached to log statements in an +application or parts of one. For example, you may want to always log the +`request_id` and `user_ip` in the context of a request. Instead of writing +`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on +every line, you can create a `logrus.Entry` to pass around instead: + +```go +requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) +requestLogger.Info("something happened on that request") # will log request_id and user_ip +requestLogger.Warn("something not great happened") +``` + +#### Hooks + +You can add hooks for logging levels. For example to send errors to an exception +tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to +multiple places simultaneously, e.g. syslog. + +Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in +`init`: + +```go +import ( + log "github.com/sirupsen/logrus" + "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake" + logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" + "log/syslog" +) + +func init() { + + // Use the Airbrake hook to report errors that have Error severity or above to + // an exception tracker. You can create custom hooks, see the Hooks section. + log.AddHook(airbrake.NewHook(123, "xyz", "production")) + + hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") + if err != nil { + log.Error("Unable to connect to local syslog daemon") + } else { + log.AddHook(hook) + } +} +``` +Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). + +A list of currently known of service hook can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) + + +#### Level logging + +Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic. + +```go +log.Trace("Something very low level.") +log.Debug("Useful debugging information.") +log.Info("Something noteworthy happened!") +log.Warn("You should probably take a look at this.") +log.Error("Something failed but I'm not quitting.") +// Calls os.Exit(1) after logging +log.Fatal("Bye.") +// Calls panic() after logging +log.Panic("I'm bailing.") +``` + +You can set the logging level on a `Logger`, then it will only log entries with +that severity or anything above it: + +```go +// Will log anything that is info or above (warn, error, fatal, panic). Default. +log.SetLevel(log.InfoLevel) +``` + +It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose +environment if your application has that. + +#### Entries + +Besides the fields added with `WithField` or `WithFields` some fields are +automatically added to all logging events: + +1. `time`. The timestamp when the entry was created. +2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after + the `AddFields` call. E.g. `Failed to send event.` +3. `level`. The logging level. E.g. `info`. + +#### Environments + +Logrus has no notion of environment. + +If you wish for hooks and formatters to only be used in specific environments, +you should handle that yourself. For example, if your application has a global +variable `Environment`, which is a string representation of the environment you +could do: + +```go +import ( + log "github.com/sirupsen/logrus" +) + +init() { + // do something here to set environment depending on an environment variable + // or command-line flag + if Environment == "production" { + log.SetFormatter(&log.JSONFormatter{}) + } else { + // The TextFormatter is default, you don't actually have to do this. + log.SetFormatter(&log.TextFormatter{}) + } +} +``` + +This configuration is how `logrus` was intended to be used, but JSON in +production is mostly only useful if you do log aggregation with tools like +Splunk or Logstash. + +#### Formatters + +The built-in logging formatters are: + +* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise + without colors. + * *Note:* to force colored output when there is no TTY, set the `ForceColors` + field to `true`. To force no colored output even if there is a TTY set the + `DisableColors` field to `true`. For Windows, see + [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). + * When colors are enabled, levels are truncated to 4 characters by default. To disable + truncation set the `DisableLevelTruncation` field to `true`. + * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). +* `logrus.JSONFormatter`. Logs fields as JSON. + * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). + +Third party logging formatters: + +* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine. +* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html). +* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. +* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. +* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. +* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure. + +You can define your formatter by implementing the `Formatter` interface, +requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a +`Fields` type (`map[string]interface{}`) with all your fields as well as the +default ones (see Entries section above): + +```go +type MyJSONFormatter struct { +} + +log.SetFormatter(new(MyJSONFormatter)) + +func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { + // Note this doesn't include Time, Level and Message which are available on + // the Entry. Consult `godoc` on information about those fields or read the + // source of the official loggers. + serialized, err := json.Marshal(entry.Data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) + } + return append(serialized, '\n'), nil +} +``` + +#### Logger as an `io.Writer` + +Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. + +```go +w := logger.Writer() +defer w.Close() + +srv := http.Server{ + // create a stdlib log.Logger that writes to + // logrus.Logger. + ErrorLog: log.New(w, "", 0), +} +``` + +Each line written to that writer will be printed the usual way, using formatters +and hooks. The level for those entries is `info`. + +This means that we can override the standard library logger easily: + +```go +logger := logrus.New() +logger.Formatter = &logrus.JSONFormatter{} + +// Use logrus for standard log output +// Note that `log` here references stdlib's log +// Not logrus imported under the name `log`. +log.SetOutput(logger.Writer()) +``` + +#### Rotation + +Log rotation is not provided with Logrus. Log rotation should be done by an +external program (like `logrotate(8)`) that can compress and delete old log +entries. It should not be a feature of the application-level logger. + +#### Tools + +| Tool | Description | +| ---- | ----------- | +|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| +|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | + +#### Testing + +Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: + +* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook +* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): + +```go +import( + "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus/hooks/test" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestSomething(t*testing.T){ + logger, hook := test.NewNullLogger() + logger.Error("Helloerror") + + assert.Equal(t, 1, len(hook.Entries)) + assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level) + assert.Equal(t, "Helloerror", hook.LastEntry().Message) + + hook.Reset() + assert.Nil(t, hook.LastEntry()) +} +``` + +#### Fatal handlers + +Logrus can register one or more functions that will be called when any `fatal` +level message is logged. The registered handlers will be executed before +logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need +to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. + +``` +... +handler := func() { + // gracefully shutdown something... +} +logrus.RegisterExitHandler(handler) +... +``` + +#### Thread safety + +By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs. +If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. + +Situation when locking is not needed includes: + +* You have no hooks registered, or hooks calling is already thread-safe. + +* Writing to logger.Out is already thread-safe, for example: + + 1) logger.Out is protected by locks. + + 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing) + + (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) diff --git a/vendor/github.com/sirupsen/logrus/alt_exit.go b/vendor/github.com/sirupsen/logrus/alt_exit.go new file mode 100644 index 0000000..8fd189e --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/alt_exit.go @@ -0,0 +1,76 @@ +package logrus + +// The following code was sourced and modified from the +// https://github.com/tebeka/atexit package governed by the following license: +// +// Copyright (c) 2012 Miki Tebeka . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// 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. + +import ( + "fmt" + "os" +) + +var handlers = []func(){} + +func runHandler(handler func()) { + defer func() { + if err := recover(); err != nil { + fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) + } + }() + + handler() +} + +func runHandlers() { + for _, handler := range handlers { + runHandler(handler) + } +} + +// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) +func Exit(code int) { + runHandlers() + os.Exit(code) +} + +// RegisterExitHandler appends a Logrus Exit handler to the list of handlers, +// call logrus.Exit to invoke all handlers. The handlers will also be invoked when +// any Fatal log entry is made. +// +// This method is useful when a caller wishes to use logrus to log a fatal +// message but also needs to gracefully shutdown. An example usecase could be +// closing database connections, or sending a alert that the application is +// closing. +func RegisterExitHandler(handler func()) { + handlers = append(handlers, handler) +} + +// DeferExitHandler prepends a Logrus Exit handler to the list of handlers, +// call logrus.Exit to invoke all handlers. The handlers will also be invoked when +// any Fatal log entry is made. +// +// This method is useful when a caller wishes to use logrus to log a fatal +// message but also needs to gracefully shutdown. An example usecase could be +// closing database connections, or sending a alert that the application is +// closing. +func DeferExitHandler(handler func()) { + handlers = append([]func(){handler}, handlers...) +} diff --git a/vendor/github.com/sirupsen/logrus/appveyor.yml b/vendor/github.com/sirupsen/logrus/appveyor.yml new file mode 100644 index 0000000..96c2ce1 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/appveyor.yml @@ -0,0 +1,14 @@ +version: "{build}" +platform: x64 +clone_folder: c:\gopath\src\github.com\sirupsen\logrus +environment: + GOPATH: c:\gopath +branches: + only: + - master +install: + - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% + - go version +build_script: + - go get -t + - go test diff --git a/vendor/github.com/sirupsen/logrus/doc.go b/vendor/github.com/sirupsen/logrus/doc.go new file mode 100644 index 0000000..da67aba --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/doc.go @@ -0,0 +1,26 @@ +/* +Package logrus is a structured logger for Go, completely API compatible with the standard library logger. + + +The simplest way to use Logrus is simply the package-level exported logger: + + package main + + import ( + log "github.com/sirupsen/logrus" + ) + + func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "number": 1, + "size": 10, + }).Info("A walrus appears") + } + +Output: + time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 + +For a full guide visit https://github.com/sirupsen/logrus +*/ +package logrus diff --git a/vendor/github.com/sirupsen/logrus/entry.go b/vendor/github.com/sirupsen/logrus/entry.go new file mode 100644 index 0000000..63e2558 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/entry.go @@ -0,0 +1,407 @@ +package logrus + +import ( + "bytes" + "context" + "fmt" + "os" + "reflect" + "runtime" + "strings" + "sync" + "time" +) + +var ( + bufferPool *sync.Pool + + // qualified package name, cached at first use + logrusPackage string + + // Positions in the call stack when tracing to report the calling method + minimumCallerDepth int + + // Used for caller information initialisation + callerInitOnce sync.Once +) + +const ( + maximumCallerDepth int = 25 + knownLogrusFrames int = 4 +) + +func init() { + bufferPool = &sync.Pool{ + New: func() interface{} { + return new(bytes.Buffer) + }, + } + + // start at the bottom of the stack before the package-name cache is primed + minimumCallerDepth = 1 +} + +// Defines the key when adding errors using WithError. +var ErrorKey = "error" + +// An entry is the final or intermediate Logrus logging entry. It contains all +// the fields passed with WithField{,s}. It's finally logged when Trace, Debug, +// Info, Warn, Error, Fatal or Panic is called on it. These objects can be +// reused and passed around as much as you wish to avoid field duplication. +type Entry struct { + Logger *Logger + + // Contains all the fields set by the user. + Data Fields + + // Time at which the log entry was created + Time time.Time + + // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic + // This field will be set on entry firing and the value will be equal to the one in Logger struct field. + Level Level + + // Calling method, with package name + Caller *runtime.Frame + + // Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic + Message string + + // When formatter is called in entry.log(), a Buffer may be set to entry + Buffer *bytes.Buffer + + // Contains the context set by the user. Useful for hook processing etc. + Context context.Context + + // err may contain a field formatting error + err string +} + +func NewEntry(logger *Logger) *Entry { + return &Entry{ + Logger: logger, + // Default is three fields, plus one optional. Give a little extra room. + Data: make(Fields, 6), + } +} + +// Returns the string representation from the reader and ultimately the +// formatter. +func (entry *Entry) String() (string, error) { + serialized, err := entry.Logger.Formatter.Format(entry) + if err != nil { + return "", err + } + str := string(serialized) + return str, nil +} + +// Add an error as single field (using the key defined in ErrorKey) to the Entry. +func (entry *Entry) WithError(err error) *Entry { + return entry.WithField(ErrorKey, err) +} + +// Add a context to the Entry. +func (entry *Entry) WithContext(ctx context.Context) *Entry { + return &Entry{Logger: entry.Logger, Data: entry.Data, Time: entry.Time, err: entry.err, Context: ctx} +} + +// Add a single field to the Entry. +func (entry *Entry) WithField(key string, value interface{}) *Entry { + return entry.WithFields(Fields{key: value}) +} + +// Add a map of fields to the Entry. +func (entry *Entry) WithFields(fields Fields) *Entry { + data := make(Fields, len(entry.Data)+len(fields)) + for k, v := range entry.Data { + data[k] = v + } + fieldErr := entry.err + for k, v := range fields { + isErrField := false + if t := reflect.TypeOf(v); t != nil { + switch t.Kind() { + case reflect.Func: + isErrField = true + case reflect.Ptr: + isErrField = t.Elem().Kind() == reflect.Func + } + } + if isErrField { + tmp := fmt.Sprintf("can not add field %q", k) + if fieldErr != "" { + fieldErr = entry.err + ", " + tmp + } else { + fieldErr = tmp + } + } else { + data[k] = v + } + } + return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context} +} + +// Overrides the time of the Entry. +func (entry *Entry) WithTime(t time.Time) *Entry { + return &Entry{Logger: entry.Logger, Data: entry.Data, Time: t, err: entry.err, Context: entry.Context} +} + +// getPackageName reduces a fully qualified function name to the package name +// There really ought to be to be a better way... +func getPackageName(f string) string { + for { + lastPeriod := strings.LastIndex(f, ".") + lastSlash := strings.LastIndex(f, "/") + if lastPeriod > lastSlash { + f = f[:lastPeriod] + } else { + break + } + } + + return f +} + +// getCaller retrieves the name of the first non-logrus calling function +func getCaller() *runtime.Frame { + + // cache this package's fully-qualified name + callerInitOnce.Do(func() { + pcs := make([]uintptr, 2) + _ = runtime.Callers(0, pcs) + logrusPackage = getPackageName(runtime.FuncForPC(pcs[1]).Name()) + + // now that we have the cache, we can skip a minimum count of known-logrus functions + // XXX this is dubious, the number of frames may vary + minimumCallerDepth = knownLogrusFrames + }) + + // Restrict the lookback frames to avoid runaway lookups + pcs := make([]uintptr, maximumCallerDepth) + depth := runtime.Callers(minimumCallerDepth, pcs) + frames := runtime.CallersFrames(pcs[:depth]) + + for f, again := frames.Next(); again; f, again = frames.Next() { + pkg := getPackageName(f.Function) + + // If the caller isn't part of this package, we're done + if pkg != logrusPackage { + return &f + } + } + + // if we got here, we failed to find the caller's context + return nil +} + +func (entry Entry) HasCaller() (has bool) { + return entry.Logger != nil && + entry.Logger.ReportCaller && + entry.Caller != nil +} + +// This function is not declared with a pointer value because otherwise +// race conditions will occur when using multiple goroutines +func (entry Entry) log(level Level, msg string) { + var buffer *bytes.Buffer + + // Default to now, but allow users to override if they want. + // + // We don't have to worry about polluting future calls to Entry#log() + // with this assignment because this function is declared with a + // non-pointer receiver. + if entry.Time.IsZero() { + entry.Time = time.Now() + } + + entry.Level = level + entry.Message = msg + if entry.Logger.ReportCaller { + entry.Caller = getCaller() + } + + entry.fireHooks() + + buffer = bufferPool.Get().(*bytes.Buffer) + buffer.Reset() + defer bufferPool.Put(buffer) + entry.Buffer = buffer + + entry.write() + + entry.Buffer = nil + + // To avoid Entry#log() returning a value that only would make sense for + // panic() to use in Entry#Panic(), we avoid the allocation by checking + // directly here. + if level <= PanicLevel { + panic(&entry) + } +} + +func (entry *Entry) fireHooks() { + entry.Logger.mu.Lock() + defer entry.Logger.mu.Unlock() + err := entry.Logger.Hooks.Fire(entry.Level, entry) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) + } +} + +func (entry *Entry) write() { + entry.Logger.mu.Lock() + defer entry.Logger.mu.Unlock() + serialized, err := entry.Logger.Formatter.Format(entry) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) + } else { + _, err = entry.Logger.Out.Write(serialized) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) + } + } +} + +func (entry *Entry) Log(level Level, args ...interface{}) { + if entry.Logger.IsLevelEnabled(level) { + entry.log(level, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Trace(args ...interface{}) { + entry.Log(TraceLevel, args...) +} + +func (entry *Entry) Debug(args ...interface{}) { + entry.Log(DebugLevel, args...) +} + +func (entry *Entry) Print(args ...interface{}) { + entry.Info(args...) +} + +func (entry *Entry) Info(args ...interface{}) { + entry.Log(InfoLevel, args...) +} + +func (entry *Entry) Warn(args ...interface{}) { + entry.Log(WarnLevel, args...) +} + +func (entry *Entry) Warning(args ...interface{}) { + entry.Warn(args...) +} + +func (entry *Entry) Error(args ...interface{}) { + entry.Log(ErrorLevel, args...) +} + +func (entry *Entry) Fatal(args ...interface{}) { + entry.Log(FatalLevel, args...) + entry.Logger.Exit(1) +} + +func (entry *Entry) Panic(args ...interface{}) { + entry.Log(PanicLevel, args...) + panic(fmt.Sprint(args...)) +} + +// Entry Printf family functions + +func (entry *Entry) Logf(level Level, format string, args ...interface{}) { + if entry.Logger.IsLevelEnabled(level) { + entry.Log(level, fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Tracef(format string, args ...interface{}) { + entry.Logf(TraceLevel, format, args...) +} + +func (entry *Entry) Debugf(format string, args ...interface{}) { + entry.Logf(DebugLevel, format, args...) +} + +func (entry *Entry) Infof(format string, args ...interface{}) { + entry.Logf(InfoLevel, format, args...) +} + +func (entry *Entry) Printf(format string, args ...interface{}) { + entry.Infof(format, args...) +} + +func (entry *Entry) Warnf(format string, args ...interface{}) { + entry.Logf(WarnLevel, format, args...) +} + +func (entry *Entry) Warningf(format string, args ...interface{}) { + entry.Warnf(format, args...) +} + +func (entry *Entry) Errorf(format string, args ...interface{}) { + entry.Logf(ErrorLevel, format, args...) +} + +func (entry *Entry) Fatalf(format string, args ...interface{}) { + entry.Logf(FatalLevel, format, args...) + entry.Logger.Exit(1) +} + +func (entry *Entry) Panicf(format string, args ...interface{}) { + entry.Logf(PanicLevel, format, args...) +} + +// Entry Println family functions + +func (entry *Entry) Logln(level Level, args ...interface{}) { + if entry.Logger.IsLevelEnabled(level) { + entry.Log(level, entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Traceln(args ...interface{}) { + entry.Logln(TraceLevel, args...) +} + +func (entry *Entry) Debugln(args ...interface{}) { + entry.Logln(DebugLevel, args...) +} + +func (entry *Entry) Infoln(args ...interface{}) { + entry.Logln(InfoLevel, args...) +} + +func (entry *Entry) Println(args ...interface{}) { + entry.Infoln(args...) +} + +func (entry *Entry) Warnln(args ...interface{}) { + entry.Logln(WarnLevel, args...) +} + +func (entry *Entry) Warningln(args ...interface{}) { + entry.Warnln(args...) +} + +func (entry *Entry) Errorln(args ...interface{}) { + entry.Logln(ErrorLevel, args...) +} + +func (entry *Entry) Fatalln(args ...interface{}) { + entry.Logln(FatalLevel, args...) + entry.Logger.Exit(1) +} + +func (entry *Entry) Panicln(args ...interface{}) { + entry.Logln(PanicLevel, args...) +} + +// Sprintlnn => Sprint no newline. This is to get the behavior of how +// fmt.Sprintln where spaces are always added between operands, regardless of +// their type. Instead of vendoring the Sprintln implementation to spare a +// string allocation, we do the simplest thing. +func (entry *Entry) sprintlnn(args ...interface{}) string { + msg := fmt.Sprintln(args...) + return msg[:len(msg)-1] +} diff --git a/vendor/github.com/sirupsen/logrus/exported.go b/vendor/github.com/sirupsen/logrus/exported.go new file mode 100644 index 0000000..62fc2f2 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/exported.go @@ -0,0 +1,225 @@ +package logrus + +import ( + "context" + "io" + "time" +) + +var ( + // std is the name of the standard logger in stdlib `log` + std = New() +) + +func StandardLogger() *Logger { + return std +} + +// SetOutput sets the standard logger output. +func SetOutput(out io.Writer) { + std.SetOutput(out) +} + +// SetFormatter sets the standard logger formatter. +func SetFormatter(formatter Formatter) { + std.SetFormatter(formatter) +} + +// SetReportCaller sets whether the standard logger will include the calling +// method as a field. +func SetReportCaller(include bool) { + std.SetReportCaller(include) +} + +// SetLevel sets the standard logger level. +func SetLevel(level Level) { + std.SetLevel(level) +} + +// GetLevel returns the standard logger level. +func GetLevel() Level { + return std.GetLevel() +} + +// IsLevelEnabled checks if the log level of the standard logger is greater than the level param +func IsLevelEnabled(level Level) bool { + return std.IsLevelEnabled(level) +} + +// AddHook adds a hook to the standard logger hooks. +func AddHook(hook Hook) { + std.AddHook(hook) +} + +// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. +func WithError(err error) *Entry { + return std.WithField(ErrorKey, err) +} + +// WithContext creates an entry from the standard logger and adds a context to it. +func WithContext(ctx context.Context) *Entry { + return std.WithContext(ctx) +} + +// WithField creates an entry from the standard logger and adds a field to +// it. If you want multiple fields, use `WithFields`. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithField(key string, value interface{}) *Entry { + return std.WithField(key, value) +} + +// WithFields creates an entry from the standard logger and adds multiple +// fields to it. This is simply a helper for `WithField`, invoking it +// once for each field. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithFields(fields Fields) *Entry { + return std.WithFields(fields) +} + +// WithTime creats an entry from the standard logger and overrides the time of +// logs generated with it. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithTime(t time.Time) *Entry { + return std.WithTime(t) +} + +// Trace logs a message at level Trace on the standard logger. +func Trace(args ...interface{}) { + std.Trace(args...) +} + +// Debug logs a message at level Debug on the standard logger. +func Debug(args ...interface{}) { + std.Debug(args...) +} + +// Print logs a message at level Info on the standard logger. +func Print(args ...interface{}) { + std.Print(args...) +} + +// Info logs a message at level Info on the standard logger. +func Info(args ...interface{}) { + std.Info(args...) +} + +// Warn logs a message at level Warn on the standard logger. +func Warn(args ...interface{}) { + std.Warn(args...) +} + +// Warning logs a message at level Warn on the standard logger. +func Warning(args ...interface{}) { + std.Warning(args...) +} + +// Error logs a message at level Error on the standard logger. +func Error(args ...interface{}) { + std.Error(args...) +} + +// Panic logs a message at level Panic on the standard logger. +func Panic(args ...interface{}) { + std.Panic(args...) +} + +// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1. +func Fatal(args ...interface{}) { + std.Fatal(args...) +} + +// Tracef logs a message at level Trace on the standard logger. +func Tracef(format string, args ...interface{}) { + std.Tracef(format, args...) +} + +// Debugf logs a message at level Debug on the standard logger. +func Debugf(format string, args ...interface{}) { + std.Debugf(format, args...) +} + +// Printf logs a message at level Info on the standard logger. +func Printf(format string, args ...interface{}) { + std.Printf(format, args...) +} + +// Infof logs a message at level Info on the standard logger. +func Infof(format string, args ...interface{}) { + std.Infof(format, args...) +} + +// Warnf logs a message at level Warn on the standard logger. +func Warnf(format string, args ...interface{}) { + std.Warnf(format, args...) +} + +// Warningf logs a message at level Warn on the standard logger. +func Warningf(format string, args ...interface{}) { + std.Warningf(format, args...) +} + +// Errorf logs a message at level Error on the standard logger. +func Errorf(format string, args ...interface{}) { + std.Errorf(format, args...) +} + +// Panicf logs a message at level Panic on the standard logger. +func Panicf(format string, args ...interface{}) { + std.Panicf(format, args...) +} + +// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1. +func Fatalf(format string, args ...interface{}) { + std.Fatalf(format, args...) +} + +// Traceln logs a message at level Trace on the standard logger. +func Traceln(args ...interface{}) { + std.Traceln(args...) +} + +// Debugln logs a message at level Debug on the standard logger. +func Debugln(args ...interface{}) { + std.Debugln(args...) +} + +// Println logs a message at level Info on the standard logger. +func Println(args ...interface{}) { + std.Println(args...) +} + +// Infoln logs a message at level Info on the standard logger. +func Infoln(args ...interface{}) { + std.Infoln(args...) +} + +// Warnln logs a message at level Warn on the standard logger. +func Warnln(args ...interface{}) { + std.Warnln(args...) +} + +// Warningln logs a message at level Warn on the standard logger. +func Warningln(args ...interface{}) { + std.Warningln(args...) +} + +// Errorln logs a message at level Error on the standard logger. +func Errorln(args ...interface{}) { + std.Errorln(args...) +} + +// Panicln logs a message at level Panic on the standard logger. +func Panicln(args ...interface{}) { + std.Panicln(args...) +} + +// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1. +func Fatalln(args ...interface{}) { + std.Fatalln(args...) +} diff --git a/vendor/github.com/sirupsen/logrus/formatter.go b/vendor/github.com/sirupsen/logrus/formatter.go new file mode 100644 index 0000000..4088837 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/formatter.go @@ -0,0 +1,78 @@ +package logrus + +import "time" + +// Default key names for the default fields +const ( + defaultTimestampFormat = time.RFC3339 + FieldKeyMsg = "msg" + FieldKeyLevel = "level" + FieldKeyTime = "time" + FieldKeyLogrusError = "logrus_error" + FieldKeyFunc = "func" + FieldKeyFile = "file" +) + +// The Formatter interface is used to implement a custom Formatter. It takes an +// `Entry`. It exposes all the fields, including the default ones: +// +// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. +// * `entry.Data["time"]`. The timestamp. +// * `entry.Data["level"]. The level the entry was logged at. +// +// Any additional fields added with `WithField` or `WithFields` are also in +// `entry.Data`. Format is expected to return an array of bytes which are then +// logged to `logger.Out`. +type Formatter interface { + Format(*Entry) ([]byte, error) +} + +// This is to not silently overwrite `time`, `msg`, `func` and `level` fields when +// dumping it. If this code wasn't there doing: +// +// logrus.WithField("level", 1).Info("hello") +// +// Would just silently drop the user provided level. Instead with this code +// it'll logged as: +// +// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} +// +// It's not exported because it's still using Data in an opinionated way. It's to +// avoid code duplication between the two default formatters. +func prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller bool) { + timeKey := fieldMap.resolve(FieldKeyTime) + if t, ok := data[timeKey]; ok { + data["fields."+timeKey] = t + delete(data, timeKey) + } + + msgKey := fieldMap.resolve(FieldKeyMsg) + if m, ok := data[msgKey]; ok { + data["fields."+msgKey] = m + delete(data, msgKey) + } + + levelKey := fieldMap.resolve(FieldKeyLevel) + if l, ok := data[levelKey]; ok { + data["fields."+levelKey] = l + delete(data, levelKey) + } + + logrusErrKey := fieldMap.resolve(FieldKeyLogrusError) + if l, ok := data[logrusErrKey]; ok { + data["fields."+logrusErrKey] = l + delete(data, logrusErrKey) + } + + // If reportCaller is not set, 'func' will not conflict. + if reportCaller { + funcKey := fieldMap.resolve(FieldKeyFunc) + if l, ok := data[funcKey]; ok { + data["fields."+funcKey] = l + } + fileKey := fieldMap.resolve(FieldKeyFile) + if l, ok := data[fileKey]; ok { + data["fields."+fileKey] = l + } + } +} diff --git a/vendor/github.com/sirupsen/logrus/go.mod b/vendor/github.com/sirupsen/logrus/go.mod new file mode 100644 index 0000000..12fdf98 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/go.mod @@ -0,0 +1,10 @@ +module github.com/sirupsen/logrus + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/konsorten/go-windows-terminal-sequences v1.0.1 + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/objx v0.1.1 // indirect + github.com/stretchr/testify v1.2.2 + golang.org/x/sys v0.0.0-20190422165155-953cdadca894 +) diff --git a/vendor/github.com/sirupsen/logrus/go.sum b/vendor/github.com/sirupsen/logrus/go.sum new file mode 100644 index 0000000..596c318 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/go.sum @@ -0,0 +1,16 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe h1:CHRGQ8V7OlCYtwaKPJi3iA7J+YdNKdo8j7nG5IgDhjs= +github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33 h1:I6FyU15t786LL7oL/hn43zqTuEGr4PN7F4XJ1p4E3Y8= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/vendor/github.com/sirupsen/logrus/hooks.go b/vendor/github.com/sirupsen/logrus/hooks.go new file mode 100644 index 0000000..3f151cd --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/hooks.go @@ -0,0 +1,34 @@ +package logrus + +// A hook to be fired when logging on the logging levels returned from +// `Levels()` on your implementation of the interface. Note that this is not +// fired in a goroutine or a channel with workers, you should handle such +// functionality yourself if your call is non-blocking and you don't wish for +// the logging calls for levels returned from `Levels()` to block. +type Hook interface { + Levels() []Level + Fire(*Entry) error +} + +// Internal type for storing the hooks on a logger instance. +type LevelHooks map[Level][]Hook + +// Add a hook to an instance of logger. This is called with +// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. +func (hooks LevelHooks) Add(hook Hook) { + for _, level := range hook.Levels() { + hooks[level] = append(hooks[level], hook) + } +} + +// Fire all the hooks for the passed level. Used by `entry.log` to fire +// appropriate hooks for a log entry. +func (hooks LevelHooks) Fire(level Level, entry *Entry) error { + for _, hook := range hooks[level] { + if err := hook.Fire(entry); err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/sirupsen/logrus/json_formatter.go b/vendor/github.com/sirupsen/logrus/json_formatter.go new file mode 100644 index 0000000..098a21a --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/json_formatter.go @@ -0,0 +1,121 @@ +package logrus + +import ( + "bytes" + "encoding/json" + "fmt" + "runtime" +) + +type fieldKey string + +// FieldMap allows customization of the key names for default fields. +type FieldMap map[fieldKey]string + +func (f FieldMap) resolve(key fieldKey) string { + if k, ok := f[key]; ok { + return k + } + + return string(key) +} + +// JSONFormatter formats logs into parsable json +type JSONFormatter struct { + // TimestampFormat sets the format used for marshaling timestamps. + TimestampFormat string + + // DisableTimestamp allows disabling automatic timestamps in output + DisableTimestamp bool + + // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key. + DataKey string + + // FieldMap allows users to customize the names of keys for default fields. + // As an example: + // formatter := &JSONFormatter{ + // FieldMap: FieldMap{ + // FieldKeyTime: "@timestamp", + // FieldKeyLevel: "@level", + // FieldKeyMsg: "@message", + // FieldKeyFunc: "@caller", + // }, + // } + FieldMap FieldMap + + // CallerPrettyfier can be set by the user to modify the content + // of the function and file keys in the json data when ReportCaller is + // activated. If any of the returned value is the empty string the + // corresponding key will be removed from json fields. + CallerPrettyfier func(*runtime.Frame) (function string, file string) + + // PrettyPrint will indent all json logs + PrettyPrint bool +} + +// Format renders a single log entry +func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { + data := make(Fields, len(entry.Data)+4) + for k, v := range entry.Data { + switch v := v.(type) { + case error: + // Otherwise errors are ignored by `encoding/json` + // https://github.com/sirupsen/logrus/issues/137 + data[k] = v.Error() + default: + data[k] = v + } + } + + if f.DataKey != "" { + newData := make(Fields, 4) + newData[f.DataKey] = data + data = newData + } + + prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) + + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = defaultTimestampFormat + } + + if entry.err != "" { + data[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err + } + if !f.DisableTimestamp { + data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) + } + data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message + data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() + if entry.HasCaller() { + funcVal := entry.Caller.Function + fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) + if f.CallerPrettyfier != nil { + funcVal, fileVal = f.CallerPrettyfier(entry.Caller) + } + if funcVal != "" { + data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal + } + if fileVal != "" { + data[f.FieldMap.resolve(FieldKeyFile)] = fileVal + } + } + + var b *bytes.Buffer + if entry.Buffer != nil { + b = entry.Buffer + } else { + b = &bytes.Buffer{} + } + + encoder := json.NewEncoder(b) + if f.PrettyPrint { + encoder.SetIndent("", " ") + } + if err := encoder.Encode(data); err != nil { + return nil, fmt.Errorf("failed to marshal fields to JSON, %v", err) + } + + return b.Bytes(), nil +} diff --git a/vendor/github.com/sirupsen/logrus/logger.go b/vendor/github.com/sirupsen/logrus/logger.go new file mode 100644 index 0000000..c0c0b1e --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/logger.go @@ -0,0 +1,351 @@ +package logrus + +import ( + "context" + "io" + "os" + "sync" + "sync/atomic" + "time" +) + +type Logger struct { + // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a + // file, or leave it default which is `os.Stderr`. You can also set this to + // something more adventurous, such as logging to Kafka. + Out io.Writer + // Hooks for the logger instance. These allow firing events based on logging + // levels and log entries. For example, to send errors to an error tracking + // service, log to StatsD or dump the core on fatal errors. + Hooks LevelHooks + // All log entries pass through the formatter before logged to Out. The + // included formatters are `TextFormatter` and `JSONFormatter` for which + // TextFormatter is the default. In development (when a TTY is attached) it + // logs with colors, but to a file it wouldn't. You can easily implement your + // own that implements the `Formatter` interface, see the `README` or included + // formatters for examples. + Formatter Formatter + + // Flag for whether to log caller info (off by default) + ReportCaller bool + + // The logging level the logger should log at. This is typically (and defaults + // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be + // logged. + Level Level + // Used to sync writing to the log. Locking is enabled by Default + mu MutexWrap + // Reusable empty entry + entryPool sync.Pool + // Function to exit the application, defaults to `os.Exit()` + ExitFunc exitFunc +} + +type exitFunc func(int) + +type MutexWrap struct { + lock sync.Mutex + disabled bool +} + +func (mw *MutexWrap) Lock() { + if !mw.disabled { + mw.lock.Lock() + } +} + +func (mw *MutexWrap) Unlock() { + if !mw.disabled { + mw.lock.Unlock() + } +} + +func (mw *MutexWrap) Disable() { + mw.disabled = true +} + +// Creates a new logger. Configuration should be set by changing `Formatter`, +// `Out` and `Hooks` directly on the default logger instance. You can also just +// instantiate your own: +// +// var log = &Logger{ +// Out: os.Stderr, +// Formatter: new(JSONFormatter), +// Hooks: make(LevelHooks), +// Level: logrus.DebugLevel, +// } +// +// It's recommended to make this a global instance called `log`. +func New() *Logger { + return &Logger{ + Out: os.Stderr, + Formatter: new(TextFormatter), + Hooks: make(LevelHooks), + Level: InfoLevel, + ExitFunc: os.Exit, + ReportCaller: false, + } +} + +func (logger *Logger) newEntry() *Entry { + entry, ok := logger.entryPool.Get().(*Entry) + if ok { + return entry + } + return NewEntry(logger) +} + +func (logger *Logger) releaseEntry(entry *Entry) { + entry.Data = map[string]interface{}{} + logger.entryPool.Put(entry) +} + +// Adds a field to the log entry, note that it doesn't log until you call +// Debug, Print, Info, Warn, Error, Fatal or Panic. It only creates a log entry. +// If you want multiple fields, use `WithFields`. +func (logger *Logger) WithField(key string, value interface{}) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithField(key, value) +} + +// Adds a struct of fields to the log entry. All it does is call `WithField` for +// each `Field`. +func (logger *Logger) WithFields(fields Fields) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithFields(fields) +} + +// Add an error as single field to the log entry. All it does is call +// `WithError` for the given `error`. +func (logger *Logger) WithError(err error) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithError(err) +} + +// Add a context to the log entry. +func (logger *Logger) WithContext(ctx context.Context) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithContext(ctx) +} + +// Overrides the time of the log entry. +func (logger *Logger) WithTime(t time.Time) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithTime(t) +} + +func (logger *Logger) Logf(level Level, format string, args ...interface{}) { + if logger.IsLevelEnabled(level) { + entry := logger.newEntry() + entry.Logf(level, format, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Tracef(format string, args ...interface{}) { + logger.Logf(TraceLevel, format, args...) +} + +func (logger *Logger) Debugf(format string, args ...interface{}) { + logger.Logf(DebugLevel, format, args...) +} + +func (logger *Logger) Infof(format string, args ...interface{}) { + logger.Logf(InfoLevel, format, args...) +} + +func (logger *Logger) Printf(format string, args ...interface{}) { + entry := logger.newEntry() + entry.Printf(format, args...) + logger.releaseEntry(entry) +} + +func (logger *Logger) Warnf(format string, args ...interface{}) { + logger.Logf(WarnLevel, format, args...) +} + +func (logger *Logger) Warningf(format string, args ...interface{}) { + logger.Warnf(format, args...) +} + +func (logger *Logger) Errorf(format string, args ...interface{}) { + logger.Logf(ErrorLevel, format, args...) +} + +func (logger *Logger) Fatalf(format string, args ...interface{}) { + logger.Logf(FatalLevel, format, args...) + logger.Exit(1) +} + +func (logger *Logger) Panicf(format string, args ...interface{}) { + logger.Logf(PanicLevel, format, args...) +} + +func (logger *Logger) Log(level Level, args ...interface{}) { + if logger.IsLevelEnabled(level) { + entry := logger.newEntry() + entry.Log(level, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Trace(args ...interface{}) { + logger.Log(TraceLevel, args...) +} + +func (logger *Logger) Debug(args ...interface{}) { + logger.Log(DebugLevel, args...) +} + +func (logger *Logger) Info(args ...interface{}) { + logger.Log(InfoLevel, args...) +} + +func (logger *Logger) Print(args ...interface{}) { + entry := logger.newEntry() + entry.Print(args...) + logger.releaseEntry(entry) +} + +func (logger *Logger) Warn(args ...interface{}) { + logger.Log(WarnLevel, args...) +} + +func (logger *Logger) Warning(args ...interface{}) { + logger.Warn(args...) +} + +func (logger *Logger) Error(args ...interface{}) { + logger.Log(ErrorLevel, args...) +} + +func (logger *Logger) Fatal(args ...interface{}) { + logger.Log(FatalLevel, args...) + logger.Exit(1) +} + +func (logger *Logger) Panic(args ...interface{}) { + logger.Log(PanicLevel, args...) +} + +func (logger *Logger) Logln(level Level, args ...interface{}) { + if logger.IsLevelEnabled(level) { + entry := logger.newEntry() + entry.Logln(level, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Traceln(args ...interface{}) { + logger.Logln(TraceLevel, args...) +} + +func (logger *Logger) Debugln(args ...interface{}) { + logger.Logln(DebugLevel, args...) +} + +func (logger *Logger) Infoln(args ...interface{}) { + logger.Logln(InfoLevel, args...) +} + +func (logger *Logger) Println(args ...interface{}) { + entry := logger.newEntry() + entry.Println(args...) + logger.releaseEntry(entry) +} + +func (logger *Logger) Warnln(args ...interface{}) { + logger.Logln(WarnLevel, args...) +} + +func (logger *Logger) Warningln(args ...interface{}) { + logger.Warnln(args...) +} + +func (logger *Logger) Errorln(args ...interface{}) { + logger.Logln(ErrorLevel, args...) +} + +func (logger *Logger) Fatalln(args ...interface{}) { + logger.Logln(FatalLevel, args...) + logger.Exit(1) +} + +func (logger *Logger) Panicln(args ...interface{}) { + logger.Logln(PanicLevel, args...) +} + +func (logger *Logger) Exit(code int) { + runHandlers() + if logger.ExitFunc == nil { + logger.ExitFunc = os.Exit + } + logger.ExitFunc(code) +} + +//When file is opened with appending mode, it's safe to +//write concurrently to a file (within 4k message on Linux). +//In these cases user can choose to disable the lock. +func (logger *Logger) SetNoLock() { + logger.mu.Disable() +} + +func (logger *Logger) level() Level { + return Level(atomic.LoadUint32((*uint32)(&logger.Level))) +} + +// SetLevel sets the logger level. +func (logger *Logger) SetLevel(level Level) { + atomic.StoreUint32((*uint32)(&logger.Level), uint32(level)) +} + +// GetLevel returns the logger level. +func (logger *Logger) GetLevel() Level { + return logger.level() +} + +// AddHook adds a hook to the logger hooks. +func (logger *Logger) AddHook(hook Hook) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.Hooks.Add(hook) +} + +// IsLevelEnabled checks if the log level of the logger is greater than the level param +func (logger *Logger) IsLevelEnabled(level Level) bool { + return logger.level() >= level +} + +// SetFormatter sets the logger formatter. +func (logger *Logger) SetFormatter(formatter Formatter) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.Formatter = formatter +} + +// SetOutput sets the logger output. +func (logger *Logger) SetOutput(output io.Writer) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.Out = output +} + +func (logger *Logger) SetReportCaller(reportCaller bool) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.ReportCaller = reportCaller +} + +// ReplaceHooks replaces the logger hooks and returns the old ones +func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks { + logger.mu.Lock() + oldHooks := logger.Hooks + logger.Hooks = hooks + logger.mu.Unlock() + return oldHooks +} diff --git a/vendor/github.com/sirupsen/logrus/logrus.go b/vendor/github.com/sirupsen/logrus/logrus.go new file mode 100644 index 0000000..8644761 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/logrus.go @@ -0,0 +1,186 @@ +package logrus + +import ( + "fmt" + "log" + "strings" +) + +// Fields type, used to pass to `WithFields`. +type Fields map[string]interface{} + +// Level type +type Level uint32 + +// Convert the Level to a string. E.g. PanicLevel becomes "panic". +func (level Level) String() string { + if b, err := level.MarshalText(); err == nil { + return string(b) + } else { + return "unknown" + } +} + +// ParseLevel takes a string level and returns the Logrus log level constant. +func ParseLevel(lvl string) (Level, error) { + switch strings.ToLower(lvl) { + case "panic": + return PanicLevel, nil + case "fatal": + return FatalLevel, nil + case "error": + return ErrorLevel, nil + case "warn", "warning": + return WarnLevel, nil + case "info": + return InfoLevel, nil + case "debug": + return DebugLevel, nil + case "trace": + return TraceLevel, nil + } + + var l Level + return l, fmt.Errorf("not a valid logrus Level: %q", lvl) +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (level *Level) UnmarshalText(text []byte) error { + l, err := ParseLevel(string(text)) + if err != nil { + return err + } + + *level = Level(l) + + return nil +} + +func (level Level) MarshalText() ([]byte, error) { + switch level { + case TraceLevel: + return []byte("trace"), nil + case DebugLevel: + return []byte("debug"), nil + case InfoLevel: + return []byte("info"), nil + case WarnLevel: + return []byte("warning"), nil + case ErrorLevel: + return []byte("error"), nil + case FatalLevel: + return []byte("fatal"), nil + case PanicLevel: + return []byte("panic"), nil + } + + return nil, fmt.Errorf("not a valid logrus level %d", level) +} + +// A constant exposing all logging levels +var AllLevels = []Level{ + PanicLevel, + FatalLevel, + ErrorLevel, + WarnLevel, + InfoLevel, + DebugLevel, + TraceLevel, +} + +// These are the different logging levels. You can set the logging level to log +// on your instance of logger, obtained with `logrus.New()`. +const ( + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel Level = iota + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel +) + +// Won't compile if StdLogger can't be realized by a log.Logger +var ( + _ StdLogger = &log.Logger{} + _ StdLogger = &Entry{} + _ StdLogger = &Logger{} +) + +// StdLogger is what your logrus-enabled library should take, that way +// it'll accept a stdlib logger and a logrus logger. There's no standard +// interface, this is the closest we get, unfortunately. +type StdLogger interface { + Print(...interface{}) + Printf(string, ...interface{}) + Println(...interface{}) + + Fatal(...interface{}) + Fatalf(string, ...interface{}) + Fatalln(...interface{}) + + Panic(...interface{}) + Panicf(string, ...interface{}) + Panicln(...interface{}) +} + +// The FieldLogger interface generalizes the Entry and Logger types +type FieldLogger interface { + WithField(key string, value interface{}) *Entry + WithFields(fields Fields) *Entry + WithError(err error) *Entry + + Debugf(format string, args ...interface{}) + Infof(format string, args ...interface{}) + Printf(format string, args ...interface{}) + Warnf(format string, args ...interface{}) + Warningf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) + Fatalf(format string, args ...interface{}) + Panicf(format string, args ...interface{}) + + Debug(args ...interface{}) + Info(args ...interface{}) + Print(args ...interface{}) + Warn(args ...interface{}) + Warning(args ...interface{}) + Error(args ...interface{}) + Fatal(args ...interface{}) + Panic(args ...interface{}) + + Debugln(args ...interface{}) + Infoln(args ...interface{}) + Println(args ...interface{}) + Warnln(args ...interface{}) + Warningln(args ...interface{}) + Errorln(args ...interface{}) + Fatalln(args ...interface{}) + Panicln(args ...interface{}) + + // IsDebugEnabled() bool + // IsInfoEnabled() bool + // IsWarnEnabled() bool + // IsErrorEnabled() bool + // IsFatalEnabled() bool + // IsPanicEnabled() bool +} + +// Ext1FieldLogger (the first extension to FieldLogger) is superfluous, it is +// here for consistancy. Do not use. Use Logger or Entry instead. +type Ext1FieldLogger interface { + FieldLogger + Tracef(format string, args ...interface{}) + Trace(args ...interface{}) + Traceln(args ...interface{}) +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go new file mode 100644 index 0000000..2403de9 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go @@ -0,0 +1,11 @@ +// +build appengine + +package logrus + +import ( + "io" +) + +func checkIfTerminal(w io.Writer) bool { + return true +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go new file mode 100644 index 0000000..3c4f43f --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go @@ -0,0 +1,13 @@ +// +build darwin dragonfly freebsd netbsd openbsd + +package logrus + +import "golang.org/x/sys/unix" + +const ioctlReadTermios = unix.TIOCGETA + +func isTerminal(fd int) bool { + _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) + return err == nil +} + diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go new file mode 100644 index 0000000..97af92c --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go @@ -0,0 +1,11 @@ +// +build js nacl plan9 + +package logrus + +import ( + "io" +) + +func checkIfTerminal(w io.Writer) bool { + return false +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go new file mode 100644 index 0000000..3293fb3 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go @@ -0,0 +1,17 @@ +// +build !appengine,!js,!windows,!nacl,!plan9 + +package logrus + +import ( + "io" + "os" +) + +func checkIfTerminal(w io.Writer) bool { + switch v := w.(type) { + case *os.File: + return isTerminal(int(v.Fd())) + default: + return false + } +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go b/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go new file mode 100644 index 0000000..f6710b3 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go @@ -0,0 +1,11 @@ +package logrus + +import ( + "golang.org/x/sys/unix" +) + +// IsTerminal returns true if the given file descriptor is a terminal. +func isTerminal(fd int) bool { + _, err := unix.IoctlGetTermio(fd, unix.TCGETA) + return err == nil +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go new file mode 100644 index 0000000..355dc96 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go @@ -0,0 +1,13 @@ +// +build linux aix + +package logrus + +import "golang.org/x/sys/unix" + +const ioctlReadTermios = unix.TCGETS + +func isTerminal(fd int) bool { + _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) + return err == nil +} + diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go new file mode 100644 index 0000000..572889d --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go @@ -0,0 +1,34 @@ +// +build !appengine,!js,windows + +package logrus + +import ( + "io" + "os" + "syscall" + + sequences "github.com/konsorten/go-windows-terminal-sequences" +) + +func initTerminal(w io.Writer) { + switch v := w.(type) { + case *os.File: + sequences.EnableVirtualTerminalProcessing(syscall.Handle(v.Fd()), true) + } +} + +func checkIfTerminal(w io.Writer) bool { + var ret bool + switch v := w.(type) { + case *os.File: + var mode uint32 + err := syscall.GetConsoleMode(syscall.Handle(v.Fd()), &mode) + ret = (err == nil) + default: + ret = false + } + if ret { + initTerminal(w) + } + return ret +} diff --git a/vendor/github.com/sirupsen/logrus/text_formatter.go b/vendor/github.com/sirupsen/logrus/text_formatter.go new file mode 100644 index 0000000..e01587c --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/text_formatter.go @@ -0,0 +1,295 @@ +package logrus + +import ( + "bytes" + "fmt" + "os" + "runtime" + "sort" + "strings" + "sync" + "time" +) + +const ( + red = 31 + yellow = 33 + blue = 36 + gray = 37 +) + +var baseTimestamp time.Time + +func init() { + baseTimestamp = time.Now() +} + +// TextFormatter formats logs into text +type TextFormatter struct { + // Set to true to bypass checking for a TTY before outputting colors. + ForceColors bool + + // Force disabling colors. + DisableColors bool + + // Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/ + EnvironmentOverrideColors bool + + // Disable timestamp logging. useful when output is redirected to logging + // system that already adds timestamps. + DisableTimestamp bool + + // Enable logging the full timestamp when a TTY is attached instead of just + // the time passed since beginning of execution. + FullTimestamp bool + + // TimestampFormat to use for display when a full timestamp is printed + TimestampFormat string + + // The fields are sorted by default for a consistent output. For applications + // that log extremely frequently and don't use the JSON formatter this may not + // be desired. + DisableSorting bool + + // The keys sorting function, when uninitialized it uses sort.Strings. + SortingFunc func([]string) + + // Disables the truncation of the level text to 4 characters. + DisableLevelTruncation bool + + // QuoteEmptyFields will wrap empty fields in quotes if true + QuoteEmptyFields bool + + // Whether the logger's out is to a terminal + isTerminal bool + + // FieldMap allows users to customize the names of keys for default fields. + // As an example: + // formatter := &TextFormatter{ + // FieldMap: FieldMap{ + // FieldKeyTime: "@timestamp", + // FieldKeyLevel: "@level", + // FieldKeyMsg: "@message"}} + FieldMap FieldMap + + // CallerPrettyfier can be set by the user to modify the content + // of the function and file keys in the data when ReportCaller is + // activated. If any of the returned value is the empty string the + // corresponding key will be removed from fields. + CallerPrettyfier func(*runtime.Frame) (function string, file string) + + terminalInitOnce sync.Once +} + +func (f *TextFormatter) init(entry *Entry) { + if entry.Logger != nil { + f.isTerminal = checkIfTerminal(entry.Logger.Out) + } +} + +func (f *TextFormatter) isColored() bool { + isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows")) + + if f.EnvironmentOverrideColors { + if force, ok := os.LookupEnv("CLICOLOR_FORCE"); ok && force != "0" { + isColored = true + } else if ok && force == "0" { + isColored = false + } else if os.Getenv("CLICOLOR") == "0" { + isColored = false + } + } + + return isColored && !f.DisableColors +} + +// Format renders a single log entry +func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { + data := make(Fields) + for k, v := range entry.Data { + data[k] = v + } + prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) + keys := make([]string, 0, len(data)) + for k := range data { + keys = append(keys, k) + } + + var funcVal, fileVal string + + fixedKeys := make([]string, 0, 4+len(data)) + if !f.DisableTimestamp { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime)) + } + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel)) + if entry.Message != "" { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg)) + } + if entry.err != "" { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError)) + } + if entry.HasCaller() { + if f.CallerPrettyfier != nil { + funcVal, fileVal = f.CallerPrettyfier(entry.Caller) + } else { + funcVal = entry.Caller.Function + fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) + } + + if funcVal != "" { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc)) + } + if fileVal != "" { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile)) + } + } + + if !f.DisableSorting { + if f.SortingFunc == nil { + sort.Strings(keys) + fixedKeys = append(fixedKeys, keys...) + } else { + if !f.isColored() { + fixedKeys = append(fixedKeys, keys...) + f.SortingFunc(fixedKeys) + } else { + f.SortingFunc(keys) + } + } + } else { + fixedKeys = append(fixedKeys, keys...) + } + + var b *bytes.Buffer + if entry.Buffer != nil { + b = entry.Buffer + } else { + b = &bytes.Buffer{} + } + + f.terminalInitOnce.Do(func() { f.init(entry) }) + + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = defaultTimestampFormat + } + if f.isColored() { + f.printColored(b, entry, keys, data, timestampFormat) + } else { + + for _, key := range fixedKeys { + var value interface{} + switch { + case key == f.FieldMap.resolve(FieldKeyTime): + value = entry.Time.Format(timestampFormat) + case key == f.FieldMap.resolve(FieldKeyLevel): + value = entry.Level.String() + case key == f.FieldMap.resolve(FieldKeyMsg): + value = entry.Message + case key == f.FieldMap.resolve(FieldKeyLogrusError): + value = entry.err + case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller(): + value = funcVal + case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller(): + value = fileVal + default: + value = data[key] + } + f.appendKeyValue(b, key, value) + } + } + + b.WriteByte('\n') + return b.Bytes(), nil +} + +func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) { + var levelColor int + switch entry.Level { + case DebugLevel, TraceLevel: + levelColor = gray + case WarnLevel: + levelColor = yellow + case ErrorLevel, FatalLevel, PanicLevel: + levelColor = red + default: + levelColor = blue + } + + levelText := strings.ToUpper(entry.Level.String()) + if !f.DisableLevelTruncation { + levelText = levelText[0:4] + } + + // Remove a single newline if it already exists in the message to keep + // the behavior of logrus text_formatter the same as the stdlib log package + entry.Message = strings.TrimSuffix(entry.Message, "\n") + + caller := "" + if entry.HasCaller() { + funcVal := fmt.Sprintf("%s()", entry.Caller.Function) + fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) + + if f.CallerPrettyfier != nil { + funcVal, fileVal = f.CallerPrettyfier(entry.Caller) + } + + if fileVal == "" { + caller = funcVal + } else if funcVal == "" { + caller = fileVal + } else { + caller = fileVal + " " + funcVal + } + } + + if f.DisableTimestamp { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message) + } else if !f.FullTimestamp { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message) + } else { + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message) + } + for _, k := range keys { + v := data[k] + fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) + f.appendValue(b, v) + } +} + +func (f *TextFormatter) needsQuoting(text string) bool { + if f.QuoteEmptyFields && len(text) == 0 { + return true + } + for _, ch := range text { + if !((ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || + ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') { + return true + } + } + return false +} + +func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { + if b.Len() > 0 { + b.WriteByte(' ') + } + b.WriteString(key) + b.WriteByte('=') + f.appendValue(b, value) +} + +func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { + stringVal, ok := value.(string) + if !ok { + stringVal = fmt.Sprint(value) + } + + if !f.needsQuoting(stringVal) { + b.WriteString(stringVal) + } else { + b.WriteString(fmt.Sprintf("%q", stringVal)) + } +} diff --git a/vendor/github.com/sirupsen/logrus/writer.go b/vendor/github.com/sirupsen/logrus/writer.go new file mode 100644 index 0000000..9e1f751 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/writer.go @@ -0,0 +1,64 @@ +package logrus + +import ( + "bufio" + "io" + "runtime" +) + +func (logger *Logger) Writer() *io.PipeWriter { + return logger.WriterLevel(InfoLevel) +} + +func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { + return NewEntry(logger).WriterLevel(level) +} + +func (entry *Entry) Writer() *io.PipeWriter { + return entry.WriterLevel(InfoLevel) +} + +func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { + reader, writer := io.Pipe() + + var printFunc func(args ...interface{}) + + switch level { + case TraceLevel: + printFunc = entry.Trace + case DebugLevel: + printFunc = entry.Debug + case InfoLevel: + printFunc = entry.Info + case WarnLevel: + printFunc = entry.Warn + case ErrorLevel: + printFunc = entry.Error + case FatalLevel: + printFunc = entry.Fatal + case PanicLevel: + printFunc = entry.Panic + default: + printFunc = entry.Print + } + + go entry.writerScanner(reader, printFunc) + runtime.SetFinalizer(writer, writerFinalizer) + + return writer +} + +func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + printFunc(scanner.Text()) + } + if err := scanner.Err(); err != nil { + entry.Errorf("Error while reading from Writer: %s", err) + } + reader.Close() +} + +func writerFinalizer(writer *io.PipeWriter) { + writer.Close() +} diff --git a/vendor/golang.org/x/net/publicsuffix/list.go b/vendor/golang.org/x/net/publicsuffix/list.go new file mode 100644 index 0000000..200617e --- /dev/null +++ b/vendor/golang.org/x/net/publicsuffix/list.go @@ -0,0 +1,181 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:generate go run gen.go + +// Package publicsuffix provides a public suffix list based on data from +// https://publicsuffix.org/ +// +// A public suffix is one under which Internet users can directly register +// names. It is related to, but different from, a TLD (top level domain). +// +// "com" is a TLD (top level domain). Top level means it has no dots. +// +// "com" is also a public suffix. Amazon and Google have registered different +// siblings under that domain: "amazon.com" and "google.com". +// +// "au" is another TLD, again because it has no dots. But it's not "amazon.au". +// Instead, it's "amazon.com.au". +// +// "com.au" isn't an actual TLD, because it's not at the top level (it has +// dots). But it is an eTLD (effective TLD), because that's the branching point +// for domain name registrars. +// +// Another name for "an eTLD" is "a public suffix". Often, what's more of +// interest is the eTLD+1, or one more label than the public suffix. For +// example, browsers partition read/write access to HTTP cookies according to +// the eTLD+1. Web pages served from "amazon.com.au" can't read cookies from +// "google.com.au", but web pages served from "maps.google.com" can share +// cookies from "www.google.com", so you don't have to sign into Google Maps +// separately from signing into Google Web Search. Note that all four of those +// domains have 3 labels and 2 dots. The first two domains are each an eTLD+1, +// the last two are not (but share the same eTLD+1: "google.com"). +// +// All of these domains have the same eTLD+1: +// - "www.books.amazon.co.uk" +// - "books.amazon.co.uk" +// - "amazon.co.uk" +// Specifically, the eTLD+1 is "amazon.co.uk", because the eTLD is "co.uk". +// +// There is no closed form algorithm to calculate the eTLD of a domain. +// Instead, the calculation is data driven. This package provides a +// pre-compiled snapshot of Mozilla's PSL (Public Suffix List) data at +// https://publicsuffix.org/ +package publicsuffix // import "golang.org/x/net/publicsuffix" + +// TODO: specify case sensitivity and leading/trailing dot behavior for +// func PublicSuffix and func EffectiveTLDPlusOne. + +import ( + "fmt" + "net/http/cookiejar" + "strings" +) + +// List implements the cookiejar.PublicSuffixList interface by calling the +// PublicSuffix function. +var List cookiejar.PublicSuffixList = list{} + +type list struct{} + +func (list) PublicSuffix(domain string) string { + ps, _ := PublicSuffix(domain) + return ps +} + +func (list) String() string { + return version +} + +// PublicSuffix returns the public suffix of the domain using a copy of the +// publicsuffix.org database compiled into the library. +// +// icann is whether the public suffix is managed by the Internet Corporation +// for Assigned Names and Numbers. If not, the public suffix is either a +// privately managed domain (and in practice, not a top level domain) or an +// unmanaged top level domain (and not explicitly mentioned in the +// publicsuffix.org list). For example, "foo.org" and "foo.co.uk" are ICANN +// domains, "foo.dyndns.org" and "foo.blogspot.co.uk" are private domains and +// "cromulent" is an unmanaged top level domain. +// +// Use cases for distinguishing ICANN domains like "foo.com" from private +// domains like "foo.appspot.com" can be found at +// https://wiki.mozilla.org/Public_Suffix_List/Use_Cases +func PublicSuffix(domain string) (publicSuffix string, icann bool) { + lo, hi := uint32(0), uint32(numTLD) + s, suffix, icannNode, wildcard := domain, len(domain), false, false +loop: + for { + dot := strings.LastIndex(s, ".") + if wildcard { + icann = icannNode + suffix = 1 + dot + } + if lo == hi { + break + } + f := find(s[1+dot:], lo, hi) + if f == notFound { + break + } + + u := nodes[f] >> (nodesBitsTextOffset + nodesBitsTextLength) + icannNode = u&(1<>= nodesBitsICANN + u = children[u&(1<>= childrenBitsLo + hi = u & (1<>= childrenBitsHi + switch u & (1<>= childrenBitsNodeType + wildcard = u&(1<>= nodesBitsTextLength + offset := x & (1<