github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/aagent/watchers/machineswatcher/matcher.go (about) 1 // Copyright (c) 2021-2022, R.I. Pienaar and the Choria Project contributors 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 5 package machines 6 7 import ( 8 "fmt" 9 "regexp" 10 11 iu "github.com/choria-io/go-choria/internal/util" 12 "github.com/expr-lang/expr" 13 ) 14 15 func (w *Watcher) identityMatchFunc(re string) bool { 16 r, err := regexp.Compile(re) 17 if err != nil { 18 w.Errorf("Could not process identity match: %s: %s", re, err) 19 return false 20 } 21 22 return r.MatchString(w.machine.Identity()) 23 } 24 25 func (w *Watcher) isNodeMatch(machine *ManagedMachine) (bool, error) { 26 if machine.Matcher == "" { 27 return true, nil 28 } 29 30 env := map[string]any{ 31 "identity": w.identityMatchFunc, 32 "has_file": iu.FileExist, 33 "has_directory": iu.FileIsDir, 34 "has_command": iu.IsExecutableInPath, 35 } 36 37 execEnv := expr.Env(env) 38 prog, err := expr.Compile(machine.Matcher, execEnv, expr.AsBool()) 39 if err != nil { 40 return false, err 41 } 42 43 res, err := expr.Run(prog, env) 44 if err != nil { 45 return false, err 46 } 47 48 b, ok := res.(bool) 49 if !ok { 50 return false, fmt.Errorf("match was non boolean") 51 } 52 53 return b, nil 54 }