Skip to content

Commit

Permalink
upgrade to new api
Browse files Browse the repository at this point in the history
  • Loading branch information
ns3777k committed Jul 7, 2024
1 parent 42f4f59 commit 72e9a94
Show file tree
Hide file tree
Showing 10 changed files with 54 additions and 77 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.15
go-version: 1.20

- name: Login to Docker Registry
run: echo "${{ secrets.DOCKERHUB_TOKEN }}" | docker login -u ns3777k --password-stdin
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
.idea
/alertmanager-webhook-jetbrains-space
/dist
.DS_Store
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ Before you begin, you need multiple things to have:
usage: alertmanager-webhook-space \
--space-channel-id=SPACE-CHANNEL-ID \
--space-base-url=SPACE-BASE-URL \
--space-client-id=SPACE-CLIENT-ID \
--space-client-secret=SPACE-CLIENT-SECRET \
--space-token=APP_TOKEN \
--debug \
[<flags>]

alertmanager-webhook-space
Expand All @@ -27,10 +27,10 @@ Flags:
Channel id
--space-base-url=SPACE-BASE-URL
Base url like https://mycompany.jetbrains.space
--space-client-id=SPACE-CLIENT-ID
Application client id
--space-client-secret=SPACE-CLIENT-SECRET
Application client secret
--space-token=APP_TOKEN
Application token
--debug
Debug logs
```

## Building from source
Expand Down
17 changes: 9 additions & 8 deletions cmd/alertmanager-webhook-space/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ func makeSignalShutdownChan() chan os.Signal {
}

type Configuration struct {
Debug bool
ListenAddr string
ChannelID string
}
Expand Down Expand Up @@ -58,15 +59,15 @@ func main() {
Required().
StringVar(&spaceClientSettings.BaseURL)

app.Flag("space-client-id", "Application client id").
Envar("CLIENT_ID").
app.Flag("space-token", "Application token").
Envar("APP_TOKEN").
Required().
StringVar(&spaceClientSettings.ClientID)
StringVar(&spaceClientSettings.ApplicationToken)

app.Flag("space-client-secret", "Application client secret").
Envar("CLIENT_SECRET").
Required().
StringVar(&spaceClientSettings.ClientSecret)
app.Flag("debug", "Debug logs").
Envar("DEBUG").
Default("false").
BoolVar(&configuration.Debug)

if _, err := app.Parse(os.Args[1:]); err != nil {
app.Usage(os.Args[1:])
Expand All @@ -75,7 +76,7 @@ func main() {

shutdownCh := make(chan struct{})
spaceClient := space.NewClient(spaceClientSettings)
h := alertHttp.NewHandler(spaceClient, configuration.ChannelID)
h := alertHttp.NewHandler(spaceClient, logger, configuration.ChannelID, configuration.Debug)
server := &http.Server{
ReadTimeout: time.Second * 5,
WriteTimeout: time.Second * 5,
Expand Down
11 changes: 8 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
module github.com/ns3777k/alertmanager-webhook-space

go 1.14
go 1.20

require (
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4 // indirect
github.com/go-resty/resty/v2 v2.3.0
github.com/gorilla/mux v1.8.0
github.com/joho/godotenv v1.3.0
github.com/sirupsen/logrus v1.7.0
gopkg.in/alecthomas/kingpin.v2 v2.2.6
)

require (
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4 // indirect
golang.org/x/net v0.0.0-20200513185701-a91f0712d120 // indirect
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd // indirect
)
3 changes: 0 additions & 3 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafo
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4 h1:EBTWhcAX7rNQ80RLwLCpHZBBrJuzallFHnF+yMXo928=
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand All @@ -24,14 +23,12 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/net v0.0.0-20200513185701-a91f0712d120 h1:EZ3cVSzKOlJxAd8e8YAJ7no8nNypTxexh/YE/xW3ZEY=
golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
29 changes: 17 additions & 12 deletions http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package http
import (
"context"
"encoding/json"
"github.com/sirupsen/logrus"
"io"
"io/ioutil"
"net/http"
"time"

Expand All @@ -14,26 +14,21 @@ import (
"github.com/ns3777k/alertmanager-webhook-space/pkg/space"
)

func unmarshalReader(r io.Reader, v interface{}) error {
b, err := ioutil.ReadAll(r)
if err != nil {
return err
}

return json.Unmarshal(b, &v)
}

type Handler struct {
channelID string
debug bool
logger *logrus.Logger
spaceClient *space.Client
Router *mux.Router
}

func NewHandler(spaceClient *space.Client, channelID string) *Handler {
func NewHandler(spaceClient *space.Client, logger *logrus.Logger, channelID string, debug bool) *Handler {
h := &Handler{
spaceClient: spaceClient,
channelID: channelID,
Router: mux.NewRouter(),
debug: debug,
logger: logger,
}

h.Router.HandleFunc("/healthcheck", h.Healthcheck)
Expand All @@ -49,7 +44,17 @@ func (h *Handler) Healthcheck(w http.ResponseWriter, r *http.Request) {
func (h *Handler) Notify(w http.ResponseWriter, r *http.Request) {
var payload alertmanager.WebHookPayload

if err := unmarshalReader(r.Body, &payload); err != nil {
b, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

if h.debug {
h.logger.Info(string(b))
}

if err := json.Unmarshal(b, &payload); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/notification/mapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ func MapAlertToMessage(alert *alertmanager.Alert, channelID string) *space.Messa
}

return &space.Message{
Recipient: &space.MessageRecipient{
ClassName: "MessageRecipient.Channel",
Channel: &space.ChannelIdentifier{
ClassName: "ChannelIdentifier.Channel",
Channel: &space.MessageChannel{
ClassName: "ChatChannel.FromId",
ID: channelID,
Expand Down
38 changes: 3 additions & 35 deletions pkg/space/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ import (
)

type ClientSettings struct {
BaseURL string
ClientID string
ClientSecret string
BaseURL string
ApplicationToken string
}

type Client struct {
Expand All @@ -34,38 +33,7 @@ func NewClient(settings *ClientSettings) *Client {
return &Client{client: client, settings: settings}
}

func (c *Client) auth(ctx context.Context) (string, error) {
resp, err := c.client.R().
SetBody("grant_type=client_credentials").
SetContext(ctx).
SetHeader("Content-Type", "application/x-www-form-urlencoded").
SetBasicAuth(c.settings.ClientID, c.settings.ClientSecret).
Post(c.settings.BaseURL + "/oauth/token")

if err != nil {
return "", err
}

defer resp.RawResponse.Body.Close()

if resp.StatusCode() != http.StatusOK {
return "", errors.New("auth response code: " + resp.Status())
}

var response authResponse
if err := json.Unmarshal(resp.Body(), &response); err != nil {
return "", err
}

return response.AccessToken, nil
}

func (c *Client) SendMessage(ctx context.Context, message *Message) error {
token, err := c.auth(ctx)
if err != nil {
return err
}

b, err := json.Marshal(message)
if err != nil {
return err
Expand All @@ -75,7 +43,7 @@ func (c *Client) SendMessage(ctx context.Context, message *Message) error {
SetBody(b).
SetContext(ctx).
SetHeader("Content-Type", "application/json").
SetAuthToken(token).
SetAuthToken(c.settings.ApplicationToken).
Post(c.settings.BaseURL + "/api/http/chats/messages/send-message")

if err != nil {
Expand Down
14 changes: 7 additions & 7 deletions pkg/space/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,6 @@ type MessageChannel struct {
ID string `json:"id"`
}

type MessageRecipient struct {
ClassName string `json:"className"`
Channel *MessageChannel `json:"channel"`
}

type MessageContentSectionElement struct {
ClassName string `json:"className"`
Content string `json:"content"`
Expand All @@ -28,7 +23,12 @@ type MessageContent struct {
Sections []*MessageContentSection `json:"sections"`
}

type ChannelIdentifier struct {
ClassName string `json:"className"`
Channel *MessageChannel `json:"channel"`
}

type Message struct {
Recipient *MessageRecipient `json:"recipient"`
Content *MessageContent `json:"content"`
Channel *ChannelIdentifier `json:"channel"`
Content *MessageContent `json:"content"`
}

0 comments on commit 72e9a94

Please sign in to comment.