config.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. package guerrilla
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "reflect"
  8. "strings"
  9. )
  10. // AppConfig is the holder of the configuration of the app
  11. type AppConfig struct {
  12. Servers []ServerConfig `json:"servers"`
  13. AllowedHosts []string `json:"allowed_hosts"`
  14. PidFile string `json:"pid_file"`
  15. }
  16. // ServerConfig specifies config options for a single server
  17. type ServerConfig struct {
  18. IsEnabled bool `json:"is_enabled"`
  19. Hostname string `json:"host_name"`
  20. MaxSize int64 `json:"max_size"`
  21. PrivateKeyFile string `json:"private_key_file"`
  22. PublicKeyFile string `json:"public_key_file"`
  23. Timeout int `json:"timeout"`
  24. ListenInterface string `json:"listen_interface"`
  25. StartTLSOn bool `json:"start_tls_on,omitempty"`
  26. TLSAlwaysOn bool `json:"tls_always_on,omitempty"`
  27. MaxClients int `json:"max_clients"`
  28. LogFile string `json:"log_file,omitempty"`
  29. _privateKeyFile_mtime int
  30. _publicKeyFile_mtime int
  31. }
  32. // Unmarshalls json data into AppConfig struct and any other initialization of the struct
  33. func (c *AppConfig) Load(jsonBytes []byte) error {
  34. err := json.Unmarshal(jsonBytes, c)
  35. if err != nil {
  36. return fmt.Errorf("could not parse config file: %s", err)
  37. }
  38. if len(c.AllowedHosts) == 0 {
  39. return errors.New("empty AllowedHosts is not allowed")
  40. }
  41. // read the timestamps for the ssl keys, to determine if they need to be reloaded
  42. for i := 0; i < len(c.Servers); i++ {
  43. if err := c.Servers[i].loadTlsKeyTimestamps(); err != nil {
  44. return err
  45. }
  46. }
  47. return nil
  48. }
  49. // Emits any configuration change events onto the event bus.
  50. func (c *AppConfig) EmitChangeEvents(oldConfig *AppConfig, app Guerrilla) {
  51. // has 'allowed hosts' changed?
  52. if !reflect.DeepEqual(oldConfig.AllowedHosts, c.AllowedHosts) {
  53. app.Publish("config_change:allowed_hosts", c)
  54. }
  55. // has pid file changed?
  56. if strings.Compare(oldConfig.PidFile, c.PidFile) != 0 {
  57. app.Publish("config_change:pid_file", c)
  58. }
  59. // server config changes
  60. oldServers := oldConfig.getServers()
  61. for iface, newServer := range c.getServers() {
  62. // is server is in both configs?
  63. if oldServer, ok := oldServers[iface]; ok {
  64. // since old server exists in the new config, we do not track it anymore
  65. delete(oldServers, iface)
  66. newServer.emitChangeEvents(oldServer, app)
  67. } else {
  68. // start new server
  69. app.Publish("server_change:new_server", newServer)
  70. }
  71. }
  72. // remove any servers that don't exist anymore
  73. for _, oldserver := range oldServers {
  74. app.Publish("server_change:remove_server", oldserver)
  75. }
  76. }
  77. // gets the servers in a map (key by interface) for easy lookup
  78. func (c *AppConfig) getServers() map[string]*ServerConfig {
  79. servers := make(map[string]*ServerConfig, len(c.Servers))
  80. for i := 0; i < len(c.Servers); i++ {
  81. servers[c.Servers[i].ListenInterface] = &c.Servers[i]
  82. }
  83. return servers
  84. }
  85. // Emits any configuration change events on the server.
  86. // All events are fired and run synchronously
  87. func (sc *ServerConfig) emitChangeEvents(oldServer *ServerConfig, app Guerrilla) {
  88. // get a list of changes
  89. changes := getDiff(
  90. *oldServer,
  91. *sc,
  92. )
  93. if len(changes) > 0 {
  94. // something changed in the server config
  95. app.Publish("server_change:update_config", sc)
  96. }
  97. // enable or disable?
  98. if _, ok := changes["IsEnabled"]; ok {
  99. if sc.IsEnabled {
  100. app.Publish("server_change:start_server", sc)
  101. } else {
  102. app.Publish("server_change:stop_server", sc)
  103. }
  104. // do not emit any more events when IsEnabled changed
  105. return
  106. }
  107. // log file change?
  108. if _, ok := changes["LogFile"]; ok {
  109. app.Publish("server_change:"+sc.ListenInterface+":new_log_file", sc)
  110. } else {
  111. // since config file has not changed, we reload it
  112. app.Publish("server_change:"+sc.ListenInterface+":reopen_log_file", sc)
  113. }
  114. // timeout changed
  115. if _, ok := changes["Timeout"]; ok {
  116. app.Publish("server_change:timeout", sc)
  117. }
  118. // max_clients changed
  119. if _, ok := changes["MaxClients"]; ok {
  120. app.Publish("server_change:max_clients", sc)
  121. }
  122. // tls changed
  123. if ok := func() bool {
  124. if _, ok := changes["PrivateKeyFile"]; ok {
  125. return true
  126. }
  127. if _, ok := changes["PublicKeyFile"]; ok {
  128. return true
  129. }
  130. if _, ok := changes["StartTLSOn"]; ok {
  131. return true
  132. }
  133. if _, ok := changes["TLSAlwaysOn"]; ok {
  134. return true
  135. }
  136. return false
  137. }(); ok {
  138. app.Publish("server_change:tls_config", sc)
  139. }
  140. }
  141. // Loads in timestamps for the ssl keys
  142. func (sc *ServerConfig) loadTlsKeyTimestamps() error {
  143. var statErr = func(iface string, err error) error {
  144. return errors.New(
  145. fmt.Sprintf(
  146. "could not stat key for server [%s], %s",
  147. iface,
  148. err.Error()))
  149. }
  150. if info, err := os.Stat(sc.PrivateKeyFile); err == nil {
  151. sc._privateKeyFile_mtime = info.ModTime().Second()
  152. } else {
  153. return statErr(sc.ListenInterface, err)
  154. }
  155. if info, err := os.Stat(sc.PublicKeyFile); err == nil {
  156. sc._publicKeyFile_mtime = info.ModTime().Second()
  157. } else {
  158. return statErr(sc.ListenInterface, err)
  159. }
  160. return nil
  161. }
  162. // Gets the timestamp of the TLS certificates. Returns a unix time of when they were last modified
  163. // when the config was read. We use this info to determine if TLS needs to be re-loaded.
  164. func (sc *ServerConfig) getTlsKeyTimestamps() (int, int) {
  165. return sc._privateKeyFile_mtime, sc._publicKeyFile_mtime
  166. }
  167. // Returns a diff between struct a & struct b.
  168. // Results are returned in a map, where each key is the name of the field that was different.
  169. // a and b are struct values, must not be pointer
  170. // and of the same struct type
  171. func getDiff(a interface{}, b interface{}) map[string]interface{} {
  172. ret := make(map[string]interface{}, 5)
  173. compareWith := structtomap(b)
  174. for key, val := range structtomap(a) {
  175. if val != compareWith[key] {
  176. ret[key] = compareWith[key]
  177. }
  178. }
  179. // detect tls changes (have the key files been modified?)
  180. if oldServer, ok := a.(ServerConfig); ok {
  181. t1, t2 := oldServer.getTlsKeyTimestamps()
  182. if newServer, ok := b.(ServerConfig); ok {
  183. t3, t4 := newServer.getTlsKeyTimestamps()
  184. if t1 != t3 {
  185. ret["PrivateKeyFile"] = newServer.PrivateKeyFile
  186. }
  187. if t2 != t4 {
  188. ret["PublicKeyFile"] = newServer.PublicKeyFile
  189. }
  190. }
  191. }
  192. return ret
  193. }
  194. // Convert fields of a struct to a map
  195. // only able to convert int, bool and string; not recursive
  196. func structtomap(obj interface{}) map[string]interface{} {
  197. ret := make(map[string]interface{}, 0)
  198. v := reflect.ValueOf(obj)
  199. t := v.Type()
  200. for index := 0; index < v.NumField(); index++ {
  201. vField := v.Field(index)
  202. fName := t.Field(index).Name
  203. switch vField.Kind() {
  204. case reflect.Int:
  205. value := vField.Int()
  206. ret[fName] = value
  207. case reflect.String:
  208. value := vField.String()
  209. ret[fName] = value
  210. case reflect.Bool:
  211. value := vField.Bool()
  212. ret[fName] = value
  213. }
  214. }
  215. return ret
  216. }