|
| 1 | +// Copyright 2017 The Prometheus Authors |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package clientset |
| 15 | + |
| 16 | +import ( |
| 17 | + "errors" |
| 18 | + "fmt" |
| 19 | + "sync" |
| 20 | + |
| 21 | + "github.com/andygrunwald/go-jira" |
| 22 | + "github.com/prometheus-community/jiralert/pkg/config" |
| 23 | +) |
| 24 | + |
| 25 | +type ClientSet struct { |
| 26 | + jira map[string]*jira.Client |
| 27 | + sync.RWMutex |
| 28 | +} |
| 29 | + |
| 30 | +var errorClientExists = errors.New("client already exists") |
| 31 | + |
| 32 | +func (c *ClientSet) getJira(userName string) (*jira.Client, bool) { |
| 33 | + c.RLock() |
| 34 | + jc, ok := c.jira[userName] |
| 35 | + c.RUnlock() |
| 36 | + |
| 37 | + return jc, ok |
| 38 | +} |
| 39 | + |
| 40 | +func (c *ClientSet) newJira(conf *config.ReceiverConfig) (*jira.Client, error) { |
| 41 | + if conf == nil { |
| 42 | + return nil, fmt.Errorf("missing receiver config") |
| 43 | + } |
| 44 | + |
| 45 | + if jc, ok := c.getJira(conf.User); ok { |
| 46 | + return jc, fmt.Errorf("jira %w: %s", errorClientExists, conf.User) |
| 47 | + } |
| 48 | + |
| 49 | + var ( |
| 50 | + client *jira.Client |
| 51 | + err error |
| 52 | + ) |
| 53 | + if conf.User != "" && conf.Password != "" { |
| 54 | + tp := jira.BasicAuthTransport{ |
| 55 | + Username: conf.User, |
| 56 | + Password: string(conf.Password), |
| 57 | + } |
| 58 | + client, err = jira.NewClient(tp.Client(), conf.APIURL) |
| 59 | + } else if conf.PersonalAccessToken != "" { |
| 60 | + tp := jira.PATAuthTransport{ |
| 61 | + Token: string(conf.PersonalAccessToken), |
| 62 | + } |
| 63 | + client, err = jira.NewClient(tp.Client(), conf.APIURL) |
| 64 | + } |
| 65 | + |
| 66 | + if err == nil { |
| 67 | + c.Lock() |
| 68 | + c.jira[conf.User] = client |
| 69 | + c.Unlock() |
| 70 | + } |
| 71 | + |
| 72 | + return client, err |
| 73 | +} |
| 74 | + |
| 75 | +func (c *ClientSet) GetOrCreateJira(conf *config.ReceiverConfig) (*jira.Client, error) { |
| 76 | + jc, err := c.newJira(conf) |
| 77 | + if errors.Is(err, errorClientExists) { |
| 78 | + err = nil |
| 79 | + } |
| 80 | + return jc, err |
| 81 | +} |
0 commit comments