]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - cmd/safcm/sync.go
safcm: move sync_changes.go and term.go to frontend package
[safcm/safcm.git] / cmd / safcm / sync.go
1 // "sync" sub-command: sync data to remote hosts
2
3 // Copyright (C) 2021  Simon Ruderich
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 package main
19
20 import (
21         "flag"
22         "fmt"
23         "io/fs"
24         "log"
25         "os"
26         "runtime"
27         "sort"
28         "strings"
29
30         "golang.org/x/term"
31
32         "ruderich.org/simon/safcm"
33         "ruderich.org/simon/safcm/cmd/safcm/config"
34         "ruderich.org/simon/safcm/frontend"
35         "ruderich.org/simon/safcm/rpc"
36 )
37
38 type Sync struct {
39         host *config.Host
40
41         config    *config.Config      // global configuration
42         allHosts  *config.Hosts       // known hosts
43         allGroups map[string][]string // known groups
44
45         isTTY bool
46
47         logFunc func(level safcm.LogLevel, escaped bool, msg string)
48 }
49
50 func MainSync(args []string) error {
51         flag.Usage = func() {
52                 fmt.Fprintf(os.Stderr,
53                         "usage: %s sync [<options>] <host|group...>\n",
54                         args[0])
55                 flag.PrintDefaults()
56         }
57
58         optionDryRun := flag.Bool("n", false,
59                 "dry-run, show diff but don't perform any changes")
60         optionQuiet := flag.Bool("q", false,
61                 "hide successful, non-trigger commands with no output from host changes listing")
62         optionLog := flag.String("log", "info", "set log `level`; "+
63                 "levels: error, info, verbose, debug, debug2, debug3")
64         optionSshConfig := flag.String("sshconfig", "",
65                 "`path` to ssh configuration file; used for tests")
66
67         flag.CommandLine.Parse(args[2:])
68
69         level, err := safcm.ParseLogLevel(*optionLog)
70         if err != nil {
71                 return fmt.Errorf("-log: %v", err)
72         }
73
74         names := flag.Args()
75         if len(names) == 0 {
76                 flag.Usage()
77                 os.Exit(1)
78         }
79
80         if runtime.GOOS == "windows" {
81                 log.Print("WARNING: Windows support is experimental!")
82         }
83
84         cfg, allHosts, allGroups, err := LoadBaseFiles()
85         if err != nil {
86                 return err
87         }
88         cfg.DryRun = *optionDryRun
89         cfg.Quiet = *optionQuiet
90         cfg.LogLevel = level
91         cfg.SshConfig = *optionSshConfig
92
93         toSync, err := hostsToSync(names, allHosts, allGroups)
94         if err != nil {
95                 return err
96         }
97         if len(toSync) == 0 {
98                 return fmt.Errorf("no hosts found")
99         }
100
101         isTTY := term.IsTerminal(int(os.Stdout.Fd())) &&
102                 term.IsTerminal(int(os.Stderr.Fd()))
103
104         loop := &frontend.Loop{
105                 DebugConn: cfg.LogLevel >= safcm.LogDebug3,
106                 LogEventFunc: func(x frontend.Event, failed *bool) {
107                         logEvent(x, cfg.LogLevel, isTTY, failed)
108                 },
109                 SyncHostFunc: func(conn *rpc.Conn, host frontend.Host) error {
110                         return host.(*Sync).Host(conn)
111                 },
112         }
113
114         var hosts []frontend.Host
115         for _, x := range toSync {
116                 s := &Sync{
117                         host:      x,
118                         config:    cfg,
119                         allHosts:  allHosts,
120                         allGroups: allGroups,
121                         isTTY:     isTTY,
122                 }
123                 s.logFunc = func(level safcm.LogLevel, escaped bool,
124                         msg string) {
125                         loop.Log(s, level, escaped, msg)
126                 }
127                 hosts = append(hosts, s)
128         }
129
130         succ := loop.Run(hosts)
131
132         if !succ {
133                 // Exit instead of returning an error to prevent an extra log
134                 // message from main()
135                 os.Exit(1)
136         }
137         return nil
138 }
139
140 // hostsToSync returns the list of hosts to sync based on the command line
141 // arguments.
142 //
143 // Full host and group matches are required to prevent unexpected behavior. No
144 // arguments does not expand to all hosts to prevent accidents; "all" can be
145 // used instead. Both host and group names are permitted as these are unique.
146 //
147 // TODO: Add option to permit partial/glob matches
148 func hostsToSync(names []string, allHosts *config.Hosts,
149         allGroups map[string][]string) ([]*config.Host, error) {
150
151         detectedMap := config.TransitivelyDetectedGroups(allGroups)
152
153         const detectedErr = `
154
155 Groups depending on "detected" groups cannot be used to select hosts as these
156 are only available after the hosts were contacted.
157 `
158
159         nameMap := make(map[string]bool)
160         for _, x := range names {
161                 if detectedMap[x] {
162                         return nil, fmt.Errorf(
163                                 "group %q depends on \"detected\" groups%s",
164                                 x, detectedErr)
165                 }
166                 nameMap[x] = true
167         }
168         nameMatched := make(map[string]bool)
169         // To detect typos we must check all given names but one host can be
170         // matched by multiple names (e.g. two groups with overlapping hosts)
171         hostAdded := make(map[string]bool)
172
173         var res []*config.Host
174         for _, host := range allHosts.List {
175                 if nameMap[host.Name] {
176                         res = append(res, host)
177                         hostAdded[host.Name] = true
178                         nameMatched[host.Name] = true
179                 }
180
181                 groups, err := config.ResolveHostGroups(host.Name,
182                         allGroups, nil)
183                 if err != nil {
184                         return nil, err
185                 }
186                 for _, x := range groups {
187                         if nameMap[x] {
188                                 if !hostAdded[host.Name] {
189                                         res = append(res, host)
190                                         hostAdded[host.Name] = true
191                                 }
192                                 nameMatched[x] = true
193                         }
194                 }
195         }
196
197         // Warn about unmatched names to detect typos
198         if len(nameMap) != len(nameMatched) {
199                 var unmatched []string
200                 for x := range nameMap {
201                         if !nameMatched[x] {
202                                 unmatched = append(unmatched,
203                                         fmt.Sprintf("%q", x))
204                         }
205                 }
206                 sort.Strings(unmatched)
207                 return nil, fmt.Errorf("hosts/groups not found: %s",
208                         strings.Join(unmatched, " "))
209         }
210
211         return res, nil
212 }
213
214 func logEvent(x frontend.Event, level safcm.LogLevel, isTTY bool, failed *bool) {
215         // We have multiple event sources so this is somewhat ugly.
216         var prefix, data string
217         var color frontend.Color
218         if x.Error != nil {
219                 prefix = "[error]"
220                 data = x.Error.Error()
221                 color = frontend.ColorRed
222                 // We logged an error, tell the caller
223                 *failed = true
224         } else if x.Log.Level != 0 {
225                 if level < x.Log.Level {
226                         return
227                 }
228                 // LogError and LogDebug3 should not occur here
229                 switch x.Log.Level {
230                 case safcm.LogInfo:
231                         prefix = "[info]"
232                 case safcm.LogVerbose:
233                         prefix = "[verbose]"
234                 case safcm.LogDebug:
235                         prefix = "[debug]"
236                 case safcm.LogDebug2:
237                         prefix = "[debug2]"
238                 default:
239                         prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
240                         color = frontend.ColorRed
241                 }
242                 data = x.Log.Text
243         } else {
244                 switch x.ConnEvent.Type {
245                 case rpc.ConnEventStderr:
246                         prefix = "[stderr]"
247                 case rpc.ConnEventDebug:
248                         prefix = "[debug3]"
249                 case rpc.ConnEventUpload:
250                         if level < safcm.LogInfo {
251                                 return
252                         }
253                         prefix = "[info]"
254                         x.ConnEvent.Data = "remote helper upload in progress"
255                 default:
256                         prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
257                         color = frontend.ColorRed
258                 }
259                 data = x.ConnEvent.Data
260         }
261
262         host := x.Host.Name()
263         if color != 0 {
264                 host = frontend.ColorString(isTTY, color, host)
265         }
266         // Make sure to escape control characters to prevent terminal
267         // injection attacks
268         if !x.Escaped {
269                 data = frontend.EscapeControlCharacters(isTTY, data)
270         }
271         log.Printf("%-9s [%s] %s", prefix, host, data)
272 }
273
274 func (s *Sync) Name() string {
275         return s.host.Name
276 }
277
278 func (s *Sync) Dial(conn *rpc.Conn) error {
279         helpers, err := fs.Sub(RemoteHelpers, "remote")
280         if err != nil {
281                 return err
282         }
283
284         // Connect to remote host
285         user := s.host.SshUser
286         if user == "" {
287                 user = s.config.SshUser
288         }
289         return conn.DialSSH(rpc.SSHConfig{
290                 Host:          s.host.Name,
291                 User:          user,
292                 SshConfig:     s.config.SshConfig,
293                 RemoteHelpers: helpers,
294         })
295 }
296
297 func (s *Sync) Host(conn *rpc.Conn) error {
298         // Collect information about remote host
299         detectedGroups, err := s.hostInfo(conn)
300         if err != nil {
301                 return err
302         }
303
304         // Sync state to remote host
305         err = s.hostSync(conn, detectedGroups)
306         if err != nil {
307                 return err
308         }
309
310         return nil
311 }
312
313 func (s *Sync) log(level safcm.LogLevel, escaped bool, msg string) {
314         s.logFunc(level, escaped, msg)
315 }
316 func (s *Sync) logDebugf(format string, a ...interface{}) {
317         s.log(safcm.LogDebug, false, fmt.Sprintf(format, a...))
318 }
319 func (s *Sync) logVerbosef(format string, a ...interface{}) {
320         s.log(safcm.LogVerbose, false, fmt.Sprintf(format, a...))
321 }
322
323 // sendRecv sends a message over conn and waits for the response. Any MsgLog
324 // messages received before the final (non MsgLog) response are passed to
325 // s.log.
326 func (s *Sync) sendRecv(conn *rpc.Conn, msg safcm.Msg) (safcm.Msg, error) {
327         err := conn.Send(msg)
328         if err != nil {
329                 return nil, err
330         }
331         for {
332                 x, err := conn.Recv()
333                 if err != nil {
334                         return nil, err
335                 }
336                 log, ok := x.(safcm.MsgLog)
337                 if ok {
338                         s.log(log.Level, false, log.Text)
339                         continue
340                 }
341                 return x, nil
342         }
343 }