1 // Copyright 2018, OpenCensus Authors
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
24 sDisconnected int32 = 5 + iota
28 func (ae *Exporter) setStateDisconnected() {
29 atomic.StoreInt32(&ae.connectionState, sDisconnected)
31 case ae.disconnectedCh <- true:
36 func (ae *Exporter) setStateConnected() {
37 atomic.StoreInt32(&ae.connectionState, sConnected)
40 func (ae *Exporter) connected() bool {
41 return atomic.LoadInt32(&ae.connectionState) == sConnected
44 const defaultConnReattemptPeriod = 10 * time.Second
46 func (ae *Exporter) indefiniteBackgroundConnection() error {
48 ae.backgroundConnectionDoneCh <- true
51 connReattemptPeriod := ae.reconnectionPeriod
52 if connReattemptPeriod <= 0 {
53 connReattemptPeriod = defaultConnReattemptPeriod
56 // No strong seeding required, nano time can
57 // already help with pseudo uniqueness.
58 rng := rand.New(rand.NewSource(time.Now().UnixNano() + rand.Int63n(1024)))
60 // maxJitter: 1 + (70% of the connectionReattemptPeriod)
61 maxJitter := int64(1 + 0.7*float64(connReattemptPeriod))
64 // Otherwise these will be the normal scenarios to enable
65 // reconnections if we trip out.
66 // 1. If we've stopped, return entirely
67 // 2. Otherwise block until we are disconnected, and
68 // then retry connecting
73 case <-ae.disconnectedCh:
74 // Normal scenario that we'll wait for
77 if err := ae.connect(); err == nil {
78 ae.setStateConnected()
80 ae.setStateDisconnected()
83 // Apply some jitter to avoid lockstep retrials of other
84 // agent-exporters. Lockstep retrials could result in an
85 // innocent DDOS, by clogging the machine's resources and network.
86 jitter := time.Duration(rng.Int63n(maxJitter))
87 <-time.After(connReattemptPeriod + jitter)
91 func (ae *Exporter) connect() error {
92 cc, err := ae.dialToAgent()
96 return ae.enableConnectionStreams(cc)