log.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "encoding/json"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. go_log "log"
  26. "os"
  27. "sync"
  28. "sync/atomic"
  29. "time"
  30. "github.com/Psiphon-Inc/rotate-safe-writer"
  31. udsipc "github.com/Psiphon-Inc/uds-ipc"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/stacktrace"
  36. "github.com/sirupsen/logrus"
  37. "google.golang.org/protobuf/proto"
  38. )
  39. // TraceLogger adds single frame stack trace information to the underlying
  40. // logging facilities.
  41. type TraceLogger struct {
  42. *logrus.Logger
  43. }
  44. // LogFields is an alias for the field struct in the underlying logging
  45. // package.
  46. type LogFields logrus.Fields
  47. // Add copies log fields from b to a, skipping fields which already exist,
  48. // regardless of value, in a.
  49. func (a LogFields) Add(b LogFields) {
  50. for name, value := range b {
  51. _, ok := a[name]
  52. if !ok {
  53. a[name] = value
  54. }
  55. }
  56. }
  57. // WithTrace adds a "trace" field containing the caller's function name and
  58. // source file line number; and "host_id", "provider", and "build_rev" fields
  59. // identifying this server and build. Use this function when the log has no
  60. // fields.
  61. func (logger *TraceLogger) WithTrace() *logrus.Entry {
  62. fields := logrus.Fields{
  63. "trace": stacktrace.GetParentFunctionName(),
  64. "host_id": logHostID,
  65. "build_rev": logBuildRev,
  66. }
  67. if logHostProvider != "" {
  68. fields["provider"] = logHostProvider
  69. }
  70. return logger.WithFields(fields)
  71. }
  72. func renameLogFields(fields LogFields) {
  73. if _, ok := fields["trace"]; ok {
  74. fields["fields.trace"] = fields["trace"]
  75. }
  76. if _, ok := fields["host_id"]; ok {
  77. fields["fields.host_id"] = fields["host_id"]
  78. }
  79. if _, ok := fields["provider"]; ok {
  80. fields["fields.provider"] = fields["provider"]
  81. }
  82. if _, ok := fields["build_rev"]; ok {
  83. fields["fields.build_rev"] = fields["build_rev"]
  84. }
  85. }
  86. // WithTraceFields adds a "trace" field containing the caller's function name
  87. // and source file line number; and "host_id", "provider", and "build_rev"
  88. // fields identifying this server and build. Use this function when the log
  89. // has fields.
  90. //
  91. // Note that any existing "trace"/"host_id"/"provider"/build_rev" field will
  92. // be renamed to "field.<name>".
  93. func (logger *TraceLogger) WithTraceFields(fields LogFields) *logrus.Entry {
  94. renameLogFields(fields)
  95. fields["trace"] = stacktrace.GetParentFunctionName()
  96. fields["host_id"] = logHostID
  97. if logHostProvider != "" {
  98. fields["provider"] = logHostProvider
  99. }
  100. fields["build_rev"] = logBuildRev
  101. return logger.WithFields(logrus.Fields(fields))
  102. }
  103. // LogRawFieldsWithTimestamp directly logs the supplied fields adding only an
  104. // additional "timestamp" field; and "host_id", "provider", and "build_rev"
  105. // fields identifying this server and build. The stock "msg" and "level"
  106. // fields are omitted.
  107. //
  108. // If JSON logging is enabled, this log is emitted at the Error level. This
  109. // function exists to support API logs which have neither a natural message
  110. // nor severity; and omitting these values here makes it easier to ship these
  111. // logs to existing API log consumers.
  112. //
  113. // If protobuf logging is enabled, the LogFields map will be parsed and used
  114. // to populate a protobuf message struct pointer which is then serialized and
  115. // emitted to a local metrics socket.
  116. //
  117. // Note that any existing "trace"/"host_id"/"provider"/"build_rev" field will
  118. // be renamed to "field.<name>".
  119. func (logger *TraceLogger) LogRawFieldsWithTimestamp(fields LogFields) {
  120. if ShouldLogJSON() {
  121. renameLogFields(fields)
  122. fields["host_id"] = logHostID
  123. if logHostProvider != "" {
  124. fields["provider"] = logHostProvider
  125. }
  126. fields["build_rev"] = logBuildRev
  127. logger.WithFields(logrus.Fields(fields)).Error(
  128. customJSONFormatterLogRawFieldsWithTimestamp)
  129. }
  130. if ShouldLogProtobuf() {
  131. for _, protoMsg := range logFieldsToProtobuf(fields) {
  132. if protoMsg == nil {
  133. logger.WithTrace().Error("failed to populate protobuf message struct")
  134. continue
  135. }
  136. serialized, err := proto.Marshal(protoMsg)
  137. if err != nil {
  138. logger.WithTrace().Errorf("failed to serialize protobuf message: %s", err.Error())
  139. continue
  140. }
  141. err = metricSocketWriter.WriteMessage(serialized)
  142. if err != nil {
  143. // The only error this can be is udsipc.ErrBufferFull
  144. logger.WithTrace().Error("metric socket write buffer is full: log dropped")
  145. continue
  146. }
  147. }
  148. }
  149. }
  150. // LogPanicRecover calls LogRawFieldsWithTimestamp with standard fields
  151. // for logging recovered panics.
  152. func (logger *TraceLogger) LogPanicRecover(recoverValue interface{}, stack []byte) {
  153. log.LogRawFieldsWithTimestamp(
  154. LogFields{
  155. "event_name": "panic",
  156. "recover_value": recoverValue,
  157. "stack": string(stack),
  158. })
  159. }
  160. type commonLogger struct {
  161. traceLogger *TraceLogger
  162. }
  163. func (logger *commonLogger) WithTrace() common.LogTrace {
  164. // Patch trace to be correct parent
  165. return logger.traceLogger.WithTrace().WithField(
  166. "trace", stacktrace.GetParentFunctionName())
  167. }
  168. func (logger *commonLogger) WithTraceFields(fields common.LogFields) common.LogTrace {
  169. // Patch trace to be correct parent
  170. return logger.traceLogger.WithTraceFields(LogFields(fields)).WithField(
  171. "trace", stacktrace.GetParentFunctionName())
  172. }
  173. func (logger *commonLogger) LogMetric(metric string, fields common.LogFields) {
  174. fields["event_name"] = metric
  175. logger.traceLogger.LogRawFieldsWithTimestamp(LogFields(fields))
  176. }
  177. func (logger *commonLogger) IsLogLevelDebug() bool {
  178. return logger.traceLogger.Level == logrus.DebugLevel
  179. }
  180. // CommonLogger wraps a TraceLogger instance with an interface that conforms
  181. // to common.Logger. This is used to make the TraceLogger available to other
  182. // packages that don't import the "server" package.
  183. func CommonLogger(traceLogger *TraceLogger) *commonLogger {
  184. return &commonLogger{
  185. traceLogger: traceLogger,
  186. }
  187. }
  188. // NewLogWriter returns an io.PipeWriter that can be used to write
  189. // to the global logger. Caller must Close() the writer.
  190. func NewLogWriter() *io.PipeWriter {
  191. return log.Writer()
  192. }
  193. // CustomJSONFormatter is a customized version of logrus.JSONFormatter
  194. type CustomJSONFormatter struct {
  195. }
  196. var (
  197. useLogCallback int32
  198. logCallback atomic.Value
  199. )
  200. // setLogCallback sets a callback that is invoked with each JSON log message.
  201. // This facility is intended for use in testing only.
  202. func setLogCallback(callback func([]byte)) {
  203. if callback == nil {
  204. atomic.StoreInt32(&useLogCallback, 0)
  205. return
  206. }
  207. atomic.StoreInt32(&useLogCallback, 1)
  208. logCallback.Store(callback)
  209. }
  210. const customJSONFormatterLogRawFieldsWithTimestamp = "CustomJSONFormatter.LogRawFieldsWithTimestamp"
  211. // Format implements logrus.Formatter. This is a customized version
  212. // of the standard logrus.JSONFormatter adapted from:
  213. // https://github.com/Sirupsen/logrus/blob/f1addc29722ba9f7651bc42b4198d0944b66e7c4/json_formatter.go
  214. //
  215. // The changes are:
  216. // - "time" is renamed to "timestamp"
  217. // - there's an option to omit the standard "msg" and "level" fields
  218. func (f *CustomJSONFormatter) Format(entry *logrus.Entry) ([]byte, error) {
  219. data := make(logrus.Fields, len(entry.Data)+3)
  220. for k, v := range entry.Data {
  221. switch v := v.(type) {
  222. case error:
  223. // Otherwise errors are ignored by `encoding/json`
  224. // https://github.com/Sirupsen/logrus/issues/137
  225. data[k] = v.Error()
  226. default:
  227. data[k] = v
  228. }
  229. }
  230. if t, ok := data["timestamp"]; ok {
  231. data["fields.timestamp"] = t
  232. }
  233. data["timestamp"] = entry.Time.Format(time.RFC3339)
  234. if entry.Message != customJSONFormatterLogRawFieldsWithTimestamp {
  235. if m, ok := data["msg"]; ok {
  236. data["fields.msg"] = m
  237. }
  238. if l, ok := data["level"]; ok {
  239. data["fields.level"] = l
  240. }
  241. data["msg"] = entry.Message
  242. data["level"] = entry.Level.String()
  243. }
  244. serialized, err := json.Marshal(data)
  245. if err != nil {
  246. return nil, fmt.Errorf("failed to marshal fields to JSON, %v", err)
  247. }
  248. if atomic.LoadInt32(&useLogCallback) == 1 {
  249. logCallback.Load().(func([]byte))(serialized)
  250. }
  251. return append(serialized, '\n'), nil
  252. }
  253. var log *TraceLogger
  254. var logFormat, logHostID, logHostProvider, logBuildRev, logDestinationPrefix string
  255. var metricSocketWriter *udsipc.Writer
  256. var shouldLogJSON, shouldLogProtobuf bool
  257. var initLogging sync.Once
  258. // InitLogging configures a logger according to the specified
  259. // config params. If not called, the default logger set by the
  260. // package init() is used.
  261. // Concurrency notes: this should only be called from the main
  262. // goroutine; InitLogging only has effect on the first call, as
  263. // the logging facilities it initializes may be in use by other
  264. // goroutines after that point.
  265. func InitLogging(config *Config) (retErr error) {
  266. initLogging.Do(func() {
  267. logHostID = config.HostID
  268. logHostProvider = config.HostProvider
  269. logBuildRev = buildinfo.GetBuildInfo().BuildRev
  270. logFormat = config.LogFormat
  271. logDestinationPrefix = config.LogDestinationPrefix
  272. level, err := logrus.ParseLevel(config.LogLevel)
  273. if err != nil {
  274. retErr = errors.Trace(err)
  275. return
  276. }
  277. // To retain backwards compatibility, the zero-value for log format
  278. // should retain the existing behavior (JSON logging only).
  279. if logFormat == "" {
  280. logFormat = "json"
  281. }
  282. shouldLogProtobuf = (logFormat == "protobuf" || logFormat == "both")
  283. shouldLogJSON = (logFormat == "json" || logFormat == "both")
  284. var logWriter io.Writer
  285. if config.LogFilename != "" {
  286. retries, create, mode := config.GetLogFileReopenConfig()
  287. logWriter, err = rotate.NewRotatableFileWriter(
  288. config.LogFilename, retries, create, mode)
  289. if err != nil {
  290. retErr = errors.Trace(err)
  291. return
  292. }
  293. if !config.SkipPanickingLogWriter {
  294. // Use PanickingLogWriter, which will intentionally
  295. // panic when a Write fails. Set SkipPanickingLogWriter
  296. // if this behavior is not desired.
  297. //
  298. // Note that NewRotatableFileWriter will first attempt
  299. // a retry when a Write fails.
  300. //
  301. // It is assumed that continuing operation while unable
  302. // to log is unacceptable; and that the psiphond service
  303. // is managed and will restart when it terminates.
  304. //
  305. // It is further assumed that panicking will result in
  306. // an error that is externally logged and reported to a
  307. // monitoring system.
  308. //
  309. // TODO: An orderly shutdown may be preferred, as some
  310. // data will be lost in a panic (e.g., server_tunnel logs).
  311. // It may be possible to perform an orderly shutdown first
  312. // and then panic, or perform an orderly shutdown and
  313. // simulate a panic message that will be reported.
  314. logWriter = NewPanickingLogWriter(config.LogFilename, logWriter)
  315. }
  316. } else {
  317. logWriter = os.Stderr
  318. }
  319. log = &TraceLogger{
  320. &logrus.Logger{
  321. Out: logWriter,
  322. Formatter: &CustomJSONFormatter{},
  323. Level: level,
  324. },
  325. }
  326. if shouldLogProtobuf {
  327. metricSocketWriter, retErr = udsipc.NewWriter(config.MetricSocketPath)
  328. if retErr != nil {
  329. retErr = errors.Tracef("failed to start metric socket writer: %w", retErr)
  330. return
  331. }
  332. metricSocketWriter.Start()
  333. }
  334. })
  335. return retErr
  336. }
  337. func IsLogLevelDebug() bool {
  338. return log.Level == logrus.DebugLevel
  339. }
  340. func ShouldLogProtobuf() bool {
  341. return shouldLogProtobuf
  342. }
  343. func ShouldLogJSON() bool {
  344. return shouldLogJSON
  345. }
  346. func init() {
  347. // Suppress standard "log" package logging performed by other packages.
  348. // For example, "net/http" logs messages such as:
  349. // "http: TLS handshake error from <client-ip-addr>:<port>: [...]: i/o timeout"
  350. go_log.SetOutput(ioutil.Discard)
  351. // Set default format
  352. logFormat = "json"
  353. shouldLogJSON = true
  354. log = &TraceLogger{
  355. &logrus.Logger{
  356. Out: os.Stderr,
  357. Formatter: &CustomJSONFormatter{},
  358. Hooks: make(logrus.LevelHooks),
  359. Level: logrus.DebugLevel,
  360. },
  361. }
  362. }