You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

webhook.go 23 kB

11 years ago
11 years ago
8 years ago
8 years ago
8 years ago
11 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
8 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "crypto/hmac"
  8. "crypto/sha256"
  9. "crypto/tls"
  10. "encoding/hex"
  11. "encoding/json"
  12. "fmt"
  13. "io/ioutil"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/modules/httplib"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/sync"
  20. "code.gitea.io/gitea/modules/util"
  21. api "code.gitea.io/sdk/gitea"
  22. "github.com/Unknwon/com"
  23. gouuid "github.com/satori/go.uuid"
  24. )
  25. // HookQueue is a global queue of web hooks
  26. var HookQueue = sync.NewUniqueQueue(setting.Webhook.QueueLength)
  27. // HookContentType is the content type of a web hook
  28. type HookContentType int
  29. const (
  30. // ContentTypeJSON is a JSON payload for web hooks
  31. ContentTypeJSON HookContentType = iota + 1
  32. // ContentTypeForm is an url-encoded form payload for web hook
  33. ContentTypeForm
  34. )
  35. var hookContentTypes = map[string]HookContentType{
  36. "json": ContentTypeJSON,
  37. "form": ContentTypeForm,
  38. }
  39. // ToHookContentType returns HookContentType by given name.
  40. func ToHookContentType(name string) HookContentType {
  41. return hookContentTypes[name]
  42. }
  43. // Name returns the name of a given web hook's content type
  44. func (t HookContentType) Name() string {
  45. switch t {
  46. case ContentTypeJSON:
  47. return "json"
  48. case ContentTypeForm:
  49. return "form"
  50. }
  51. return ""
  52. }
  53. // IsValidHookContentType returns true if given name is a valid hook content type.
  54. func IsValidHookContentType(name string) bool {
  55. _, ok := hookContentTypes[name]
  56. return ok
  57. }
  58. // HookEvents is a set of web hook events
  59. type HookEvents struct {
  60. Create bool `json:"create"`
  61. Delete bool `json:"delete"`
  62. Fork bool `json:"fork"`
  63. Issues bool `json:"issues"`
  64. IssueComment bool `json:"issue_comment"`
  65. Push bool `json:"push"`
  66. PullRequest bool `json:"pull_request"`
  67. Repository bool `json:"repository"`
  68. Release bool `json:"release"`
  69. }
  70. // HookEvent represents events that will delivery hook.
  71. type HookEvent struct {
  72. PushOnly bool `json:"push_only"`
  73. SendEverything bool `json:"send_everything"`
  74. ChooseEvents bool `json:"choose_events"`
  75. HookEvents `json:"events"`
  76. }
  77. // HookStatus is the status of a web hook
  78. type HookStatus int
  79. // Possible statuses of a web hook
  80. const (
  81. HookStatusNone = iota
  82. HookStatusSucceed
  83. HookStatusFail
  84. )
  85. // Webhook represents a web hook object.
  86. type Webhook struct {
  87. ID int64 `xorm:"pk autoincr"`
  88. RepoID int64 `xorm:"INDEX"`
  89. OrgID int64 `xorm:"INDEX"`
  90. URL string `xorm:"url TEXT"`
  91. Signature string `xorm:"TEXT"`
  92. ContentType HookContentType
  93. Secret string `xorm:"TEXT"`
  94. Events string `xorm:"TEXT"`
  95. *HookEvent `xorm:"-"`
  96. IsSSL bool `xorm:"is_ssl"`
  97. IsActive bool `xorm:"INDEX"`
  98. HookTaskType HookTaskType
  99. Meta string `xorm:"TEXT"` // store hook-specific attributes
  100. LastStatus HookStatus // Last delivery status
  101. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  102. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  103. }
  104. // AfterLoad updates the webhook object upon setting a column
  105. func (w *Webhook) AfterLoad() {
  106. w.HookEvent = &HookEvent{}
  107. if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
  108. log.Error("Unmarshal[%d]: %v", w.ID, err)
  109. }
  110. }
  111. // GetSlackHook returns slack metadata
  112. func (w *Webhook) GetSlackHook() *SlackMeta {
  113. s := &SlackMeta{}
  114. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  115. log.Error("webhook.GetSlackHook(%d): %v", w.ID, err)
  116. }
  117. return s
  118. }
  119. // GetDiscordHook returns discord metadata
  120. func (w *Webhook) GetDiscordHook() *DiscordMeta {
  121. s := &DiscordMeta{}
  122. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  123. log.Error("webhook.GetDiscordHook(%d): %v", w.ID, err)
  124. }
  125. return s
  126. }
  127. // GetTelegramHook returns telegram metadata
  128. func (w *Webhook) GetTelegramHook() *TelegramMeta {
  129. s := &TelegramMeta{}
  130. if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
  131. log.Error("webhook.GetTelegramHook(%d): %v", w.ID, err)
  132. }
  133. return s
  134. }
  135. // History returns history of webhook by given conditions.
  136. func (w *Webhook) History(page int) ([]*HookTask, error) {
  137. return HookTasks(w.ID, page)
  138. }
  139. // UpdateEvent handles conversion from HookEvent to Events.
  140. func (w *Webhook) UpdateEvent() error {
  141. data, err := json.Marshal(w.HookEvent)
  142. w.Events = string(data)
  143. return err
  144. }
  145. // HasCreateEvent returns true if hook enabled create event.
  146. func (w *Webhook) HasCreateEvent() bool {
  147. return w.SendEverything ||
  148. (w.ChooseEvents && w.HookEvents.Create)
  149. }
  150. // HasDeleteEvent returns true if hook enabled delete event.
  151. func (w *Webhook) HasDeleteEvent() bool {
  152. return w.SendEverything ||
  153. (w.ChooseEvents && w.HookEvents.Delete)
  154. }
  155. // HasForkEvent returns true if hook enabled fork event.
  156. func (w *Webhook) HasForkEvent() bool {
  157. return w.SendEverything ||
  158. (w.ChooseEvents && w.HookEvents.Fork)
  159. }
  160. // HasIssuesEvent returns true if hook enabled issues event.
  161. func (w *Webhook) HasIssuesEvent() bool {
  162. return w.SendEverything ||
  163. (w.ChooseEvents && w.HookEvents.Issues)
  164. }
  165. // HasIssueCommentEvent returns true if hook enabled issue_comment event.
  166. func (w *Webhook) HasIssueCommentEvent() bool {
  167. return w.SendEverything ||
  168. (w.ChooseEvents && w.HookEvents.IssueComment)
  169. }
  170. // HasPushEvent returns true if hook enabled push event.
  171. func (w *Webhook) HasPushEvent() bool {
  172. return w.PushOnly || w.SendEverything ||
  173. (w.ChooseEvents && w.HookEvents.Push)
  174. }
  175. // HasPullRequestEvent returns true if hook enabled pull request event.
  176. func (w *Webhook) HasPullRequestEvent() bool {
  177. return w.SendEverything ||
  178. (w.ChooseEvents && w.HookEvents.PullRequest)
  179. }
  180. // HasReleaseEvent returns if hook enabled release event.
  181. func (w *Webhook) HasReleaseEvent() bool {
  182. return w.SendEverything ||
  183. (w.ChooseEvents && w.HookEvents.Release)
  184. }
  185. // HasRepositoryEvent returns if hook enabled repository event.
  186. func (w *Webhook) HasRepositoryEvent() bool {
  187. return w.SendEverything ||
  188. (w.ChooseEvents && w.HookEvents.Repository)
  189. }
  190. func (w *Webhook) eventCheckers() []struct {
  191. has func() bool
  192. typ HookEventType
  193. } {
  194. return []struct {
  195. has func() bool
  196. typ HookEventType
  197. }{
  198. {w.HasCreateEvent, HookEventCreate},
  199. {w.HasDeleteEvent, HookEventDelete},
  200. {w.HasForkEvent, HookEventFork},
  201. {w.HasPushEvent, HookEventPush},
  202. {w.HasIssuesEvent, HookEventIssues},
  203. {w.HasIssueCommentEvent, HookEventIssueComment},
  204. {w.HasPullRequestEvent, HookEventPullRequest},
  205. {w.HasRepositoryEvent, HookEventRepository},
  206. {w.HasReleaseEvent, HookEventRelease},
  207. }
  208. }
  209. // EventsArray returns an array of hook events
  210. func (w *Webhook) EventsArray() []string {
  211. events := make([]string, 0, 7)
  212. for _, c := range w.eventCheckers() {
  213. if c.has() {
  214. events = append(events, string(c.typ))
  215. }
  216. }
  217. return events
  218. }
  219. // CreateWebhook creates a new web hook.
  220. func CreateWebhook(w *Webhook) error {
  221. return createWebhook(x, w)
  222. }
  223. func createWebhook(e Engine, w *Webhook) error {
  224. _, err := e.Insert(w)
  225. return err
  226. }
  227. // getWebhook uses argument bean as query condition,
  228. // ID must be specified and do not assign unnecessary fields.
  229. func getWebhook(bean *Webhook) (*Webhook, error) {
  230. has, err := x.Get(bean)
  231. if err != nil {
  232. return nil, err
  233. } else if !has {
  234. return nil, ErrWebhookNotExist{bean.ID}
  235. }
  236. return bean, nil
  237. }
  238. // GetWebhookByID returns webhook of repository by given ID.
  239. func GetWebhookByID(id int64) (*Webhook, error) {
  240. return getWebhook(&Webhook{
  241. ID: id,
  242. })
  243. }
  244. // GetWebhookByRepoID returns webhook of repository by given ID.
  245. func GetWebhookByRepoID(repoID, id int64) (*Webhook, error) {
  246. return getWebhook(&Webhook{
  247. ID: id,
  248. RepoID: repoID,
  249. })
  250. }
  251. // GetWebhookByOrgID returns webhook of organization by given ID.
  252. func GetWebhookByOrgID(orgID, id int64) (*Webhook, error) {
  253. return getWebhook(&Webhook{
  254. ID: id,
  255. OrgID: orgID,
  256. })
  257. }
  258. // GetActiveWebhooksByRepoID returns all active webhooks of repository.
  259. func GetActiveWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  260. return getActiveWebhooksByRepoID(x, repoID)
  261. }
  262. func getActiveWebhooksByRepoID(e Engine, repoID int64) ([]*Webhook, error) {
  263. webhooks := make([]*Webhook, 0, 5)
  264. return webhooks, e.Where("is_active=?", true).
  265. Find(&webhooks, &Webhook{RepoID: repoID})
  266. }
  267. // GetWebhooksByRepoID returns all webhooks of a repository.
  268. func GetWebhooksByRepoID(repoID int64) ([]*Webhook, error) {
  269. webhooks := make([]*Webhook, 0, 5)
  270. return webhooks, x.Find(&webhooks, &Webhook{RepoID: repoID})
  271. }
  272. // GetActiveWebhooksByOrgID returns all active webhooks for an organization.
  273. func GetActiveWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  274. return getActiveWebhooksByOrgID(x, orgID)
  275. }
  276. func getActiveWebhooksByOrgID(e Engine, orgID int64) (ws []*Webhook, err error) {
  277. err = e.
  278. Where("org_id=?", orgID).
  279. And("is_active=?", true).
  280. Find(&ws)
  281. return ws, err
  282. }
  283. // GetWebhooksByOrgID returns all webhooks for an organization.
  284. func GetWebhooksByOrgID(orgID int64) (ws []*Webhook, err error) {
  285. err = x.Find(&ws, &Webhook{OrgID: orgID})
  286. return ws, err
  287. }
  288. // GetDefaultWebhook returns admin-default webhook by given ID.
  289. func GetDefaultWebhook(id int64) (*Webhook, error) {
  290. webhook := &Webhook{ID: id}
  291. has, err := x.
  292. Where("repo_id=? AND org_id=?", 0, 0).
  293. Get(webhook)
  294. if err != nil {
  295. return nil, err
  296. } else if !has {
  297. return nil, ErrWebhookNotExist{id}
  298. }
  299. return webhook, nil
  300. }
  301. // GetDefaultWebhooks returns all admin-default webhooks.
  302. func GetDefaultWebhooks() ([]*Webhook, error) {
  303. return getDefaultWebhooks(x)
  304. }
  305. func getDefaultWebhooks(e Engine) ([]*Webhook, error) {
  306. webhooks := make([]*Webhook, 0, 5)
  307. return webhooks, e.
  308. Where("repo_id=? AND org_id=?", 0, 0).
  309. Find(&webhooks)
  310. }
  311. // UpdateWebhook updates information of webhook.
  312. func UpdateWebhook(w *Webhook) error {
  313. _, err := x.ID(w.ID).AllCols().Update(w)
  314. return err
  315. }
  316. // UpdateWebhookLastStatus updates last status of webhook.
  317. func UpdateWebhookLastStatus(w *Webhook) error {
  318. _, err := x.ID(w.ID).Cols("last_status").Update(w)
  319. return err
  320. }
  321. // deleteWebhook uses argument bean as query condition,
  322. // ID must be specified and do not assign unnecessary fields.
  323. func deleteWebhook(bean *Webhook) (err error) {
  324. sess := x.NewSession()
  325. defer sess.Close()
  326. if err = sess.Begin(); err != nil {
  327. return err
  328. }
  329. if count, err := sess.Delete(bean); err != nil {
  330. return err
  331. } else if count == 0 {
  332. return ErrWebhookNotExist{ID: bean.ID}
  333. } else if _, err = sess.Delete(&HookTask{HookID: bean.ID}); err != nil {
  334. return err
  335. }
  336. return sess.Commit()
  337. }
  338. // DeleteWebhookByRepoID deletes webhook of repository by given ID.
  339. func DeleteWebhookByRepoID(repoID, id int64) error {
  340. return deleteWebhook(&Webhook{
  341. ID: id,
  342. RepoID: repoID,
  343. })
  344. }
  345. // DeleteWebhookByOrgID deletes webhook of organization by given ID.
  346. func DeleteWebhookByOrgID(orgID, id int64) error {
  347. return deleteWebhook(&Webhook{
  348. ID: id,
  349. OrgID: orgID,
  350. })
  351. }
  352. // DeleteDefaultWebhook deletes an admin-default webhook by given ID.
  353. func DeleteDefaultWebhook(id int64) error {
  354. sess := x.NewSession()
  355. defer sess.Close()
  356. if err := sess.Begin(); err != nil {
  357. return err
  358. }
  359. count, err := sess.
  360. Where("repo_id=? AND org_id=?", 0, 0).
  361. Delete(&Webhook{ID: id})
  362. if err != nil {
  363. return err
  364. } else if count == 0 {
  365. return ErrWebhookNotExist{ID: id}
  366. }
  367. if _, err := sess.Delete(&HookTask{HookID: id}); err != nil {
  368. return err
  369. }
  370. return sess.Commit()
  371. }
  372. // copyDefaultWebhooksToRepo creates copies of the default webhooks in a new repo
  373. func copyDefaultWebhooksToRepo(e Engine, repoID int64) error {
  374. ws, err := getDefaultWebhooks(e)
  375. if err != nil {
  376. return fmt.Errorf("GetDefaultWebhooks: %v", err)
  377. }
  378. for _, w := range ws {
  379. w.ID = 0
  380. w.RepoID = repoID
  381. if err := createWebhook(e, w); err != nil {
  382. return fmt.Errorf("CreateWebhook: %v", err)
  383. }
  384. }
  385. return nil
  386. }
  387. // ___ ___ __ ___________ __
  388. // / | \ ____ ____ | | _\__ ___/____ _____| | __
  389. // / ~ \/ _ \ / _ \| |/ / | | \__ \ / ___/ |/ /
  390. // \ Y ( <_> | <_> ) < | | / __ \_\___ \| <
  391. // \___|_ / \____/ \____/|__|_ \ |____| (____ /____ >__|_ \
  392. // \/ \/ \/ \/ \/
  393. // HookTaskType is the type of an hook task
  394. type HookTaskType int
  395. // Types of hook tasks
  396. const (
  397. GOGS HookTaskType = iota + 1
  398. SLACK
  399. GITEA
  400. DISCORD
  401. DINGTALK
  402. TELEGRAM
  403. )
  404. var hookTaskTypes = map[string]HookTaskType{
  405. "gitea": GITEA,
  406. "gogs": GOGS,
  407. "slack": SLACK,
  408. "discord": DISCORD,
  409. "dingtalk": DINGTALK,
  410. "telegram": TELEGRAM,
  411. }
  412. // ToHookTaskType returns HookTaskType by given name.
  413. func ToHookTaskType(name string) HookTaskType {
  414. return hookTaskTypes[name]
  415. }
  416. // Name returns the name of an hook task type
  417. func (t HookTaskType) Name() string {
  418. switch t {
  419. case GITEA:
  420. return "gitea"
  421. case GOGS:
  422. return "gogs"
  423. case SLACK:
  424. return "slack"
  425. case DISCORD:
  426. return "discord"
  427. case DINGTALK:
  428. return "dingtalk"
  429. case TELEGRAM:
  430. return "telegram"
  431. }
  432. return ""
  433. }
  434. // IsValidHookTaskType returns true if given name is a valid hook task type.
  435. func IsValidHookTaskType(name string) bool {
  436. _, ok := hookTaskTypes[name]
  437. return ok
  438. }
  439. // HookEventType is the type of an hook event
  440. type HookEventType string
  441. // Types of hook events
  442. const (
  443. HookEventCreate HookEventType = "create"
  444. HookEventDelete HookEventType = "delete"
  445. HookEventFork HookEventType = "fork"
  446. HookEventPush HookEventType = "push"
  447. HookEventIssues HookEventType = "issues"
  448. HookEventIssueComment HookEventType = "issue_comment"
  449. HookEventPullRequest HookEventType = "pull_request"
  450. HookEventRepository HookEventType = "repository"
  451. HookEventRelease HookEventType = "release"
  452. HookEventPullRequestApproved HookEventType = "pull_request_approved"
  453. HookEventPullRequestRejected HookEventType = "pull_request_rejected"
  454. HookEventPullRequestComment HookEventType = "pull_request_comment"
  455. )
  456. // HookRequest represents hook task request information.
  457. type HookRequest struct {
  458. Headers map[string]string `json:"headers"`
  459. }
  460. // HookResponse represents hook task response information.
  461. type HookResponse struct {
  462. Status int `json:"status"`
  463. Headers map[string]string `json:"headers"`
  464. Body string `json:"body"`
  465. }
  466. // HookTask represents a hook task.
  467. type HookTask struct {
  468. ID int64 `xorm:"pk autoincr"`
  469. RepoID int64 `xorm:"INDEX"`
  470. HookID int64
  471. UUID string
  472. Type HookTaskType
  473. URL string `xorm:"TEXT"`
  474. Signature string `xorm:"TEXT"`
  475. api.Payloader `xorm:"-"`
  476. PayloadContent string `xorm:"TEXT"`
  477. ContentType HookContentType
  478. EventType HookEventType
  479. IsSSL bool
  480. IsDelivered bool
  481. Delivered int64
  482. DeliveredString string `xorm:"-"`
  483. // History info.
  484. IsSucceed bool
  485. RequestContent string `xorm:"TEXT"`
  486. RequestInfo *HookRequest `xorm:"-"`
  487. ResponseContent string `xorm:"TEXT"`
  488. ResponseInfo *HookResponse `xorm:"-"`
  489. }
  490. // BeforeUpdate will be invoked by XORM before updating a record
  491. // representing this object
  492. func (t *HookTask) BeforeUpdate() {
  493. if t.RequestInfo != nil {
  494. t.RequestContent = t.simpleMarshalJSON(t.RequestInfo)
  495. }
  496. if t.ResponseInfo != nil {
  497. t.ResponseContent = t.simpleMarshalJSON(t.ResponseInfo)
  498. }
  499. }
  500. // AfterLoad updates the webhook object upon setting a column
  501. func (t *HookTask) AfterLoad() {
  502. t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
  503. if len(t.RequestContent) == 0 {
  504. return
  505. }
  506. t.RequestInfo = &HookRequest{}
  507. if err := json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
  508. log.Error("Unmarshal RequestContent[%d]: %v", t.ID, err)
  509. }
  510. if len(t.ResponseContent) > 0 {
  511. t.ResponseInfo = &HookResponse{}
  512. if err := json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
  513. log.Error("Unmarshal ResponseContent[%d]: %v", t.ID, err)
  514. }
  515. }
  516. }
  517. func (t *HookTask) simpleMarshalJSON(v interface{}) string {
  518. p, err := json.Marshal(v)
  519. if err != nil {
  520. log.Error("Marshal [%d]: %v", t.ID, err)
  521. }
  522. return string(p)
  523. }
  524. // HookTasks returns a list of hook tasks by given conditions.
  525. func HookTasks(hookID int64, page int) ([]*HookTask, error) {
  526. tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
  527. return tasks, x.
  528. Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).
  529. Where("hook_id=?", hookID).
  530. Desc("id").
  531. Find(&tasks)
  532. }
  533. // CreateHookTask creates a new hook task,
  534. // it handles conversion from Payload to PayloadContent.
  535. func CreateHookTask(t *HookTask) error {
  536. return createHookTask(x, t)
  537. }
  538. func createHookTask(e Engine, t *HookTask) error {
  539. data, err := t.Payloader.JSONPayload()
  540. if err != nil {
  541. return err
  542. }
  543. t.UUID = gouuid.NewV4().String()
  544. t.PayloadContent = string(data)
  545. _, err = e.Insert(t)
  546. return err
  547. }
  548. // UpdateHookTask updates information of hook task.
  549. func UpdateHookTask(t *HookTask) error {
  550. _, err := x.ID(t.ID).AllCols().Update(t)
  551. return err
  552. }
  553. // PrepareWebhook adds special webhook to task queue for given payload.
  554. func PrepareWebhook(w *Webhook, repo *Repository, event HookEventType, p api.Payloader) error {
  555. return prepareWebhook(x, w, repo, event, p)
  556. }
  557. func prepareWebhook(e Engine, w *Webhook, repo *Repository, event HookEventType, p api.Payloader) error {
  558. for _, e := range w.eventCheckers() {
  559. if event == e.typ {
  560. if !e.has() {
  561. return nil
  562. }
  563. }
  564. }
  565. var payloader api.Payloader
  566. var err error
  567. // Use separate objects so modifications won't be made on payload on non-Gogs/Gitea type hooks.
  568. switch w.HookTaskType {
  569. case SLACK:
  570. payloader, err = GetSlackPayload(p, event, w.Meta)
  571. if err != nil {
  572. return fmt.Errorf("GetSlackPayload: %v", err)
  573. }
  574. case DISCORD:
  575. payloader, err = GetDiscordPayload(p, event, w.Meta)
  576. if err != nil {
  577. return fmt.Errorf("GetDiscordPayload: %v", err)
  578. }
  579. case DINGTALK:
  580. payloader, err = GetDingtalkPayload(p, event, w.Meta)
  581. if err != nil {
  582. return fmt.Errorf("GetDingtalkPayload: %v", err)
  583. }
  584. case TELEGRAM:
  585. payloader, err = GetTelegramPayload(p, event, w.Meta)
  586. if err != nil {
  587. return fmt.Errorf("GetTelegramPayload: %v", err)
  588. }
  589. default:
  590. p.SetSecret(w.Secret)
  591. payloader = p
  592. }
  593. var signature string
  594. if len(w.Secret) > 0 {
  595. data, err := payloader.JSONPayload()
  596. if err != nil {
  597. log.Error("prepareWebhooks.JSONPayload: %v", err)
  598. }
  599. sig := hmac.New(sha256.New, []byte(w.Secret))
  600. sig.Write(data)
  601. signature = hex.EncodeToString(sig.Sum(nil))
  602. }
  603. if err = createHookTask(e, &HookTask{
  604. RepoID: repo.ID,
  605. HookID: w.ID,
  606. Type: w.HookTaskType,
  607. URL: w.URL,
  608. Signature: signature,
  609. Payloader: payloader,
  610. ContentType: w.ContentType,
  611. EventType: event,
  612. IsSSL: w.IsSSL,
  613. }); err != nil {
  614. return fmt.Errorf("CreateHookTask: %v", err)
  615. }
  616. return nil
  617. }
  618. // PrepareWebhooks adds new webhooks to task queue for given payload.
  619. func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) error {
  620. return prepareWebhooks(x, repo, event, p)
  621. }
  622. func prepareWebhooks(e Engine, repo *Repository, event HookEventType, p api.Payloader) error {
  623. ws, err := getActiveWebhooksByRepoID(e, repo.ID)
  624. if err != nil {
  625. return fmt.Errorf("GetActiveWebhooksByRepoID: %v", err)
  626. }
  627. // check if repo belongs to org and append additional webhooks
  628. if repo.mustOwner(e).IsOrganization() {
  629. // get hooks for org
  630. orgHooks, err := getActiveWebhooksByOrgID(e, repo.OwnerID)
  631. if err != nil {
  632. return fmt.Errorf("GetActiveWebhooksByOrgID: %v", err)
  633. }
  634. ws = append(ws, orgHooks...)
  635. }
  636. if len(ws) == 0 {
  637. return nil
  638. }
  639. for _, w := range ws {
  640. if err = prepareWebhook(e, w, repo, event, p); err != nil {
  641. return err
  642. }
  643. }
  644. return nil
  645. }
  646. func (t *HookTask) deliver() {
  647. t.IsDelivered = true
  648. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  649. req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
  650. Header("X-Gitea-Delivery", t.UUID).
  651. Header("X-Gitea-Event", string(t.EventType)).
  652. Header("X-Gitea-Signature", t.Signature).
  653. Header("X-Gogs-Delivery", t.UUID).
  654. Header("X-Gogs-Event", string(t.EventType)).
  655. Header("X-Gogs-Signature", t.Signature).
  656. HeaderWithSensitiveCase("X-GitHub-Delivery", t.UUID).
  657. HeaderWithSensitiveCase("X-GitHub-Event", string(t.EventType)).
  658. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
  659. switch t.ContentType {
  660. case ContentTypeJSON:
  661. req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
  662. case ContentTypeForm:
  663. req.Param("payload", t.PayloadContent)
  664. }
  665. // Record delivery information.
  666. t.RequestInfo = &HookRequest{
  667. Headers: map[string]string{},
  668. }
  669. for k, vals := range req.Headers() {
  670. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  671. }
  672. t.ResponseInfo = &HookResponse{
  673. Headers: map[string]string{},
  674. }
  675. defer func() {
  676. t.Delivered = time.Now().UnixNano()
  677. if t.IsSucceed {
  678. log.Trace("Hook delivered: %s", t.UUID)
  679. } else {
  680. log.Trace("Hook delivery failed: %s", t.UUID)
  681. }
  682. if err := UpdateHookTask(t); err != nil {
  683. log.Error("UpdateHookTask [%d]: %v", t.ID, err)
  684. }
  685. // Update webhook last delivery status.
  686. w, err := GetWebhookByID(t.HookID)
  687. if err != nil {
  688. log.Error("GetWebhookByID: %v", err)
  689. return
  690. }
  691. if t.IsSucceed {
  692. w.LastStatus = HookStatusSucceed
  693. } else {
  694. w.LastStatus = HookStatusFail
  695. }
  696. if err = UpdateWebhookLastStatus(w); err != nil {
  697. log.Error("UpdateWebhookLastStatus: %v", err)
  698. return
  699. }
  700. }()
  701. resp, err := req.Response()
  702. if err != nil {
  703. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  704. return
  705. }
  706. defer resp.Body.Close()
  707. // Status code is 20x can be seen as succeed.
  708. t.IsSucceed = resp.StatusCode/100 == 2
  709. t.ResponseInfo.Status = resp.StatusCode
  710. for k, vals := range resp.Header {
  711. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  712. }
  713. p, err := ioutil.ReadAll(resp.Body)
  714. if err != nil {
  715. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  716. return
  717. }
  718. t.ResponseInfo.Body = string(p)
  719. }
  720. // DeliverHooks checks and delivers undelivered hooks.
  721. // TODO: shoot more hooks at same time.
  722. func DeliverHooks() {
  723. tasks := make([]*HookTask, 0, 10)
  724. err := x.Where("is_delivered=?", false).Find(&tasks)
  725. if err != nil {
  726. log.Error("DeliverHooks: %v", err)
  727. return
  728. }
  729. // Update hook task status.
  730. for _, t := range tasks {
  731. t.deliver()
  732. }
  733. // Start listening on new hook requests.
  734. for repoIDStr := range HookQueue.Queue() {
  735. log.Trace("DeliverHooks [repo_id: %v]", repoIDStr)
  736. HookQueue.Remove(repoIDStr)
  737. repoID, err := com.StrTo(repoIDStr).Int64()
  738. if err != nil {
  739. log.Error("Invalid repo ID: %s", repoIDStr)
  740. continue
  741. }
  742. tasks = make([]*HookTask, 0, 5)
  743. if err := x.Where("repo_id=? AND is_delivered=?", repoID, false).Find(&tasks); err != nil {
  744. log.Error("Get repository [%d] hook tasks: %v", repoID, err)
  745. continue
  746. }
  747. for _, t := range tasks {
  748. t.deliver()
  749. }
  750. }
  751. }
  752. // InitDeliverHooks starts the hooks delivery thread
  753. func InitDeliverHooks() {
  754. go DeliverHooks()
  755. }