v0.0.0-...-2d91164 Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Apr 9, 2020 License: MIT Imports: 33 Imported by: 0



The contents of this file should be all thread safe Global functions for use with templates



View Source
const (
	EventEndpoint            = "/slack/event"
	InterctEndpoint          = "/slack/interact"
	SlashEndpoint            = "/slack/slash"
	LoadActionsEndpoint      = "/slack/load-actions"
	AtsuEventEndpoint        = "/slack/atsu-event"
	SlackAuthorizeEndpoint   = "/slack/authorize"
	SlackCallbackEndpoint    = "/slack/callback"
	SlackOnDemandTplEndpoint = "/slack/on-demand-template"
	FreeformTemplate         = "_freeform.tpl"
	FreeformPassword         = "YXRzdS10by10aGUtbW9vbiEhIQ==" // TODO XXX hard-coded for now
	SlackAuthorizeUrl        = ""
	SlackAccessUrl           = ""
View Source
const (
	// Feedback is the kafka message type for responding to alerts, see `_alert_response.tpl`
	Feedback = KafkaMessageType("feedback")


View Source
var Channel = ResponseType("channel")
View Source
var Dialog = ResponseType("dialog")
View Source
var Direct = ResponseType("direct")
View Source
var GlobalCache = NewCache(time.Minute, defaultExpiryCapacity)

GlobalCache always gets initialized and can be used simply with no other initialization

View Source
var HelperMetrics = &helperInstrument{
	slowRequestThresh:             time.Second * 3,
	elasticSearchSlowRequests:     make([]slowRequest, 0, 20),
	elasticSearchResponseTimeSecs: metric.NewHistogram("1h1h"),
	elasticSearchRequestCount:     metric.NewCounter("1h1h"),

HelperMetrics is an object to make instrumenting what happens in the helper functions easier

View Source
var None = ResponseType("none")
View Source
var WebHook = ResponseType("webhook")


func CachedByKey

func CachedByKey(k string) string

func CachedByVal

func CachedByVal(v string) string

func Error

func Error(msg string) (bool, error)

Error is a simple function to allow throwing errors from within templates

func GetAnomalies

func GetAnomalies() string

func GetMounts

func GetMounts(host, index string) ([]string, error)

func ParseDialog

func ParseDialog(input []byte) (slack.Dialog, error)

func ParseInteractionCallback

func ParseInteractionCallback(b []byte) (slack.InteractionCallback, error)

func ParseMessage

func ParseMessage(input []byte) (slack.Message, error)

ParseMessage is convenience helper for translating a json []byte into a slack.Message

func ReadTemplates

func ReadTemplates(dir string) (*template.Template, map[string]*TemplateMetadata, error)

func TruncatePath

func TruncatePath(p string, max int) string

TruncatePath is a helper for trimming paths to a specific size limit we try to keep it pretty by chopping off inner path segments eg '/one/two/three/four/five' becomes '/one/*/five' for 11 char limit

if the last segment is > char limit, we simply truncate the name eg '/one/two/somelongfilename' becomes '*name' for 5 char limit


type Action

type Action struct {
	OnDemand     bool // should this action use an on-demand template
	ResponseType ResponseType
	ResponseUrl  string
	Channel      string
	TriggerId    string
	Id           string
	TeamId       string
	TemplateName string
	TemplateMeta TemplateMetadata
	Data         TemplateData

Action is an encapsulation of a slack template execution. We run the template name against the template data.

func (*Action) SetResponse

func (a *Action) SetResponse(rt ResponseType, responseUrl, channel, triggerId string)

func (*Action) String

func (a *Action) String() string

type ActionInput

type ActionInput struct {
	OnDemand        bool
	Id              string
	TeamId          string
	Team            string
	Channel         string
	User            string
	InputText       string
	InteractionData map[string]interface{}
	TemplateName    string

func (*ActionInput) Validate

func (ai *ActionInput) Validate() error

type ActionResult

type ActionResult struct {
	TeamId            string
	Error             error
	Action            *Action
	ResponseUrl       string
	Channel           string
	TriggerId         string
	ResponseType      ResponseType
	SendToKafka       bool
	KafkaMessageType  KafkaMessageType
	Data              TemplateData
	ProcessedTemplate []byte

func (ActionResult) String

func (ar ActionResult) String() string

type EnvironmentParams

type EnvironmentParams struct {
	ElasticSearchUrl string
	ViewUrl          string
	HealthUrl        string

type FeedbackMessage

type FeedbackMessage struct {
	User   string  `json:"user"`
	Label  float64 `json:"label"`
	Value  float64 `json:"value,omitempty"`
	AtsuId string  `json:"atsu_id,omitempty"`
	Etype  string  `json:"etype,omitempty"`

FeedbackMessage corresponds to the KafkaMessageType `Feedback`, this struct dictates the json format.

type HelperStatus

type HelperStatus struct {
	ElasticSearchResponseTimeSecs interface{}
	ElasticSearchRequestCount     interface{}
	ElasticSearchSlowRequests     interface{}

type Identity

type Identity struct {
	Id   string `json:"id"`
	Name string `json:"name"`

type KafkaMessageType

type KafkaMessageType string

KafkaMessageType dictates the how messages should be sent to kafka it can change the message format as well as which topic sent to.

type ResponseType

type ResponseType string

type Slack

type Slack struct {
	// contains filtered or unexported fields

func NewSlack

func NewSlack(cfg SlackConfig, com interfaces.ChatOpsCom, database db.Database) *Slack

func (*Slack) AtsuEventHandler

func (s *Slack) AtsuEventHandler(w http.ResponseWriter, r *http.Request)

AtsuEventHandler handles incoming requests from atsu this is a mechanism to translate an incoming request to a slack event. On demand templates can be run if the 'od' query parameter is truthy.

func (*Slack) AuthorizeHandler

func (s *Slack) AuthorizeHandler(w http.ResponseWriter, r *http.Request)

func (*Slack) CallbackHandler

func (s *Slack) CallbackHandler(w http.ResponseWriter, r *http.Request)

func (*Slack) ConvertBlockAction

func (s *Slack) ConvertBlockAction(message slack.InteractionCallback) *Action

ConvertBlockAction translates a block action into an Action

func (*Slack) ConvertCommandInput

func (s *Slack) ConvertCommandInput(teamId, teamDomain, channel, user, input string) (*Action, error)

ConvertCommandInput translates a string input into an Action this assumes the input is in a space delimited format that looks like a command line action with flags, stripping slack user ids example input: "action action2 -flag value -flag2 value2 -flag3" would be interpreted as attempting to process template "action_action2" with the map { "flag":"value", "flag2":"value2","flag3":true } *note* if template "action_action2" is not found, we will look for template "action"

func (*Slack) ConvertInteractionCallback

func (s *Slack) ConvertInteractionCallback(sa slack.InteractionCallback) *Action

func (*Slack) DelayedInteractionHandler

func (s *Slack) DelayedInteractionHandler(w http.ResponseWriter, r *http.Request)

DelayedInteractionHandler handles interactivity events from slack (

func (*Slack) EnvParams

func (s *Slack) EnvParams() EnvironmentParams

func (*Slack) EventHandler

func (s *Slack) EventHandler(w http.ResponseWriter, r *http.Request)

EventHandler handles events from the slack events api ( this is for subscribed events such as mentions

func (*Slack) ExecuteAction

func (s *Slack) ExecuteAction(action *Action) (*ActionResult, error)

ExecuteAction executes an Action which is typically processing a template or sending a message to kafka returns an ActionResult if further action is required, typically an ActionResult is returned if there is still something that needs to go back to slack.

func (*Slack) ImmediateInteractionHandler

func (s *Slack) ImmediateInteractionHandler(w http.ResponseWriter, r *http.Request)

ImmediateInteractionHandler handles interactivity events from slack (

func (*Slack) KafkaSend

func (s *Slack) KafkaSend(mt KafkaMessageType, data TemplateData)

KafkaSend will produce a message to kafka based on the message type and template data.

func (*Slack) LoadTemplates

func (s *Slack) LoadTemplates() error

func (*Slack) NewAction

func (s *Slack) NewAction(input ActionInput) *Action

func (*Slack) OnDemandTemplateHandler

func (s *Slack) OnDemandTemplateHandler(w http.ResponseWriter, r *http.Request)
OnDemandTemplateHandler is a handler that will attempt to load a template from the

post body payload. ex:

{{/* Template Info --- name: od-test description: an example on demand template --- */}}

{"blocks": [{
           "type": "section",
           "text": {
               "type": "mrkdwn",
               "text": "{{ .InteractionData.text }}"

see the AtsuEventHandler for information about on demand templates.

func (*Slack) SendErrorResponse

func (s *Slack) SendErrorResponse(err error, rt ResponseType, teamId, channel, responseUrl string)

SendErrorResponse is for sending a direct response through slack to the user (via response url) or channel this effectively populates the default error template and posts it back to slack for the 'sorry an error happened' type failure.

func (*Slack) SendResultResponse

func (s *Slack) SendResultResponse(result *ActionResult)

SendResultResponse evaluates the ActionResult and sends the appropriate response payload back to slack

func (*Slack) SendToChannel

func (s *Slack) SendToChannel(team string, channel string, options ...slack.MsgOption)

SendToChannel sends the provided options list to the provided slack channel

func (*Slack) SetDebug

func (s *Slack) SetDebug(b bool)

func (*Slack) SlashHandler

func (s *Slack) SlashHandler(w http.ResponseWriter, r *http.Request)

SlashHandler handles slack slash command events (

func (*Slack) Start

func (s *Slack) Start(router *mux.Router, r *relay.Relay) error

func (*Slack) Status

func (s *Slack) Status() SlackStatus

func (*Slack) Stop

func (s *Slack) Stop()

func (*Slack) VerifyRequest

func (s *Slack) VerifyRequest(h http.Header, body []byte) bool


type SlackAuthResponse

type SlackAuthResponse struct {
	Ok              bool         `json:"ok"`
	AccessToken     string       `json:"access_token"`
	TokenType       string       `json:"token_type"`
	Scope           string       `json:"scope"`
	BotUserId       string       `json:"bot_user_id"`
	AppId           string       `json:"app_id"`
	Team            Identity     `json:"team"`
	Enterprise      Identity     `json:"enterprise"`
	IncomingWebHook SlackWebHook `json:"incoming_webhook"`

func (*SlackAuthResponse) String

func (s *SlackAuthResponse) String() string

type SlackConfig

type SlackConfig struct {
	AppId             string
	Token             string
	VerificationToken string
	SecretSigningKey  string
	InWebHook         string
	FeedbackTopic     string
	ClientId          string
	ClientSecret      string
	AuthRedirectUrl   string

	TemplateDir string

func (SlackConfig) Validate

func (cfg SlackConfig) Validate() error

type SlackInstance

type SlackInstance struct {
	TeamId     string
	WebHookUrl string
	BotToken   string
	// contains filtered or unexported fields

type SlackStatus

type SlackStatus struct {
	Health                health.State `json:"health"`
	ResponseTimeSecs      interface{}
	SlashCounter          interface{}
	EventCounter          interface{}
	InteractCounter       interface{}
	LoadActionCounter     interface{}
	AtsuEventCounter      interface{}
	ErrorsCounter         interface{}
	TemplateErrorsCounter interface{}
	ErrorTimes            []int64
	ErrorsRecent          []string
	Events                int64 `json:"events"`
	Errors                int64 `json:"errors"`

type SlackWebHook

type SlackWebHook struct {
	Channel          string `json:"channel"`
	ChannelId        string `json:"channel_id"`
	ConfigurationUrl string `json:"configuration_url"`
	Url              string `json:"url"`

type TemplateData

type TemplateData struct {
	Team            string
	Channel         string
	User            string
	InputText       string
	Timestamp       int64
	InteractionData map[string]interface{}

TemplateData is intended to be fed into a template to give template authors system level settings along with the interaction data that comes back from interactions

func (*TemplateData) FeedbackMessage

func (t *TemplateData) FeedbackMessage() FeedbackMessage

FeedbackMessage generates a FeedbackMessage object from the TemplateData object

type TemplateMetadata

type TemplateMetadata struct {
	Name             string
	Description      string
	SendToKafka      bool
	KafkaMessageType string
	IsTerminating    bool
	Dialog           bool
	Extra            map[string]interface{}

TemplateMetadata encapsulates values passed from the template via ParseTemplateMetadataFile

func ParseTemplateMetadata

func ParseTemplateMetadata(data io.Reader) (*TemplateMetadata, error)

func ParseTemplateMetadataFile

func ParseTemplateMetadataFile(file string) (*TemplateMetadata, error)

ParseTemplateMetadataFile reads the template file, extracts the yml at the top into a struct. Valid templates should have --- marked yml eg --- myfield: asdf mysecondfield: 123 ---

func ReadOnDemandTemplate

func ReadOnDemandTemplate(data io.Reader, tpl *template.Template) (*template.Template, *TemplateMetadata, error)

type TwoWayCache

type TwoWayCache struct {
	// contains filtered or unexported fields

TwoWayCache is a cache where you can retrieve values by key as well as key by value this implementation is fully thread safe, for use in asynchronous template execution

func NewCache

func NewCache(duration time.Duration, capacity int) TwoWayCache

NewCache create a new instance, takes in the entry cache lifetime, and the default capacity. the cache will begin to expire items once the capacity is reached.

func (*TwoWayCache) Add

func (t *TwoWayCache) Add(key, val interface{})

Add a new key value pair to the cache

func (*TwoWayCache) Clear

func (t *TwoWayCache) Clear()

Clear completely resets the cache

func (*TwoWayCache) GetByKey

func (t *TwoWayCache) GetByKey(key interface{}) (interface{}, bool)

GetByKey retrieve the value by the supplied key

func (*TwoWayCache) GetByValue

func (t *TwoWayCache) GetByValue(val interface{}) (interface{}, bool)

GetByValue retrieve the key by the supplied value

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL