@@ -26,20 +26,6 @@ type Connection struct {
2626 errTimes uint32
2727}
2828
29- func (c * Connection ) testConnection () error {
30- var err error
31- maxTime := 15 * time .Second
32-
33- for i := 1 * time .Second ; i < maxTime ; i *= time .Duration (2 ) {
34- if _ , err = c .makeMetaDataRequest ("/" ); err == nil {
35- return nil // OK
36- }
37-
38- time .Sleep (i )
39- }
40- return err
41- }
42-
4329func (c * Connection ) makeMetaDataRequest (path string ) ([]byte , error ) {
4430 req , err := http .NewRequest ("GET" , strings .Join ([]string {c .url , path }, "" ), nil )
4531 if err != nil {
@@ -98,6 +84,27 @@ func NewMetadClient(backendNodes []string) (*Client, error) {
9884}
9985
10086func (c * Client ) selectConnection () error {
87+ maxTime := 15 * time .Second
88+ i := 1 * time .Second
89+ for ; i < maxTime ; i *= time .Duration (2 ) {
90+ if conn , err := c .testConnection (); err == nil {
91+ //found available conn
92+ if c .current != nil {
93+ atomic .StoreUint32 (& c .current .errTimes , 0 )
94+ }
95+ c .current = conn
96+ break
97+ }
98+ time .Sleep (i )
99+ }
100+ if i >= maxTime {
101+ return fmt .Errorf ("fail to connect any backend." )
102+ }
103+ log .Info ("Using Metad URL: " + c .current .url )
104+ return nil
105+ }
106+
107+ func (c * Client ) testConnection () (* Connection , error ) {
101108 //random start
102109 if c .current == nil {
103110 rand .Seed (time .Now ().Unix ())
@@ -107,22 +114,17 @@ func (c *Client) selectConnection() error {
107114 c .connections = c .connections .Next ()
108115 conn := c .connections .Value .(* Connection )
109116 startConn := conn
110- err := conn .testConnection ( )
117+ _ , err := conn .makeMetaDataRequest ( "/" )
111118 for err != nil {
112- log .Error ("Connection to [%s], error: [%s ]" , conn .url , err . Error () )
119+ log .Error ("connection to [%s], error: [%v ]" , conn .url , err )
113120 c .connections = c .connections .Next ()
114121 conn = c .connections .Value .(* Connection )
115122 if conn == startConn {
116- return errors . New ( "Fail to connect any backend." )
123+ break
117124 }
118- err = conn .testConnection ()
119- }
120- if c .current != nil {
121- atomic .StoreUint32 (& c .current .errTimes , 0 )
125+ _ , err = conn .makeMetaDataRequest ("/" )
122126 }
123- c .current = conn
124- log .Info ("Using Metad URL: " + c .current .url )
125- return nil
127+ return conn , err
126128}
127129
128130func (c * Client ) GetValues (keys []string ) (map [string ]string , error ) {
0 commit comments