117 lines
2.3 KiB
Go
117 lines
2.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"git.ztn.sh/gwendolyn/docker-event-handler/events"
|
|
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"text/template"
|
|
|
|
"gopkg.in/ini.v1"
|
|
)
|
|
|
|
type Container struct {
|
|
Action []string
|
|
Name []string
|
|
Image []string
|
|
ID []string
|
|
Hostname []string
|
|
Label map[string]*string
|
|
Run *template.Template
|
|
}
|
|
|
|
func (h Container) Matches(event events.Event) bool {
|
|
e, ok := event.(events.Container)
|
|
if !ok {
|
|
return false
|
|
}
|
|
|
|
if !stringListMatches(h.Action, e.Action) {
|
|
return false
|
|
}
|
|
|
|
if !stringListMatches(h.ID, e.ID) {
|
|
return false
|
|
}
|
|
|
|
if e.Container == nil {
|
|
if len(h.Name) > 0 || len(h.Image) > 0 || len(h.Hostname) > 0 || len(h.Label) > 0 {
|
|
return false
|
|
}
|
|
} else {
|
|
if !stringListMatches(h.Name, e.Container.Name) {
|
|
return false
|
|
}
|
|
if !stringListMatches(h.Image, e.Container.Image) {
|
|
return false
|
|
}
|
|
if !stringListMatches(h.Hostname, e.Container.Config.Hostname) {
|
|
return false
|
|
}
|
|
if !labelsMatch(h.Label, e.Container.Config.Labels) {
|
|
return false
|
|
}
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func (h Container) Invoke(event events.Event) error {
|
|
e := event.(events.Container) // enforce that the event is a container events
|
|
return runTemplatedScript(h.Run, e)
|
|
}
|
|
|
|
func readContainerFromConfig(section *ini.Section) (Container, error) {
|
|
var handler Container
|
|
var err error
|
|
handler.Label = make(map[string]*string)
|
|
for _, key := range section.Keys() {
|
|
values := key.ValueWithShadows()
|
|
switch key.Name() {
|
|
case "Action":
|
|
handler.Action = values
|
|
break
|
|
case "Name":
|
|
handler.Name = values
|
|
break
|
|
case "Image":
|
|
handler.Image = values
|
|
break
|
|
case "ID":
|
|
handler.ID = values
|
|
break
|
|
case "Hostname":
|
|
handler.Hostname = values
|
|
break
|
|
case "Label":
|
|
for _, val := range values {
|
|
parts := strings.SplitN(val, "=", 2)
|
|
var k string
|
|
var v *string
|
|
if len(parts) == 2 {
|
|
k = parts[0]
|
|
v = &parts[1]
|
|
} else {
|
|
k = parts[0]
|
|
v = nil
|
|
}
|
|
handler.Label[k] = v
|
|
}
|
|
break
|
|
case "Run":
|
|
if len(values) > 1 {
|
|
return handler, errors.New(fmt.Sprintf("duplicate key %v in section %v", key.Name(), section.Name()))
|
|
}
|
|
handler.Run, err = template.New("Run").Parse(values[0])
|
|
if err != nil {
|
|
return handler, err
|
|
}
|
|
break
|
|
default:
|
|
return handler, errors.New(fmt.Sprintf("unknown key %v in section %v", key.Name(), section.Name()))
|
|
}
|
|
}
|
|
return handler, nil
|
|
}
|