serve_hostname.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 small utility to just serve the hostname on TCP and/or UDP.
  14. package servehostname
  15. import (
  16. "fmt"
  17. "log"
  18. "net"
  19. "net/http"
  20. "os"
  21. "os/signal"
  22. "syscall"
  23. "time"
  24. "github.com/spf13/cobra"
  25. )
  26. // CmdServeHostname is used by agnhost Cobra.
  27. var CmdServeHostname = &cobra.Command{
  28. Use: "serve-hostname",
  29. Short: "Serves the hostname",
  30. Long: `Serves the hostname through HTTP / TCP / UDP on the given port.`,
  31. Args: cobra.MaximumNArgs(0),
  32. Run: main,
  33. }
  34. var (
  35. doTCP bool
  36. doUDP bool
  37. doHTTP bool
  38. doClose bool
  39. port int
  40. )
  41. func init() {
  42. CmdServeHostname.Flags().BoolVar(&doTCP, "tcp", false, "Serve raw over TCP.")
  43. CmdServeHostname.Flags().BoolVar(&doUDP, "udp", false, "Serve raw over UDP.")
  44. CmdServeHostname.Flags().BoolVar(&doHTTP, "http", true, "Serve HTTP.")
  45. CmdServeHostname.Flags().BoolVar(&doClose, "close", false, "Close connection per each HTTP request.")
  46. CmdServeHostname.Flags().IntVar(&port, "port", 9376, "Port number.")
  47. }
  48. func main(cmd *cobra.Command, args []string) {
  49. if doHTTP && (doTCP || doUDP) {
  50. log.Fatalf("Can't server TCP/UDP mode and HTTP mode at the same time")
  51. }
  52. hostname, err := os.Hostname()
  53. if err != nil {
  54. log.Fatalf("Error from os.Hostname(): %s", err)
  55. }
  56. if doTCP {
  57. listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
  58. if err != nil {
  59. log.Fatalf("Error from net.Listen(): %s", err)
  60. }
  61. go func() {
  62. for {
  63. conn, err := listener.Accept()
  64. if err != nil {
  65. log.Fatalf("Error from Accept(): %s", err)
  66. }
  67. log.Printf("TCP request from %s", conn.RemoteAddr().String())
  68. conn.Write([]byte(hostname))
  69. conn.Close()
  70. }
  71. }()
  72. }
  73. if doUDP {
  74. addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", port))
  75. if err != nil {
  76. log.Fatalf("Error from net.ResolveUDPAddr(): %s", err)
  77. }
  78. sock, err := net.ListenUDP("udp", addr)
  79. if err != nil {
  80. log.Fatalf("Error from ListenUDP(): %s", err)
  81. }
  82. go func() {
  83. var buffer [16]byte
  84. for {
  85. _, cliAddr, err := sock.ReadFrom(buffer[0:])
  86. if err != nil {
  87. log.Fatalf("Error from ReadFrom(): %s", err)
  88. }
  89. log.Printf("UDP request from %s", cliAddr.String())
  90. sock.WriteTo([]byte(hostname), cliAddr)
  91. }
  92. }()
  93. }
  94. if doHTTP {
  95. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  96. log.Printf("HTTP request from %s", r.RemoteAddr)
  97. if doClose {
  98. // Add this header to force to close the connection after serving the request.
  99. w.Header().Add("Connection", "close")
  100. }
  101. fmt.Fprintf(w, "%s", hostname)
  102. })
  103. go func() {
  104. // Run in a closure so http.ListenAndServe doesn't block
  105. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
  106. }()
  107. }
  108. log.Printf("Serving on port %d.\n", port)
  109. signals := make(chan os.Signal, 1)
  110. signal.Notify(signals, syscall.SIGTERM)
  111. sig := <-signals
  112. log.Printf("Shutting down after receiving signal: %s.\n", sig)
  113. log.Printf("Awaiting pod deletion.\n")
  114. time.Sleep(60 * time.Second)
  115. }