From 25a773a93f20f697dea9a3d94196478b2cebdc20 Mon Sep 17 00:00:00 2001 From: Christoph Maser Date: Thu, 2 Nov 2023 16:30:15 +0100 Subject: [PATCH] feat: add rocketchat notifier Signed-off-by: Christoph Maser Co-authored-by: George Robinson --- asset/assets_vfsdata.go | 4 +- config/config.go | 140 +++++---- config/config_test.go | 111 +++++++- config/notifiers.go | 80 ++++++ config/receiver/receiver.go | 4 + ...nf.rocketchat-both-token-and-tokenfile.yml | 20 ++ ...ocketchat-both-tokenid-and-tokenidfile.yml | 20 ++ .../conf.rocketchat-default-token-file.yml | 22 ++ .../conf.rocketchat-default-token.yml | 22 ++ config/testdata/conf.rocketchat-no-token.yml | 19 ++ docs/configuration.md | 69 ++++- notify/notify.go | 1 + notify/rocketchat/rocketchat.go | 269 ++++++++++++++++++ notify/rocketchat/rocketchat_test.go | 66 +++++ template/default.tmpl | 7 + 15 files changed, 791 insertions(+), 63 deletions(-) create mode 100644 config/testdata/conf.rocketchat-both-token-and-tokenfile.yml create mode 100644 config/testdata/conf.rocketchat-both-tokenid-and-tokenidfile.yml create mode 100644 config/testdata/conf.rocketchat-default-token-file.yml create mode 100644 config/testdata/conf.rocketchat-default-token.yml create mode 100644 config/testdata/conf.rocketchat-no-token.yml create mode 100644 notify/rocketchat/rocketchat.go create mode 100644 notify/rocketchat/rocketchat_test.go diff --git a/asset/assets_vfsdata.go b/asset/assets_vfsdata.go index 16ab608eb3..c7ce927ae1 100644 --- a/asset/assets_vfsdata.go +++ b/asset/assets_vfsdata.go @@ -163,9 +163,9 @@ var Assets = func() http.FileSystem { "/templates/default.tmpl": &vfsgen۰CompressedFileInfo{ name: "default.tmpl", modTime: time.Date(1970, 1, 1, 0, 0, 1, 0, time.UTC), - uncompressedSize: 7283, + uncompressedSize: 7680, - compressedContent: []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff\xec\x59\xcd\x6e\xeb\x36\x13\xdd\xfb\x29\x06\xba\xdf\x22\x5e\x44\xf7\x5b\x07\x08\x8a\x8b\xa2\x3f\x8b\xb4\x28\x1c\xa4\x9b\xa2\x10\x18\x69\xac\x30\xa1\x48\x85\x1c\xd9\x31\x1c\xbd\x7b\x41\x49\x96\x45\x49\xb6\x29\x5f\x77\x55\xef\x62\x7a\xe6\x9c\xe1\x39\xa3\x21\xe5\x6c\xb7\x90\xe0\x92\x4b\x84\x20\x8a\x98\x40\x4d\x19\x93\x2c\x45\x1d\x40\x59\x7e\xeb\x7c\xde\x6e\x01\x65\x02\x65\x39\x3b\x98\xf2\xb4\x78\xb0\x59\xdb\x2d\x84\x3f\x7d\x10\x6a\xc9\xc4\xd3\xe2\x01\xca\xf2\xeb\x97\xaf\x55\x9c\xf9\x41\x63\x8c\x7c\x85\xfa\xde\x06\x2d\x9a\x0f\xf0\x09\x85\x16\xef\x05\xea\x4d\x9d\xde\x10\xb9\x4c\xa6\x78\x7e\xc5\x98\x2c\xc3\x5f\x36\xfb\x91\x18\x15\x06\x3e\x81\xd4\x53\x9e\xa3\xae\x53\xf9\x12\xf0\xbd\xfd\x32\x58\x72\xcd\x65\x6a\x73\xee\x6c\x4e\xb5\x21\x13\xfe\x5c\xad\xc2\x27\x08\x94\x5d\xc6\xbf\xc1\x06\xfd\xa2\x55\x91\x3f\xb0\x67\x14\x26\x7c\x54\x9a\x30\xf9\x83\x71\x6d\xc2\x3f\x99\x28\xd0\x12\xbe\x2a\x2e\x21\x00\x8b\x0a\x35\x65\x4a\x70\x63\xb1\xc2\x1f\x55\x96\x29\x59\x27\xcf\x9b\xb5\x0e\xde\x1c\xca\xf2\x66\xbb\x85\x35\xa7\x17\x37\x38\x5c\x60\xa6\x56\xe8\xb2\xff\xce\x32\x34\x8d\xa2\x63\xec\x6d\xe1\xf3\xf6\xaf\x03\x36\x25\x68\x62\xcd\x73\xe2\x4a\x06\x47\x34\x26\xfc\xa0\xda\xd2\x48\x70\x43\x4d\xa8\x66\x32\x45\x08\xa1\x2c\xeb\xba\xee\x66\xfb\xc5\xa1\x4e\x56\x95\xdb\x4a\x48\x5b\xbe\xfd\x74\x0f\xed\x06\x9a\xc2\x6a\xf2\x6f\x52\x2a\x62\xb6\x26\x07\xb2\xb3\x7c\x1e\xee\xa3\x2a\x74\x8c\x77\xb5\x99\x28\x51\x33\x52\xba\xee\xc4\xd9\x88\x50\x47\x25\x88\x32\xa6\xdf\x12\xb5\x96\x03\x2d\x66\xbe\x62\x78\x56\x3d\x9b\x2e\x87\x2f\xb2\x97\x20\xb3\x71\x45\x8c\x60\xf1\x5b\x98\xe0\x92\x15\x82\x42\xe2\x24\xb0\x91\x82\x30\xcb\x05\x23\xf7\xe1\x0c\x0f\xf5\xa0\x8b\x53\x18\x3b\x1e\xb2\x31\x28\x77\x08\x79\xe2\x2d\x99\x10\xcf\x2c\x7e\x1b\xe0\x8d\x96\x6f\x41\xe1\x13\x4e\x05\x0a\x2e\xdf\xbc\x2b\x88\x9b\x0a\x78\x12\xf8\x25\xe4\x1a\x6d\xaf\x79\x46\x77\x0a\x3a\xaa\x58\x35\x83\x3d\x4b\xe6\xb1\x92\x98\xa9\x57\x1e\xf8\xc7\x17\x5a\xf8\x56\xec\xbf\xb9\xa5\x52\x54\x9f\x38\x9d\x1e\xec\x86\xe7\x76\x6b\x49\x41\x9b\x36\x65\x38\xd0\xa6\xb5\xe3\x10\x31\x16\x1c\x25\x9d\xdf\x90\x87\x10\xf7\xa7\xe2\x79\x9e\x0d\x71\xb9\x34\xc4\x64\x8c\x66\x04\x77\x30\xc1\xc3\xc3\xaa\xaa\xdc\xa4\x28\x39\xb6\xc0\x19\x1a\xc3\xd2\xf3\x9e\xef\x01\xd8\xd0\xa1\xe6\xc0\x3b\x30\xd0\x46\x4f\xb8\x59\xef\x7c\x75\x0e\xf0\x39\xfc\x1f\x6e\xed\xe0\xac\x16\xa1\x5e\xac\x46\xe7\x71\x45\xdc\x5b\x40\x45\x72\xdb\xd9\xd1\x08\xdf\x02\x8d\x12\x2b\x4c\x7a\x8c\xbb\x65\x7f\xce\x5d\xc6\x80\xf5\xd6\x47\x52\x53\xcd\xf1\xe9\xdd\xe4\xb8\xbe\xc6\xf8\x85\xd1\x54\xcf\x67\x57\xff\x8e\xf8\xd7\xbd\x28\x3f\x69\x31\xc0\x1b\xf5\xe7\x80\xeb\x3d\x7f\x48\x45\xf6\xb0\x3c\x38\x49\x87\xe1\x39\xd3\xb4\x99\x10\x4f\x2c\xf5\x8d\x66\x29\x4a\x8a\xfa\x47\x9c\xdb\x5f\x2b\x1e\x93\xd2\x2a\x37\xfb\xb6\x25\x46\x18\xb9\x8d\x76\xed\xa5\x69\xb3\x60\xa8\x2a\x4a\xe2\xb4\x89\x12\x6e\x72\xc1\x36\xd1\x81\xdb\xd4\xe9\xc1\x3d\x44\xce\x94\xe4\xa4\xac\x20\x11\x29\x25\x26\x1e\x89\xce\xd9\x55\x98\x17\xb5\x42\x7d\x81\xfb\xe3\x00\xea\xdf\xef\xa7\xcb\xb4\x93\x7f\x37\x5d\xae\x99\x86\x57\xfa\x63\x4a\xee\xef\x74\x53\xce\x94\xee\x6d\x4e\x76\x1e\xf6\xfd\x6b\xfa\xf4\x77\x84\x0e\xce\xd5\xde\x29\xf6\x76\x55\x24\x14\x98\x6a\x96\x8d\x49\xf9\x9f\x15\x25\xe1\x26\x56\x3a\xb9\xc0\x20\xea\x23\x5d\xd5\xb5\xd7\x84\x67\xfc\xb8\x3e\xba\xdf\xad\x63\x66\x08\x59\xd6\x1d\xa6\x59\xc6\xf4\xe6\xac\x3e\xed\x63\x9d\xdf\xf1\x03\xa4\xe6\xcd\xde\xc7\xa6\x2f\x30\xc9\xa8\xce\xcf\x6d\xdf\xed\x58\x4b\xed\xeb\xd9\x08\xf9\x14\xf3\x5e\xb9\x66\x17\x71\xce\x01\xea\xbd\x46\x5f\x35\x9f\x55\x37\xe4\x51\xad\x72\xcd\x95\xe6\xf6\xe5\xe7\xb6\xb9\x48\xff\x6f\xb7\x04\x77\xf7\x10\x04\xbb\xfb\xf5\xee\xa7\x55\x67\xb7\x36\x07\x00\xa0\xca\x33\xb8\xc2\x5d\x1e\x97\x09\x7e\xec\x7e\xdd\x85\x60\xf7\x55\xe0\x64\xf0\x25\xdc\xe0\x7b\x27\x31\x88\x35\x27\x1e\x33\x11\xcc\xdb\xc0\x16\xbe\x2d\xeb\x1e\x82\x5f\x79\xfa\xe2\x62\xa1\x30\x58\x01\x32\x99\xf4\x51\xd7\x4c\x4b\x2e\xd3\x60\x0e\x37\x12\x3b\x40\x35\xcc\xfc\x04\xd7\x6f\x98\xf0\x22\xf3\x67\xe3\x72\xa9\x2c\x95\x5d\xdd\x53\x9d\xa4\x79\x50\xeb\x1e\x87\x4c\x5a\x4f\xba\x7f\xd7\xff\xae\xe9\x42\x3b\x69\xae\x4f\x6d\x63\x0c\xb8\x27\xb9\x35\xd9\x31\x0f\xd7\x2e\xee\x9c\x97\x7b\x97\x73\xf0\xb4\x8b\x7d\x27\x4f\x39\xbb\x47\xea\x7f\xfb\x4f\x00\x00\x00\xff\xff\x30\xb3\x3d\xcd\x73\x1c\x00\x00"), + compressedContent: []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff\xec\x59\xcf\x6f\xeb\x36\x0c\xbe\xe7\xaf\x20\xfc\x76\x68\x0e\xf5\xdb\xb9\x40\x31\x3c\x0c\xfb\x71\xe8\x86\xa1\x45\x77\x19\x86\x40\xb5\x19\x57\xad\x2c\xb9\x12\x9d\x34\x48\xf3\xbf\x0f\xb2\x1d\x47\xb2\x9d\x44\x4e\xb3\xd3\xcb\xad\x91\xc9\x8f\xd4\xf7\xd1\xa4\xac\xae\xd7\x90\xe2\x9c\x4b\x84\x68\x36\x63\x02\x35\xe5\x4c\xb2\x0c\x75\x04\x9b\xcd\x37\xe7\xf7\x7a\x0d\x28\x53\xd8\x6c\x26\x7b\x5d\x1e\xef\xef\xac\xd7\x7a\x0d\xf1\x2f\xef\x84\x5a\x32\xf1\x78\x7f\x07\x9b\xcd\xd7\x2f\x5f\x2b\x3b\xf3\x93\xc6\x04\xf9\x02\xf5\xad\x35\xba\x6f\x7e\xc0\x07\x94\x5a\xbc\x95\xa8\x57\xb5\x7b\x13\xc8\x8f\x64\xca\xa7\x17\x4c\xc8\x46\xf8\xc7\x7a\x3f\x10\xa3\xd2\xc0\x07\x90\x7a\x2c\x0a\xd4\xb5\x2b\x9f\x03\xbe\xb5\x0f\xa3\x39\xd7\x5c\x66\xd6\xe7\xc6\xfa\x54\x1b\x32\xf1\xaf\xd5\x2a\x7c\x80\x40\xe9\x46\xfc\x17\xac\xd1\x6f\x5a\x95\xc5\x1d\x7b\x42\x61\xe2\x07\xa5\x09\xd3\xbf\x18\xd7\x26\xfe\x9b\x89\x12\x6d\xc0\x17\xc5\x25\x44\x60\x51\xa1\x0e\x99\x11\x5c\x59\xac\xf8\x67\x95\xe7\x4a\xd6\xce\xd3\x66\xcd\xc1\x9b\xc2\x66\x73\xb5\x5e\xc3\x92\xd3\xb3\x6f\x1c\xdf\x63\xae\x16\xe8\x47\xff\x93\xe5\x68\x1a\x46\x87\xa2\xb7\x89\x4f\xdb\xbf\xf6\xc8\x94\xa2\x49\x34\x2f\x88\x2b\x19\x1d\xe0\x98\xf0\x9d\x6a\x49\x67\x82\x1b\x6a\x4c\x35\x93\x19\x42\x0c\x9b\x4d\x9d\xd7\xcd\x64\xb7\xd8\xe7\xc9\xb2\x72\x5d\x11\x69\xd3\xb7\xbf\x6e\xa1\xdd\x40\x93\x58\x1d\xfc\x9b\x94\x8a\x98\xcd\xc9\x83\x74\x96\x4f\xc3\x7d\x50\xa5\x4e\xf0\xa6\x16\x13\x25\x6a\x46\x4a\xd7\x95\x38\x19\x20\xea\x20\x05\xb3\x9c\xe9\xd7\x54\x2d\x65\x8f\x8b\x49\x28\x19\x81\x59\x4f\xc6\xd3\x11\x8a\x1c\x44\xc8\x64\x98\x11\x23\x58\xf2\x1a\xa7\x38\x67\xa5\xa0\x98\x38\x09\x6c\xa8\x20\xcc\x0b\xc1\xc8\x7f\x39\xe3\x7d\x35\xe8\xe3\x94\xc6\xb6\x87\x7c\x08\xca\x6f\x42\x81\x78\x73\x26\xc4\x13\x4b\x5e\x7b\x78\x83\xe9\x5b\x50\xf8\x80\x63\x86\x82\xcb\xd7\xe0\x0c\x92\x26\x03\x9e\x46\x61\x0e\x85\x46\x5b\x6b\x81\xd6\x4e\x42\x07\x19\xab\x7a\x70\x60\xca\x3c\x51\x12\x73\xf5\xc2\xa3\x70\xfb\x52\x8b\xd0\x8c\xc3\x37\x37\x57\x8a\xea\x89\xe3\xd4\xa0\x6b\x5e\xd8\xad\xa5\x25\xad\x5a\x97\x7e\x43\x1b\x57\x8e\x7d\xc4\x44\x70\x94\x74\x7a\x41\xee\x43\xdc\x4d\xc5\xd3\x34\xeb\xe3\x72\x69\x88\xc9\x04\xcd\x00\x6e\xaf\x83\xc7\xfb\x59\x55\x85\xc9\x50\x72\x6c\x81\x73\x34\x86\x65\xa7\xbd\xdf\x3d\xb0\xbe\x42\xcd\xc0\xdb\xd3\xd0\x06\x27\xdc\xa4\x33\x5f\xbd\x01\x3e\x85\x1f\xe1\xda\x36\xce\x6a\x11\xea\xc5\xaa\x75\x1e\x66\xc4\x3f\x05\x54\x41\xae\x9d\x1d\x0d\xc4\xbb\x47\xa3\xc4\x02\xd3\x4e\xc4\xed\x72\x78\xcc\xad\x47\x2f\xea\x75\x08\xa5\xa6\xea\xe3\xe3\xab\xc9\x53\x7d\x89\xc9\x33\xa3\xb1\x9a\x4f\x2e\xfa\x1d\xd0\xcf\x3d\x28\x3f\x6a\xd1\xc3\x1b\xd4\x67\x8f\xea\x1d\x7d\x48\xcd\xec\xb0\xdc\xdb\x49\xfb\xe6\x05\xd3\xb4\x1a\x61\x4f\x2c\x0b\xb5\x66\x19\x4a\x9a\x75\x47\x9c\x5f\x5f\x0b\x9e\x90\xd2\xaa\x30\xbb\xb2\x25\x46\x38\xf3\x0b\xed\x52\x4b\xe3\x7a\x41\x9f\x55\x94\xc4\x69\x35\x4b\xb9\x29\x04\x5b\xcd\xf6\x9c\xa6\x8e\x37\xee\x3e\x72\xae\x24\x27\x65\x09\x99\x91\x52\x62\xe4\x48\xf4\x66\x57\x69\x9e\xd5\x02\xf5\x19\xce\x8f\x3d\xa8\xff\xbf\x9e\xce\x53\x4e\xe1\xd5\x74\xbe\x62\xea\x1f\xe9\x0f\x31\xb9\x3b\xd3\x8d\x99\x29\xee\x69\x4e\x3a\x2f\xfb\xee\x33\x7d\xfc\x37\x82\x83\x73\x91\x77\x8c\xbc\x2e\x8b\x84\x02\x33\xcd\xf2\x21\x2a\xbf\x5b\x52\x52\x6e\x12\xa5\xd3\x33\x34\xa2\x2e\xd2\x85\x5d\x7b\x4c\x78\xc2\xf7\xcb\xab\xfb\x69\x1e\x73\x43\xc8\x72\xb7\x99\xe6\x39\xd3\xab\x93\xea\xb4\x8b\x75\x7a\xc5\xf7\x90\x9a\x2f\xfb\x10\x99\xbe\xc0\x28\xa1\x9c\xeb\xb6\x4f\x2b\xd6\x86\x0e\xd5\x6c\x20\xf8\x18\xf1\x5e\xb8\x66\x67\x51\xce\x03\xea\x7c\x46\x5f\x38\x9f\x54\x27\xe4\x41\xae\x0a\xcd\x95\xe6\xf6\xe3\xe7\xba\x39\x48\xff\xb0\x5d\x82\x9b\x5b\x88\xa2\xed\xf9\x7a\x7b\xb5\xea\xed\xd6\xfa\x00\x00\x54\x7e\x06\x17\xb8\xf5\xe3\x32\xc5\xf7\xed\xed\x2e\x44\xdb\x47\x91\xe7\xc1\xe7\x70\x85\x6f\x8e\x63\x94\x68\x4e\x3c\x61\x22\x9a\xb6\x86\x2d\x7c\x9b\xd6\x2d\x44\xbf\xf3\xec\xd9\xc7\x42\x61\xb0\x02\x64\x32\xed\xa2\x2e\x99\x96\x5c\x66\xd1\x14\xae\x24\x3a\x40\x35\xcc\xf4\x48\xac\x3f\x30\xe5\x65\x1e\x1e\x8d\xcb\xb9\xb2\xa1\xec\xea\x2e\xd4\xd1\x30\x77\x6a\xd9\x89\x21\xd3\x56\x13\xf7\xef\xfa\xdf\x35\x2e\xb4\xe7\xe6\xeb\xd4\x16\x46\x2f\xf6\x28\xb5\x46\x2b\x16\xa0\xda\xd9\x95\x0b\x52\xef\x7c\x0a\x1e\x57\xb1\xab\xe4\x31\x65\x77\x48\xdd\xa7\x6e\xab\xd3\x2a\x79\x45\xf2\x6f\x24\x4e\x9e\x53\x03\x60\x4c\x70\x66\x4e\xbf\xd3\xdd\x97\xde\xa7\x2f\xe2\x07\x80\x0f\xdf\xc4\x0f\x38\x1c\xbb\x8e\x1f\x4a\xbe\x77\x27\xff\x5f\x00\x00\x00\xff\xff\xab\xbc\x36\x42\x00\x1e\x00\x00"), }, "/templates/email.tmpl": &vfsgen۰CompressedFileInfo{ name: "email.tmpl", diff --git a/config/config.go b/config/config.go index 4d694eefcc..305b2fd160 100644 --- a/config/config.go +++ b/config/config.go @@ -266,6 +266,9 @@ func resolveFilepaths(baseDir string, cfg *Config) { for _, cfg := range receiver.JiraConfigs { cfg.HTTPConfig.SetDirectory(baseDir) } + for _, cfg := range receiver.RocketchatConfigs { + cfg.HTTPConfig.SetDirectory(baseDir) + } } } @@ -361,6 +364,14 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { return fmt.Errorf("at most one of smtp_auth_password & smtp_auth_password_file must be configured") } + if c.Global.RocketchatToken != nil && len(c.Global.RocketchatTokenFile) > 0 { + return errors.New("at most one of rocketchat_token & rocketchat_token_file must be configured") + } + + if c.Global.RocketchatTokenID != nil && len(c.Global.RocketchatTokenIDFile) > 0 { + return errors.New("at most one of rocketchat_token_id & rocketchat_token_id_file must be configured") + } + names := map[string]struct{}{} for _, rcv := range c.Receivers { @@ -562,6 +573,28 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { jira.APIURL = c.Global.JiraAPIURL } } + for _, rocketchat := range rcv.RocketchatConfigs { + if rocketchat.HTTPConfig == nil { + rocketchat.HTTPConfig = c.Global.HTTPConfig + } + if rocketchat.APIURL == nil { + rocketchat.APIURL = c.Global.RocketchatAPIURL + } + if rocketchat.TokenID == nil && len(rocketchat.TokenIDFile) == 0 { + if c.Global.RocketchatTokenID == nil && len(c.Global.RocketchatTokenIDFile) == 0 { + return errors.New("no global Rocketchat TokenID set either inline or in a file") + } + rocketchat.TokenID = c.Global.RocketchatTokenID + rocketchat.TokenIDFile = c.Global.RocketchatTokenIDFile + } + if rocketchat.Token == nil && len(rocketchat.TokenFile) == 0 { + if c.Global.RocketchatToken == nil && len(c.Global.RocketchatTokenFile) == 0 { + return errors.New("no global Rocketchat Token set either inline or in a file") + } + rocketchat.Token = c.Global.RocketchatToken + rocketchat.TokenFile = c.Global.RocketchatTokenFile + } + } names[rcv.Name] = struct{}{} } @@ -654,17 +687,18 @@ func DefaultGlobalConfig() GlobalConfig { defaultSMTPTLSConfig := commoncfg.TLSConfig{} return GlobalConfig{ - ResolveTimeout: model.Duration(5 * time.Minute), - HTTPConfig: &defaultHTTPConfig, - SMTPHello: "localhost", - SMTPRequireTLS: true, - SMTPTLSConfig: &defaultSMTPTLSConfig, - PagerdutyURL: mustParseURL("https://events.pagerduty.com/v2/enqueue"), - OpsGenieAPIURL: mustParseURL("https://api.opsgenie.com/"), - WeChatAPIURL: mustParseURL("https://qyapi.weixin.qq.com/cgi-bin/"), - VictorOpsAPIURL: mustParseURL("https://alert.victorops.com/integrations/generic/20131114/alert/"), - TelegramAPIUrl: mustParseURL("https://api.telegram.org"), - WebexAPIURL: mustParseURL("https://webexapis.com/v1/messages"), + ResolveTimeout: model.Duration(5 * time.Minute), + HTTPConfig: &defaultHTTPConfig, + SMTPHello: "localhost", + SMTPRequireTLS: true, + SMTPTLSConfig: &defaultSMTPTLSConfig, + PagerdutyURL: mustParseURL("https://events.pagerduty.com/v2/enqueue"), + OpsGenieAPIURL: mustParseURL("https://api.opsgenie.com/"), + WeChatAPIURL: mustParseURL("https://qyapi.weixin.qq.com/cgi-bin/"), + VictorOpsAPIURL: mustParseURL("https://alert.victorops.com/integrations/generic/20131114/alert/"), + TelegramAPIUrl: mustParseURL("https://api.telegram.org"), + WebexAPIURL: mustParseURL("https://webexapis.com/v1/messages"), + RocketchatAPIURL: mustParseURL("https://open.rocket.chat/"), } } @@ -766,31 +800,36 @@ type GlobalConfig struct { HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - JiraAPIURL *URL `yaml:"jira_api_url,omitempty" json:"jira_api_url,omitempty"` - SMTPFrom string `yaml:"smtp_from,omitempty" json:"smtp_from,omitempty"` - SMTPHello string `yaml:"smtp_hello,omitempty" json:"smtp_hello,omitempty"` - SMTPSmarthost HostPort `yaml:"smtp_smarthost,omitempty" json:"smtp_smarthost,omitempty"` - SMTPAuthUsername string `yaml:"smtp_auth_username,omitempty" json:"smtp_auth_username,omitempty"` - SMTPAuthPassword Secret `yaml:"smtp_auth_password,omitempty" json:"smtp_auth_password,omitempty"` - SMTPAuthPasswordFile string `yaml:"smtp_auth_password_file,omitempty" json:"smtp_auth_password_file,omitempty"` - SMTPAuthSecret Secret `yaml:"smtp_auth_secret,omitempty" json:"smtp_auth_secret,omitempty"` - SMTPAuthIdentity string `yaml:"smtp_auth_identity,omitempty" json:"smtp_auth_identity,omitempty"` - SMTPRequireTLS bool `yaml:"smtp_require_tls" json:"smtp_require_tls,omitempty"` - SMTPTLSConfig *commoncfg.TLSConfig `yaml:"smtp_tls_config,omitempty" json:"smtp_tls_config,omitempty"` - SlackAPIURL *SecretURL `yaml:"slack_api_url,omitempty" json:"slack_api_url,omitempty"` - SlackAPIURLFile string `yaml:"slack_api_url_file,omitempty" json:"slack_api_url_file,omitempty"` - PagerdutyURL *URL `yaml:"pagerduty_url,omitempty" json:"pagerduty_url,omitempty"` - OpsGenieAPIURL *URL `yaml:"opsgenie_api_url,omitempty" json:"opsgenie_api_url,omitempty"` - OpsGenieAPIKey Secret `yaml:"opsgenie_api_key,omitempty" json:"opsgenie_api_key,omitempty"` - OpsGenieAPIKeyFile string `yaml:"opsgenie_api_key_file,omitempty" json:"opsgenie_api_key_file,omitempty"` - WeChatAPIURL *URL `yaml:"wechat_api_url,omitempty" json:"wechat_api_url,omitempty"` - WeChatAPISecret Secret `yaml:"wechat_api_secret,omitempty" json:"wechat_api_secret,omitempty"` - WeChatAPICorpID string `yaml:"wechat_api_corp_id,omitempty" json:"wechat_api_corp_id,omitempty"` - VictorOpsAPIURL *URL `yaml:"victorops_api_url,omitempty" json:"victorops_api_url,omitempty"` - VictorOpsAPIKey Secret `yaml:"victorops_api_key,omitempty" json:"victorops_api_key,omitempty"` - VictorOpsAPIKeyFile string `yaml:"victorops_api_key_file,omitempty" json:"victorops_api_key_file,omitempty"` - TelegramAPIUrl *URL `yaml:"telegram_api_url,omitempty" json:"telegram_api_url,omitempty"` - WebexAPIURL *URL `yaml:"webex_api_url,omitempty" json:"webex_api_url,omitempty"` + JiraAPIURL *URL `yaml:"jira_api_url,omitempty" json:"jira_api_url,omitempty"` + SMTPFrom string `yaml:"smtp_from,omitempty" json:"smtp_from,omitempty"` + SMTPHello string `yaml:"smtp_hello,omitempty" json:"smtp_hello,omitempty"` + SMTPSmarthost HostPort `yaml:"smtp_smarthost,omitempty" json:"smtp_smarthost,omitempty"` + SMTPAuthUsername string `yaml:"smtp_auth_username,omitempty" json:"smtp_auth_username,omitempty"` + SMTPAuthPassword Secret `yaml:"smtp_auth_password,omitempty" json:"smtp_auth_password,omitempty"` + SMTPAuthPasswordFile string `yaml:"smtp_auth_password_file,omitempty" json:"smtp_auth_password_file,omitempty"` + SMTPAuthSecret Secret `yaml:"smtp_auth_secret,omitempty" json:"smtp_auth_secret,omitempty"` + SMTPAuthIdentity string `yaml:"smtp_auth_identity,omitempty" json:"smtp_auth_identity,omitempty"` + SMTPRequireTLS bool `yaml:"smtp_require_tls" json:"smtp_require_tls,omitempty"` + SMTPTLSConfig *commoncfg.TLSConfig `yaml:"smtp_tls_config,omitempty" json:"smtp_tls_config,omitempty"` + SlackAPIURL *SecretURL `yaml:"slack_api_url,omitempty" json:"slack_api_url,omitempty"` + SlackAPIURLFile string `yaml:"slack_api_url_file,omitempty" json:"slack_api_url_file,omitempty"` + PagerdutyURL *URL `yaml:"pagerduty_url,omitempty" json:"pagerduty_url,omitempty"` + OpsGenieAPIURL *URL `yaml:"opsgenie_api_url,omitempty" json:"opsgenie_api_url,omitempty"` + OpsGenieAPIKey Secret `yaml:"opsgenie_api_key,omitempty" json:"opsgenie_api_key,omitempty"` + OpsGenieAPIKeyFile string `yaml:"opsgenie_api_key_file,omitempty" json:"opsgenie_api_key_file,omitempty"` + WeChatAPIURL *URL `yaml:"wechat_api_url,omitempty" json:"wechat_api_url,omitempty"` + WeChatAPISecret Secret `yaml:"wechat_api_secret,omitempty" json:"wechat_api_secret,omitempty"` + WeChatAPICorpID string `yaml:"wechat_api_corp_id,omitempty" json:"wechat_api_corp_id,omitempty"` + VictorOpsAPIURL *URL `yaml:"victorops_api_url,omitempty" json:"victorops_api_url,omitempty"` + VictorOpsAPIKey Secret `yaml:"victorops_api_key,omitempty" json:"victorops_api_key,omitempty"` + VictorOpsAPIKeyFile string `yaml:"victorops_api_key_file,omitempty" json:"victorops_api_key_file,omitempty"` + TelegramAPIUrl *URL `yaml:"telegram_api_url,omitempty" json:"telegram_api_url,omitempty"` + WebexAPIURL *URL `yaml:"webex_api_url,omitempty" json:"webex_api_url,omitempty"` + RocketchatAPIURL *URL `yaml:"rocketchat_api_url,omitempty" json:"rocketchat_api_url,omitempty"` + RocketchatToken *Secret `yaml:"rocketchat_token,omitempty" json:"rocketchat_token,omitempty"` + RocketchatTokenFile string `yaml:"rocketchat_token_file,omitempty" json:"rocketchat_token_file,omitempty"` + RocketchatTokenID *Secret `yaml:"rocketchat_token_id,omitempty" json:"rocketchat_token_id,omitempty"` + RocketchatTokenIDFile string `yaml:"rocketchat_token_id_file,omitempty" json:"rocketchat_token_id_file,omitempty"` } // UnmarshalYAML implements the yaml.Unmarshaler interface for GlobalConfig. @@ -922,20 +961,21 @@ type Receiver struct { // A unique identifier for this receiver. Name string `yaml:"name" json:"name"` - DiscordConfigs []*DiscordConfig `yaml:"discord_configs,omitempty" json:"discord_configs,omitempty"` - EmailConfigs []*EmailConfig `yaml:"email_configs,omitempty" json:"email_configs,omitempty"` - PagerdutyConfigs []*PagerdutyConfig `yaml:"pagerduty_configs,omitempty" json:"pagerduty_configs,omitempty"` - SlackConfigs []*SlackConfig `yaml:"slack_configs,omitempty" json:"slack_configs,omitempty"` - WebhookConfigs []*WebhookConfig `yaml:"webhook_configs,omitempty" json:"webhook_configs,omitempty"` - OpsGenieConfigs []*OpsGenieConfig `yaml:"opsgenie_configs,omitempty" json:"opsgenie_configs,omitempty"` - WechatConfigs []*WechatConfig `yaml:"wechat_configs,omitempty" json:"wechat_configs,omitempty"` - PushoverConfigs []*PushoverConfig `yaml:"pushover_configs,omitempty" json:"pushover_configs,omitempty"` - VictorOpsConfigs []*VictorOpsConfig `yaml:"victorops_configs,omitempty" json:"victorops_configs,omitempty"` - SNSConfigs []*SNSConfig `yaml:"sns_configs,omitempty" json:"sns_configs,omitempty"` - TelegramConfigs []*TelegramConfig `yaml:"telegram_configs,omitempty" json:"telegram_configs,omitempty"` - WebexConfigs []*WebexConfig `yaml:"webex_configs,omitempty" json:"webex_configs,omitempty"` - MSTeamsConfigs []*MSTeamsConfig `yaml:"msteams_configs,omitempty" json:"msteams_configs,omitempty"` - JiraConfigs []*JiraConfig `yaml:"jira_configs,omitempty" json:"jira_configs,omitempty"` + DiscordConfigs []*DiscordConfig `yaml:"discord_configs,omitempty" json:"discord_configs,omitempty"` + EmailConfigs []*EmailConfig `yaml:"email_configs,omitempty" json:"email_configs,omitempty"` + PagerdutyConfigs []*PagerdutyConfig `yaml:"pagerduty_configs,omitempty" json:"pagerduty_configs,omitempty"` + SlackConfigs []*SlackConfig `yaml:"slack_configs,omitempty" json:"slack_configs,omitempty"` + WebhookConfigs []*WebhookConfig `yaml:"webhook_configs,omitempty" json:"webhook_configs,omitempty"` + OpsGenieConfigs []*OpsGenieConfig `yaml:"opsgenie_configs,omitempty" json:"opsgenie_configs,omitempty"` + WechatConfigs []*WechatConfig `yaml:"wechat_configs,omitempty" json:"wechat_configs,omitempty"` + PushoverConfigs []*PushoverConfig `yaml:"pushover_configs,omitempty" json:"pushover_configs,omitempty"` + VictorOpsConfigs []*VictorOpsConfig `yaml:"victorops_configs,omitempty" json:"victorops_configs,omitempty"` + SNSConfigs []*SNSConfig `yaml:"sns_configs,omitempty" json:"sns_configs,omitempty"` + TelegramConfigs []*TelegramConfig `yaml:"telegram_configs,omitempty" json:"telegram_configs,omitempty"` + WebexConfigs []*WebexConfig `yaml:"webex_configs,omitempty" json:"webex_configs,omitempty"` + MSTeamsConfigs []*MSTeamsConfig `yaml:"msteams_configs,omitempty" json:"msteams_configs,omitempty"` + JiraConfigs []*JiraConfig `yaml:"jira_configs,omitempty" json:"jira_configs,omitempty"` + RocketchatConfigs []*RocketchatConfig `yaml:"rocketchat_configs,omitempty" json:"rocketchat_configs,omitempty"` } // UnmarshalYAML implements the yaml.Unmarshaler interface for Receiver. diff --git a/config/config_test.go b/config/config_test.go index fa21bb498a..15edfeed2d 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -872,14 +872,15 @@ func TestEmptyFieldsAndRegex(t *testing.T) { SMTPTLSConfig: &commoncfg.TLSConfig{ InsecureSkipVerify: false, }, - SlackAPIURL: (*SecretURL)(mustParseURL("http://slack.example.com/")), - SMTPRequireTLS: true, - PagerdutyURL: mustParseURL("https://events.pagerduty.com/v2/enqueue"), - OpsGenieAPIURL: mustParseURL("https://api.opsgenie.com/"), - WeChatAPIURL: mustParseURL("https://qyapi.weixin.qq.com/cgi-bin/"), - VictorOpsAPIURL: mustParseURL("https://alert.victorops.com/integrations/generic/20131114/alert/"), - TelegramAPIUrl: mustParseURL("https://api.telegram.org"), - WebexAPIURL: mustParseURL("https://webexapis.com/v1/messages"), + SlackAPIURL: (*SecretURL)(mustParseURL("http://slack.example.com/")), + SMTPRequireTLS: true, + PagerdutyURL: mustParseURL("https://events.pagerduty.com/v2/enqueue"), + OpsGenieAPIURL: mustParseURL("https://api.opsgenie.com/"), + WeChatAPIURL: mustParseURL("https://qyapi.weixin.qq.com/cgi-bin/"), + VictorOpsAPIURL: mustParseURL("https://alert.victorops.com/integrations/generic/20131114/alert/"), + TelegramAPIUrl: mustParseURL("https://api.telegram.org"), + WebexAPIURL: mustParseURL("https://webexapis.com/v1/messages"), + RocketchatAPIURL: mustParseURL("https://open.rocket.chat/"), }, Templates: []string{ @@ -1203,6 +1204,100 @@ func TestInvalidSNSConfig(t *testing.T) { } } +func TestRocketchatDefaultToken(t *testing.T) { + conf, err := LoadFile("testdata/conf.rocketchat-default-token.yml") + if err != nil { + t.Fatalf("Error parsing %s: %s", "testdata/conf.rocketchat-default-token.yml", err) + } + + defaultToken := conf.Global.RocketchatToken + overrideToken := Secret("token456") + if defaultToken != conf.Receivers[0].RocketchatConfigs[0].Token { + t.Fatalf("Invalid rocketchat key: %s\nExpected: %s", string(*conf.Receivers[0].RocketchatConfigs[0].Token), string(*defaultToken)) + } + if overrideToken != *conf.Receivers[1].RocketchatConfigs[0].Token { + t.Errorf("Invalid rocketchat key: %s\nExpected: %s", string(*conf.Receivers[0].RocketchatConfigs[0].Token), string(overrideToken)) + } +} + +func TestRocketchatDefaultTokenID(t *testing.T) { + conf, err := LoadFile("testdata/conf.rocketchat-default-token.yml") + if err != nil { + t.Fatalf("Error parsing %s: %s", "testdata/conf.rocketchat-default-token.yml", err) + } + + defaultTokenID := conf.Global.RocketchatTokenID + overrideTokenID := Secret("id456") + if defaultTokenID != conf.Receivers[0].RocketchatConfigs[0].TokenID { + t.Fatalf("Invalid rocketchat key: %s\nExpected: %s", string(*conf.Receivers[0].RocketchatConfigs[0].TokenID), string(*defaultTokenID)) + } + if overrideTokenID != *conf.Receivers[1].RocketchatConfigs[0].TokenID { + t.Errorf("Invalid rocketchat key: %s\nExpected: %s", string(*conf.Receivers[0].RocketchatConfigs[0].TokenID), string(overrideTokenID)) + } +} + +func TestRocketchatDefaultTokenFile(t *testing.T) { + conf, err := LoadFile("testdata/conf.rocketchat-default-token-file.yml") + if err != nil { + t.Fatalf("Error parsing %s: %s", "testdata/conf.rocketchat-default-token-file.yml", err) + } + + defaultTokenFile := conf.Global.RocketchatTokenFile + overrideTokenFile := "/override_file" + if defaultTokenFile != conf.Receivers[0].RocketchatConfigs[0].TokenFile { + t.Fatalf("Invalid Rocketchat key_file: %s\nExpected: %s", conf.Receivers[0].RocketchatConfigs[0].TokenFile, defaultTokenFile) + } + if overrideTokenFile != conf.Receivers[1].RocketchatConfigs[0].TokenFile { + t.Errorf("Invalid Rocketchat key_file: %s\nExpected: %s", conf.Receivers[0].RocketchatConfigs[0].TokenFile, overrideTokenFile) + } +} + +func TestRocketchatDefaultIDTokenFile(t *testing.T) { + conf, err := LoadFile("testdata/conf.rocketchat-default-token-file.yml") + if err != nil { + t.Fatalf("Error parsing %s: %s", "testdata/conf.rocketchat-default-token-file.yml", err) + } + + defaultTokenIDFile := conf.Global.RocketchatTokenIDFile + overrideTokenIDFile := "/override_file" + if defaultTokenIDFile != conf.Receivers[0].RocketchatConfigs[0].TokenIDFile { + t.Fatalf("Invalid Rocketchat key_file: %s\nExpected: %s", conf.Receivers[0].RocketchatConfigs[0].TokenIDFile, defaultTokenIDFile) + } + if overrideTokenIDFile != conf.Receivers[1].RocketchatConfigs[0].TokenIDFile { + t.Errorf("Invalid Rocketchat key_file: %s\nExpected: %s", conf.Receivers[0].RocketchatConfigs[0].TokenIDFile, overrideTokenIDFile) + } +} + +func TestRocketchatBothTokenAndTokenFile(t *testing.T) { + _, err := LoadFile("testdata/conf.rocketchat-both-token-and-tokenfile.yml") + if err == nil { + t.Fatalf("Expected an error parsing %s: %s", "testdata/conf.rocketchat-both-token-and-tokenfile.yml", err) + } + if err.Error() != "at most one of rocketchat_token & rocketchat_token_file must be configured" { + t.Errorf("Expected: %s\nGot: %s", "at most one of rocketchat_token & rocketchat_token_file must be configured", err.Error()) + } +} + +func TestRocketchatBothTokenIDAndTokenIDFile(t *testing.T) { + _, err := LoadFile("testdata/conf.rocketchat-both-tokenid-and-tokenidfile.yml") + if err == nil { + t.Fatalf("Expected an error parsing %s: %s", "testdata/conf.rocketchat-both-tokenid-and-tokenidfile.yml", err) + } + if err.Error() != "at most one of rocketchat_token_id & rocketchat_token_id_file must be configured" { + t.Errorf("Expected: %s\nGot: %s", "at most one of rocketchat_token_id & rocketchat_token_id_file must be configured", err.Error()) + } +} + +func TestRocketchatNoToken(t *testing.T) { + _, err := LoadFile("testdata/conf.rocketchat-no-token.yml") + if err == nil { + t.Fatalf("Expected an error parsing %s: %s", "testdata/conf.rocketchat-no-token.yml", err) + } + if err.Error() != "no global Rocketchat Token set either inline or in a file" { + t.Errorf("Expected: %s\nGot: %s", "no global Rocketchat Token set either inline or in a file", err.Error()) + } +} + func TestUnmarshalHostPort(t *testing.T) { for _, tc := range []struct { in string diff --git a/config/notifiers.go b/config/notifiers.go index 6984166170..e85361f8e6 100644 --- a/config/notifiers.go +++ b/config/notifiers.go @@ -14,6 +14,7 @@ package config import ( + "errors" "fmt" "net/textproto" "regexp" @@ -98,6 +99,18 @@ var ( CallbackID: `{{ template "slack.default.callbackid" . }}`, Footer: `{{ template "slack.default.footer" . }}`, } + // DefaultRocketchatConfig defines default values for Rocketchat configurations. + DefaultRocketchatConfig = RocketchatConfig{ + NotifierConfig: NotifierConfig{ + VSendResolved: false, + }, + Color: `{{ if eq .Status "firing" }}red{{ else }}green{{ end }}`, + Emoji: `{{ template "rocketchat.default.emoji" . }}`, + IconURL: `{{ template "rocketchat.default.iconurl" . }}`, + Text: `{{ template "rocketchat.default.text" . }}`, + Title: `{{ template "rocketchat.default.title" . }}`, + TitleLink: `{{ template "rocketchat.default.titlelink" . }}`, + } // DefaultOpsGenieConfig defines default values for OpsGenie configurations. DefaultOpsGenieConfig = OpsGenieConfig{ @@ -870,6 +883,73 @@ func (c *JiraConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { if c.IssueType == "" { return fmt.Errorf("missing issue_type in jira_config") } + return nil +} + +type RocketchatAttachmentField struct { + Short *bool `json:"short"` + Title string `json:"title,omitempty"` + Value string `json:"value,omitempty"` +} + +const ( + ProcessingTypeSendMessage string = "sendMessage" + ProcessingTypeRespondWithMessage string = "respondWithMessage" +) + +type RocketchatAttachmentAction struct { + Type string `json:"type,omitempty"` + Text string `json:"text,omitempty"` + URL string `json:"url,omitempty"` + ImageURL string `json:"image_url,omitempty"` + IsWebView bool `json:"is_webview"` + WebviewHeightRatio string `json:"webview_height_ratio,omitempty"` + Msg string `json:"msg,omitempty"` + MsgInChatWindow bool `json:"msg_in_chat_window"` + MsgProcessingType string `json:"msg_processing_type,omitempty"` +} +// RocketchatConfig configures notifications via Rocketchat. +type RocketchatConfig struct { + NotifierConfig `yaml:",inline" json:",inline"` + + HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` + + APIURL *URL `yaml:"api_url,omitempty" json:"api_url,omitempty"` + TokenID *Secret `yaml:"token_id,omitempty" json:"token_id,omitempty"` + TokenIDFile string `yaml:"token_id_file,omitempty" json:"token_id_file,omitempty"` + Token *Secret `yaml:"token,omitempty" json:"token,omitempty"` + TokenFile string `yaml:"token_file,omitempty" json:"token_file,omitempty"` + + // RocketChat channel override, (like #other-channel or @username). + Channel string `yaml:"channel,omitempty" json:"channel,omitempty"` + + Color string `yaml:"color,omitempty" json:"color,omitempty"` + Title string `yaml:"title,omitempty" json:"title,omitempty"` + TitleLink string `yaml:"title_link,omitempty" json:"title_link,omitempty"` + Text string `yaml:"text,omitempty" json:"text,omitempty"` + Fields []*RocketchatAttachmentField `yaml:"fields,omitempty" json:"fields,omitempty"` + ShortFields bool `yaml:"short_fields" json:"short_fields,omitempty"` + Emoji string `yaml:"emoji,omitempty" json:"emoji,omitempty"` + IconURL string `yaml:"icon_url,omitempty" json:"icon_url,omitempty"` + ImageURL string `yaml:"image_url,omitempty" json:"image_url,omitempty"` + ThumbURL string `yaml:"thumb_url,omitempty" json:"thumb_url,omitempty"` + LinkNames bool `yaml:"link_names" json:"link_names,omitempty"` + Actions []*RocketchatAttachmentAction `yaml:"actions,omitempty" json:"actions,omitempty"` +} + +// UnmarshalYAML implements the yaml.Unmarshaler interface. +func (c *RocketchatConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + *c = DefaultRocketchatConfig + type plain RocketchatConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + if c.Token != nil && len(c.TokenFile) > 0 { + return errors.New("at most one of token & token_file must be configured") + } + if c.TokenID != nil && len(c.TokenIDFile) > 0 { + return errors.New("at most one of token_id & token_id_file must be configured") + } return nil } diff --git a/config/receiver/receiver.go b/config/receiver/receiver.go index 040d7534b9..a8572abe44 100644 --- a/config/receiver/receiver.go +++ b/config/receiver/receiver.go @@ -27,6 +27,7 @@ import ( "github.com/prometheus/alertmanager/notify/opsgenie" "github.com/prometheus/alertmanager/notify/pagerduty" "github.com/prometheus/alertmanager/notify/pushover" + "github.com/prometheus/alertmanager/notify/rocketchat" "github.com/prometheus/alertmanager/notify/slack" "github.com/prometheus/alertmanager/notify/sns" "github.com/prometheus/alertmanager/notify/telegram" @@ -96,6 +97,9 @@ func BuildReceiverIntegrations(nc config.Receiver, tmpl *template.Template, logg for i, c := range nc.JiraConfigs { add("jira", i, c, func(l log.Logger) (notify.Notifier, error) { return jira.New(c, tmpl, l, httpOpts...) }) } + for i, c := range nc.RocketchatConfigs { + add("rocketchat", i, c, func(l log.Logger) (notify.Notifier, error) { return rocketchat.New(c, tmpl, l, httpOpts...) }) + } if errs.Len() > 0 { return nil, &errs diff --git a/config/testdata/conf.rocketchat-both-token-and-tokenfile.yml b/config/testdata/conf.rocketchat-both-token-and-tokenfile.yml new file mode 100644 index 0000000000..b51cebde47 --- /dev/null +++ b/config/testdata/conf.rocketchat-both-token-and-tokenfile.yml @@ -0,0 +1,20 @@ +global: + rocketchat_token_file: /global_file + rocketchat_token: token123 +route: + group_by: ['alertname', 'cluster', 'service'] + group_wait: 30s + group_interval: 5m + repeat_interval: 3h + receiver: team-Y-rocketchat + routes: + - match: + service: foo + receiver: team-X-rocketchat +receivers: + - name: 'team-X-rocketchat' + rocketchat_configs: + - channel: '#team-X' + - name: 'team-Y-rocketchat' + rocketchat_configs: + - channel: '#team-Y' diff --git a/config/testdata/conf.rocketchat-both-tokenid-and-tokenidfile.yml b/config/testdata/conf.rocketchat-both-tokenid-and-tokenidfile.yml new file mode 100644 index 0000000000..702e0522c7 --- /dev/null +++ b/config/testdata/conf.rocketchat-both-tokenid-and-tokenidfile.yml @@ -0,0 +1,20 @@ +global: + rocketchat_token_id_file: /global_file + rocketchat_token_id: id123 +route: + group_by: ['alertname', 'cluster', 'service'] + group_wait: 30s + group_interval: 5m + repeat_interval: 3h + receiver: team-Y-rocketchat + routes: + - match: + service: foo + receiver: team-X-rocketchat +receivers: + - name: 'team-X-rocketchat' + rocketchat_configs: + - channel: '#team-X' + - name: 'team-Y-rocketchat' + rocketchat_configs: + - channel: '#team-Y' diff --git a/config/testdata/conf.rocketchat-default-token-file.yml b/config/testdata/conf.rocketchat-default-token-file.yml new file mode 100644 index 0000000000..c298422938 --- /dev/null +++ b/config/testdata/conf.rocketchat-default-token-file.yml @@ -0,0 +1,22 @@ +global: + rocketchat_token_file: /global_file + rocketchat_token_id_file: /etc/alertmanager/rocketchat_token_id +route: + group_by: ['alertname', 'cluster', 'service'] + group_wait: 30s + group_interval: 5m + repeat_interval: 3h + receiver: team-Y-rocketchat + routes: + - match: + service: foo + receiver: team-X-rocketchat +receivers: + - name: 'team-X-rocketchat' + rocketchat_configs: + - channel: '#team-X' + - name: 'team-Y-rocketchat' + rocketchat_configs: + - channel: '#team-Y' + token_file: /override_file + token_id_file: /override_file diff --git a/config/testdata/conf.rocketchat-default-token.yml b/config/testdata/conf.rocketchat-default-token.yml new file mode 100644 index 0000000000..01387472c8 --- /dev/null +++ b/config/testdata/conf.rocketchat-default-token.yml @@ -0,0 +1,22 @@ +global: + rocketchat_token: token123 + rocketchat_token_id: id123 +route: + group_by: ['alertname', 'cluster', 'service'] + group_wait: 30s + group_interval: 5m + repeat_interval: 3h + receiver: team-Y-rocketchat + routes: + - match: + service: foo + receiver: team-X-rocketchat +receivers: + - name: 'team-X-rocketchat' + rocketchat_configs: + - channel: '#team-X' + - name: 'team-Y-rocketchat' + rocketchat_configs: + - channel: '#team-Y' + token: token456 + token_id: id456 diff --git a/config/testdata/conf.rocketchat-no-token.yml b/config/testdata/conf.rocketchat-no-token.yml new file mode 100644 index 0000000000..ca44388828 --- /dev/null +++ b/config/testdata/conf.rocketchat-no-token.yml @@ -0,0 +1,19 @@ +global: + rocketchat_token_id: id123 +route: + group_by: ['alertname', 'cluster', 'service'] + group_wait: 30s + group_interval: 5m + repeat_interval: 3h + receiver: team-Y-rocketchat + routes: + - match: + service: foo + receiver: team-X-rocketchat +receivers: + - name: 'team-X-rocketchat' + rocketchat_configs: + - channel: '#team-X' + - name: 'team-Y-rocketchat' + rocketchat_configs: + - channel: '#team-Y' diff --git a/docs/configuration.md b/docs/configuration.md index ee012b4f44..147ebba440 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -97,7 +97,7 @@ global: # The default TLS configuration for SMTP receivers [ smtp_tls_config: ] - # Default settings for the JIRA integration. + # Default settings for the JIRA integration. [ jira_api_url: ] # The API URL to use for Slack notifications. @@ -110,6 +110,11 @@ global: [ opsgenie_api_key: ] [ opsgenie_api_key_file: ] [ opsgenie_api_url: | default = "https://api.opsgenie.com/" ] + [ rocketchat_api_url: | default = "https://open.rocket.chat/api/v1/chat.postMessage" ] + [ rocketchat_token: ] + [ rocketchat_token_file: ] + [ rocketchat_token_id: ] + [ rocketchat_token_id_file: ] [ wechat_api_url: | default = "https://qyapi.weixin.qq.com/cgi-bin/" ] [ wechat_api_secret: ] [ wechat_api_corp_id: ] @@ -708,6 +713,8 @@ pagerduty_configs: [ - , ... ] pushover_configs: [ - , ... ] +rocket_configs: + [ - , ... ] slack_configs: [ - , ... ] sns_configs: @@ -954,7 +961,7 @@ Microsoft Teams notifications are sent via the [Incoming Webhooks](https://learn JIRA notifications are sent via [JIRA Rest API v2](https://developer.atlassian.com/cloud/jira/platform/rest/v2/intro/) or [JIRA REST API v3](https://developer.atlassian.com/cloud/jira/platform/rest/v3/intro/#version). -Note: This integration is only tested against a Jira Cloud instance. +Note: This integration is only tested against a Jira Cloud instance. Jira Data Center (on premise instance) can work, but it's not guaranteed. Both APIs have the same feature set. The difference is that V2 supports [Wiki Markup](https://jira.atlassian.com/secure/WikiRendererHelpAction.jspa?section=all) @@ -979,7 +986,7 @@ project: [ description: | default = '{{ template "jira.default.description" . }}' ] # Labels to be added to the issue. -labels: +labels: [ - ... ] # Priority of the issue. @@ -1256,6 +1263,62 @@ token_file: [ http_config: | default = global.http_config ] ``` +### `` + +Rocketchat notifications are sent via the [Rocketchat REST API](https://developer.rocket.chat/reference/api/rest-api/endpoints/messaging/chat-endpoints/postmessage). + +```yaml +# Whether to notify about resolved alerts. +[ send_resolved: | default = true ] +[ api_url: | default = global.rocketchat_api_url ] +[ channel: | default = global.rocketchat_api_url ] + +# The sender token and token_id +# See https://docs.rocket.chat/use-rocket.chat/user-guides/user-panel/my-account#personal-access-tokens +# token and token_file are mutually exclusive. +# token_id and token_id_file are mutually exclusive. +token: +token_file: +token_id: +token_id_file: + + +[ color: ... ] +[ image_url ] +[ thumb_url ] +[ link_names ] +[ short_fields: | default = false ] +actions: + [ ... ] +``` + +#### `` + +The fields are documented in the [Rocketchat API documentation](https://developer.rocket.chat/reference/api/rest-api/endpoints/messaging/chat-endpoints/postmessage#attachment-field-objects). + +```yaml +[ title: ] +[ value: ] +[ short: | default = rocketchat_config.short_fields ] +``` + +#### `` +The fields are documented in the [Rocketchat API api models](https://github.com/RocketChat/Rocket.Chat.Go.SDK/blob/master/models/message.go). + +```yaml +[ type: | ignored, only "button" is supported ] +[ text: ] +[ url: ] +[ msg: ] + ### `` Slack notifications can be sent via [Incoming webhooks](https://api.slack.com/messaging/webhooks) or [Bot tokens](https://api.slack.com/authentication/token-types). diff --git a/notify/notify.go b/notify/notify.go index b5e1ae91b6..43df43a38b 100644 --- a/notify/notify.go +++ b/notify/notify.go @@ -366,6 +366,7 @@ func (m *Metrics) InitializeFor(receiver map[string][]Integration) { "webex", "msteams", "jira", + "rocketchat", } { m.numNotifications.WithLabelValues(integration) m.numNotificationRequestsTotal.WithLabelValues(integration) diff --git a/notify/rocketchat/rocketchat.go b/notify/rocketchat/rocketchat.go new file mode 100644 index 0000000000..2dc06b4397 --- /dev/null +++ b/notify/rocketchat/rocketchat.go @@ -0,0 +1,269 @@ +// Copyright 2022 Prometheus Team +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package rocketchat + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "strings" + + "github.com/go-kit/log" + "github.com/go-kit/log/level" + commoncfg "github.com/prometheus/common/config" + + "github.com/prometheus/alertmanager/config" + "github.com/prometheus/alertmanager/notify" + "github.com/prometheus/alertmanager/template" + "github.com/prometheus/alertmanager/types" +) + +const maxTitleLenRunes = 1024 + +type Notifier struct { + conf *config.RocketchatConfig + tmpl *template.Template + logger log.Logger + client *http.Client + retrier *notify.Retrier + token string + tokenID string + + postJSONFunc func(ctx context.Context, client *http.Client, url string, body io.Reader) (*http.Response, error) +} + +// PostMessage Payload for postmessage rest API +// +// https://rocket.chat/docs/developer-guides/rest-api/chat/postmessage/ +type Attachment struct { + Title string `json:"title,omitempty"` + TitleLink string `json:"title_link,omitempty"` + Text string `json:"text,omitempty"` + ImageURL string `json:"image_url,omitempty"` + ThumbURL string `json:"thumb_url,omitempty"` + Color string `json:"color,omitempty"` + Fields []config.RocketchatAttachmentField `json:"fields,omitempty"` + Actions []config.RocketchatAttachmentAction `json:"actions,omitempty"` +} + +// PostMessage Payload for postmessage rest API +// +// https://rocket.chat/docs/developer-guides/rest-api/chat/postmessage/ +type PostMessage struct { + Channel string `json:"channel,omitempty"` + Text string `json:"text,omitempty"` + ParseUrls bool `json:"parseUrls,omitempty"` + Alias string `json:"alias,omitempty"` + Emoji string `json:"emoji,omitempty"` + Avatar string `json:"avatar,omitempty"` + Attachments []Attachment `json:"attachments,omitempty"` + Actions []config.RocketchatAttachmentAction `json:"actions,omitempty"` +} + +type rocketchatRoundTripper struct { + wrapped http.RoundTripper + token string + tokenID string +} + +func (t *rocketchatRoundTripper) RoundTrip(req *http.Request) (res *http.Response, e error) { + req.Header.Set("X-Auth-Token", t.token) + req.Header.Set("X-User-Id", t.tokenID) + return t.wrapped.RoundTrip(req) +} + +// New returns a new Rocketchat notification handler. +func New(c *config.RocketchatConfig, t *template.Template, l log.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) { + client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "rocketchat", httpOpts...) + if err != nil { + return nil, err + } + token, err := getToken(c) + if err != nil { + return nil, err + } + tokenID, err := getTokenID(c) + if err != nil { + return nil, err + } + + client.Transport = &rocketchatRoundTripper{wrapped: client.Transport, token: token, tokenID: tokenID} + return &Notifier{ + conf: c, + tmpl: t, + logger: l, + client: client, + retrier: ¬ify.Retrier{}, + postJSONFunc: notify.PostJSON, + token: token, + tokenID: tokenID, + }, nil +} + +func getTokenID(c *config.RocketchatConfig) (string, error) { + if len(c.TokenIDFile) > 0 { + content, err := os.ReadFile(c.TokenIDFile) + if err != nil { + return "", fmt.Errorf("could not read %s: %w", c.TokenIDFile, err) + } + return strings.TrimSpace(string(content)), nil + } + return string(*c.TokenID), nil +} + +func getToken(c *config.RocketchatConfig) (string, error) { + if len(c.TokenFile) > 0 { + content, err := os.ReadFile(c.TokenFile) + if err != nil { + return "", fmt.Errorf("could not read %s: %w", c.TokenFile, err) + } + return strings.TrimSpace(string(content)), nil + } + return string(*c.Token), nil +} + +// Notify implements the Notifier interface. +func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) { + var err error + + data := notify.GetTemplateData(ctx, n.tmpl, as, n.logger) + tmplText := notify.TmplText(n.tmpl, data, &err) + if err != nil { + return false, err + } + title := tmplText(n.conf.Title) + if err != nil { + return false, err + } + + title, truncated := notify.TruncateInRunes(title, maxTitleLenRunes) + if truncated { + key, err := notify.ExtractGroupKey(ctx) + if err != nil { + return false, err + } + level.Warn(n.logger).Log("msg", "Truncated title", "key", key, "max_runes", maxTitleLenRunes) + } + att := &Attachment{ + Title: title, + TitleLink: tmplText(n.conf.TitleLink), + Text: tmplText(n.conf.Text), + ImageURL: tmplText(n.conf.ImageURL), + ThumbURL: tmplText(n.conf.ThumbURL), + Color: tmplText(n.conf.Color), + } + numFields := len(n.conf.Fields) + if numFields > 0 { + fields := make([]config.RocketchatAttachmentField, numFields) + for index, field := range n.conf.Fields { + // Check if short was defined for the field otherwise fallback to the global setting + var short bool + if field.Short != nil { + short = *field.Short + } else { + short = n.conf.ShortFields + } + + // Rebuild the field by executing any templates and setting the new value for short + fields[index] = config.RocketchatAttachmentField{ + Title: tmplText(field.Title), + Value: tmplText(field.Value), + Short: &short, + } + } + att.Fields = fields + } + numActions := len(n.conf.Actions) + if numActions > 0 { + actions := make([]config.RocketchatAttachmentAction, numActions) + for index, action := range n.conf.Actions { + actions[index] = config.RocketchatAttachmentAction{ + Type: "button", // Only button type is supported + Text: tmplText(action.Text), + URL: tmplText(action.URL), + Msg: tmplText(action.Msg), + } + } + att.Actions = actions + } + + body := &PostMessage{ + Channel: n.conf.Channel, + Emoji: tmplText(n.conf.Emoji), + Avatar: tmplText(n.conf.IconURL), + Attachments: []Attachment{*att}, + } + if err != nil { + return false, err + } + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(body); err != nil { + return false, err + } + resp, err := n.postJSONFunc(ctx, n.client, n.conf.APIURL.String(), &buf) + if err != nil { + return true, notify.RedactURL(err) + } + defer notify.Drain(resp) + + // Use a retrier to generate an error message for non-200 responses and + // classify them as retriable or not. + retry, err := n.retrier.Check(resp.StatusCode, resp.Body) + if err != nil { + err = fmt.Errorf("channel %q: %w", body.Channel, err) + return retry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err) + } + + // Rocketchat web API might return errors with a 200 response code. + retry, err = checkResponseError(resp) + if err != nil { + err = fmt.Errorf("channel %q: %w", body.Channel, err) + return retry, notify.NewErrorWithReason(notify.ClientErrorReason, err) + } + + return retry, nil +} + +// checkResponseError parses out the error message from Rocketchat API response. +func checkResponseError(resp *http.Response) (bool, error) { + body, err := io.ReadAll(resp.Body) + if err != nil { + return true, fmt.Errorf("could not read response body: %w", err) + } + + return checkJSONResponseError(body) +} + +// checkJSONResponseError classifies JSON responses from Rocketchat. +func checkJSONResponseError(body []byte) (bool, error) { + // response is for parsing out errors from the JSON response. + type response struct { + Success bool `json:"success"` + Error string `json:"error"` + } + + var data response + if err := json.Unmarshal(body, &data); err != nil { + return true, fmt.Errorf("could not unmarshal JSON response %q: %w", string(body), err) + } + if !data.Success { + return false, fmt.Errorf("error response from Rocketchat: %s", data.Error) + } + return false, nil +} diff --git a/notify/rocketchat/rocketchat_test.go b/notify/rocketchat/rocketchat_test.go new file mode 100644 index 0000000000..35033d3db7 --- /dev/null +++ b/notify/rocketchat/rocketchat_test.go @@ -0,0 +1,66 @@ +// Copyright 2019 Prometheus Team +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package rocketchat + +import ( + "fmt" + "net/url" + "os" + "testing" + + "github.com/go-kit/log" + commoncfg "github.com/prometheus/common/config" + "github.com/stretchr/testify/require" + + "github.com/prometheus/alertmanager/config" + "github.com/prometheus/alertmanager/notify/test" +) + +func TestRocketchatRetry(t *testing.T) { + secret := config.Secret("xxxxx") + notifier, err := New( + &config.RocketchatConfig{ + HTTPConfig: &commoncfg.HTTPClientConfig{}, + Token: &secret, + TokenID: &secret, + }, + test.CreateTmpl(t), + log.NewNopLogger(), + ) + require.NoError(t, err) + + for statusCode, expected := range test.RetryTests(test.DefaultRetryCodes()) { + actual, _ := notifier.retrier.Check(statusCode, nil) + require.Equal(t, expected, actual, fmt.Sprintf("error on status %d", statusCode)) + } +} + +func TestGettingRocketchatTokenFromFile(t *testing.T) { + f, err := os.CreateTemp("", "rocketchat_test") + require.NoError(t, err, "creating temp file failed") + _, err = f.WriteString("secret") + require.NoError(t, err, "writing to temp file failed") + + _, err = New( + &config.RocketchatConfig{ + TokenFile: f.Name(), + TokenIDFile: f.Name(), + HTTPConfig: &commoncfg.HTTPClientConfig{}, + APIURL: &config.URL{URL: &url.URL{Scheme: "http", Host: "example.com", Path: "/api/v1/"}}, + }, + test.CreateTmpl(t), + log.NewNopLogger(), + ) + require.NoError(t, err) +} diff --git a/template/default.tmpl b/template/default.tmpl index 299bdecbb6..8ebf1bd6aa 100644 --- a/template/default.tmpl +++ b/template/default.tmpl @@ -197,3 +197,10 @@ Alerts Resolved: {{- end -}} {{- $priority -}} {{- end -}} + +{{ define "rocketchat.default.title" }}{{ template "__subject" . }}{{ end }} +{{ define "rocketchat.default.alias" }}{{ template "__alertmanager" . }}{{ end }} +{{ define "rocketchat.default.titlelink" }}{{ template "__alertmanagerURL" . }}{{ end }} +{{ define "rocketchat.default.emoji" }}{{ end }} +{{ define "rocketchat.default.iconurl" }}{{ end }} +{{ define "rocketchat.default.text" }}{{ end }}