nettest.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. Copyright 2014 The Kubernetes 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
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // A tiny web server for checking networking connectivity.
  14. //
  15. // Will dial out to, and expect to hear from, every pod that is a member of
  16. // the service passed in the flag -service.
  17. //
  18. // Will serve a webserver on given -port.
  19. //
  20. // Visit /read to see the current state, or /quit to shut down.
  21. //
  22. // Visit /status to see pass/running/fail determination. (literally, it will
  23. // return one of those words.)
  24. //
  25. // /write is used by other network test pods to register connectivity.
  26. package main
  27. import (
  28. "bytes"
  29. "encoding/json"
  30. "flag"
  31. "fmt"
  32. "io/ioutil"
  33. "log"
  34. "net"
  35. "net/http"
  36. "os"
  37. "os/signal"
  38. "sync"
  39. "syscall"
  40. "time"
  41. v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  42. "k8s.io/apimachinery/pkg/util/sets"
  43. "k8s.io/apimachinery/pkg/version"
  44. clientset "k8s.io/client-go/kubernetes"
  45. restclient "k8s.io/client-go/rest"
  46. )
  47. var (
  48. port = flag.Int("port", 8080, "Port number to serve at.")
  49. peerCount = flag.Int("peers", 8, "Must find at least this many peers for the test to pass.")
  50. service = flag.String("service", "nettest", "Service to find other network test pods in.")
  51. namespace = flag.String("namespace", "default", "Namespace of this pod. TODO: kubernetes should make this discoverable.")
  52. delayShutdown = flag.Int("delay-shutdown", 0, "Number of seconds to delay shutdown when receiving SIGTERM.")
  53. )
  54. // State tracks the internal state of our little http server.
  55. // It's returned verbatim over the /read endpoint.
  56. type State struct {
  57. // Hostname is set once and never changed-- it's always safe to read.
  58. Hostname string
  59. // The below fields require that lock is held before reading or writing.
  60. Sent map[string]int
  61. Received map[string]int
  62. Errors []string
  63. Log []string
  64. StillContactingPeers bool
  65. lock sync.Mutex
  66. }
  67. func (s *State) doneContactingPeers() {
  68. s.lock.Lock()
  69. defer s.lock.Unlock()
  70. s.StillContactingPeers = false
  71. }
  72. // serveStatus returns "pass", "running", or "fail".
  73. func (s *State) serveStatus(w http.ResponseWriter, r *http.Request) {
  74. s.lock.Lock()
  75. defer s.lock.Unlock()
  76. if len(s.Sent) >= *peerCount && len(s.Received) >= *peerCount {
  77. fmt.Fprintf(w, "pass")
  78. return
  79. }
  80. if s.StillContactingPeers {
  81. fmt.Fprintf(w, "running")
  82. return
  83. }
  84. // Logf can't be called while holding the lock, so defer using a goroutine
  85. go s.Logf("Declaring failure for %s/%s with %d sent and %d received and %d peers", *namespace, *service, len(s.Sent), len(s.Received), *peerCount)
  86. fmt.Fprintf(w, "fail")
  87. }
  88. // serveRead writes our json encoded state
  89. func (s *State) serveRead(w http.ResponseWriter, r *http.Request) {
  90. s.lock.Lock()
  91. defer s.lock.Unlock()
  92. w.WriteHeader(http.StatusOK)
  93. b, err := json.MarshalIndent(s, "", "\t")
  94. s.appendErr(err)
  95. _, err = w.Write(b)
  96. s.appendErr(err)
  97. }
  98. // WritePost is the format that (json encoded) requests to the /write handler should take.
  99. type WritePost struct {
  100. Source string
  101. Dest string
  102. }
  103. // WriteResp is returned by /write
  104. type WriteResp struct {
  105. Hostname string
  106. }
  107. // serveWrite records the contact in our state.
  108. func (s *State) serveWrite(w http.ResponseWriter, r *http.Request) {
  109. defer r.Body.Close()
  110. s.lock.Lock()
  111. defer s.lock.Unlock()
  112. w.WriteHeader(http.StatusOK)
  113. var wp WritePost
  114. s.appendErr(json.NewDecoder(r.Body).Decode(&wp))
  115. if wp.Source == "" {
  116. s.appendErr(fmt.Errorf("%v: Got request with no source", s.Hostname))
  117. } else {
  118. if s.Received == nil {
  119. s.Received = map[string]int{}
  120. }
  121. s.Received[wp.Source]++
  122. }
  123. s.appendErr(json.NewEncoder(w).Encode(&WriteResp{Hostname: s.Hostname}))
  124. }
  125. // appendErr adds err to the list, if err is not nil. s must be locked.
  126. func (s *State) appendErr(err error) {
  127. if err != nil {
  128. s.Errors = append(s.Errors, err.Error())
  129. }
  130. }
  131. // Logf writes to the log message list. s must not be locked.
  132. // s's Log member will drop an old message if it would otherwise
  133. // become longer than 500 messages.
  134. func (s *State) Logf(format string, args ...interface{}) {
  135. s.lock.Lock()
  136. defer s.lock.Unlock()
  137. s.Log = append(s.Log, fmt.Sprintf(format, args...))
  138. if len(s.Log) > 500 {
  139. s.Log = s.Log[1:]
  140. }
  141. }
  142. // s must not be locked
  143. func (s *State) appendSuccessfulSend(toHostname string) {
  144. s.lock.Lock()
  145. defer s.lock.Unlock()
  146. if s.Sent == nil {
  147. s.Sent = map[string]int{}
  148. }
  149. s.Sent[toHostname]++
  150. }
  151. var (
  152. // Our one and only state object
  153. state State
  154. )
  155. func main() {
  156. flag.Parse()
  157. if *service == "" {
  158. log.Fatal("Must provide -service flag.")
  159. }
  160. hostname, err := os.Hostname()
  161. if err != nil {
  162. log.Fatalf("Error getting hostname: %v", err)
  163. }
  164. if *delayShutdown > 0 {
  165. termCh := make(chan os.Signal)
  166. signal.Notify(termCh, syscall.SIGTERM)
  167. go func() {
  168. <-termCh
  169. log.Printf("Sleeping %d seconds before exit ...", *delayShutdown)
  170. time.Sleep(time.Duration(*delayShutdown) * time.Second)
  171. os.Exit(0)
  172. }()
  173. }
  174. state := State{
  175. Hostname: hostname,
  176. StillContactingPeers: true,
  177. }
  178. go contactOthers(&state)
  179. http.HandleFunc("/quit", func(w http.ResponseWriter, r *http.Request) {
  180. os.Exit(0)
  181. })
  182. http.HandleFunc("/read", state.serveRead)
  183. http.HandleFunc("/write", state.serveWrite)
  184. http.HandleFunc("/status", state.serveStatus)
  185. go log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
  186. select {}
  187. }
  188. // Find all sibling pods in the service and post to their /write handler.
  189. func contactOthers(state *State) {
  190. var (
  191. versionInfo *version.Info
  192. err error
  193. )
  194. sleepTime := 5 * time.Second
  195. // In large cluster getting all endpoints is pretty expensive.
  196. // Thus, we will limit ourselves to send on average at most 10 such
  197. // requests per second
  198. if sleepTime < time.Duration(*peerCount/10)*time.Second {
  199. sleepTime = time.Duration(*peerCount/10) * time.Second
  200. }
  201. timeout := 5 * time.Minute
  202. // Similarly we need to bump timeout so that it is reasonable in large
  203. // clusters.
  204. if timeout < time.Duration(*peerCount)*time.Second {
  205. timeout = time.Duration(*peerCount) * time.Second
  206. }
  207. defer state.doneContactingPeers()
  208. config, err := restclient.InClusterConfig()
  209. if err != nil {
  210. log.Fatalf("Unable to create config; error: %v\n", err)
  211. }
  212. config.ContentType = "application/vnd.kubernetes.protobuf"
  213. client, err := clientset.NewForConfig(config)
  214. if err != nil {
  215. log.Fatalf("Unable to create client; error: %v\n", err)
  216. }
  217. // Try to get the server version until <timeout>; we use a timeout because
  218. // the pod might not have immediate network connectivity.
  219. for start := time.Now(); time.Since(start) < timeout; time.Sleep(sleepTime) {
  220. // Double check that worked by getting the server version.
  221. if versionInfo, err = client.Discovery().ServerVersion(); err != nil {
  222. log.Printf("Unable to get server version: %v; retrying.\n", err)
  223. } else {
  224. log.Printf("Server version: %#v\n", versionInfo)
  225. break
  226. }
  227. time.Sleep(1 * time.Second)
  228. }
  229. if err != nil {
  230. log.Fatalf("Unable to contact Kubernetes: %v\n", err)
  231. }
  232. for start := time.Now(); time.Since(start) < timeout; time.Sleep(sleepTime) {
  233. eps := getWebserverEndpoints(client)
  234. if eps.Len() >= *peerCount {
  235. break
  236. }
  237. state.Logf("%v/%v has %v endpoints (%v), which is less than %v as expected. Waiting for all endpoints to come up.", *namespace, *service, len(eps), eps.List(), *peerCount)
  238. }
  239. // Do this repeatedly, in case there's some propagation delay with getting
  240. // newly started pods into the endpoints list.
  241. for i := 0; i < 15; i++ {
  242. eps := getWebserverEndpoints(client)
  243. for ep := range eps {
  244. state.Logf("Attempting to contact %s", ep)
  245. contactSingle(ep, state)
  246. }
  247. time.Sleep(sleepTime)
  248. }
  249. }
  250. //getWebserverEndpoints returns the webserver endpoints as a set of String, each in the format like "http://{ip}:{port}"
  251. func getWebserverEndpoints(client clientset.Interface) sets.String {
  252. endpoints, err := client.CoreV1().Endpoints(*namespace).Get(*service, v1.GetOptions{})
  253. eps := sets.String{}
  254. if err != nil {
  255. state.Logf("Unable to read the endpoints for %v/%v: %v.", *namespace, *service, err)
  256. return eps
  257. }
  258. for _, ss := range endpoints.Subsets {
  259. for _, a := range ss.Addresses {
  260. for _, p := range ss.Ports {
  261. ipPort := net.JoinHostPort(a.IP, fmt.Sprint(p.Port))
  262. eps.Insert(fmt.Sprintf("http://%s", ipPort))
  263. }
  264. }
  265. }
  266. return eps
  267. }
  268. // contactSingle dials the address 'e' and tries to POST to its /write address.
  269. func contactSingle(e string, state *State) {
  270. body, err := json.Marshal(&WritePost{
  271. Dest: e,
  272. Source: state.Hostname,
  273. })
  274. if err != nil {
  275. log.Fatalf("json marshal error: %v", err)
  276. }
  277. resp, err := http.Post(e+"/write", "application/json", bytes.NewReader(body))
  278. if err != nil {
  279. state.Logf("Warning: unable to contact the endpoint %q: %v", e, err)
  280. return
  281. }
  282. defer resp.Body.Close()
  283. body, err = ioutil.ReadAll(resp.Body)
  284. if err != nil {
  285. state.Logf("Warning: unable to read response from '%v': '%v'", e, err)
  286. return
  287. }
  288. var wr WriteResp
  289. err = json.Unmarshal(body, &wr)
  290. if err != nil {
  291. state.Logf("Warning: unable to unmarshal response (%v) from '%v': '%v'", string(body), e, err)
  292. return
  293. }
  294. state.appendSuccessfulSend(wr.Hostname)
  295. }