]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - cmd/safcm/sync.go
4a82ca3b906464f8ce58f652f4abf9afbbf71cb8
[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         "log"
24         "os"
25         "os/signal"
26         "sort"
27         "strings"
28         "sync"
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/rpc"
35 )
36
37 type Sync struct {
38         host *config.Host
39
40         config    *config.Config      // global configuration
41         allHosts  *config.Hosts       // known hosts
42         allGroups map[string][]string // known groups
43
44         events chan<- Event // all events generated by/for this host
45
46         isTTY bool
47 }
48
49 type Event struct {
50         Host *config.Host
51
52         // Only one of Error, Log and ConnEvent is set in a single event
53         Error     error
54         Log       Log
55         ConnEvent rpc.ConnEvent
56
57         Escaped bool // true if untrusted input is already escaped
58 }
59
60 type Log struct {
61         Level safcm.LogLevel
62         Text  string
63 }
64
65 func MainSync(args []string) error {
66         flag.Usage = func() {
67                 fmt.Fprintf(os.Stderr,
68                         "usage: %s sync [<options>] <host|group...>\n",
69                         args[0])
70                 flag.PrintDefaults()
71         }
72
73         optionDryRun := flag.Bool("n", false,
74                 "dry-run, show diff but don't perform any changes")
75         optionQuiet := flag.Bool("q", false,
76                 "hide successful, non-trigger commands with no output from host changes listing")
77         optionLog := flag.String("log", "info", "set log `level`; "+
78                 "levels: error, info, verbose, debug, debug2, debug3")
79         optionSshConfig := flag.String("sshconfig", "",
80                 "`path` to ssh configuration file; used for tests")
81
82         flag.CommandLine.Parse(args[2:])
83
84         var level safcm.LogLevel
85         switch *optionLog {
86         case "error":
87                 level = safcm.LogError
88         case "info":
89                 level = safcm.LogInfo
90         case "verbose":
91                 level = safcm.LogVerbose
92         case "debug":
93                 level = safcm.LogDebug
94         case "debug2":
95                 level = safcm.LogDebug2
96         case "debug3":
97                 level = safcm.LogDebug3
98         default:
99                 return fmt.Errorf("invalid -log value %q", *optionLog)
100         }
101
102         names := flag.Args()
103         if len(names) == 0 {
104                 flag.Usage()
105                 os.Exit(1)
106         }
107
108         cfg, allHosts, allGroups, err := LoadBaseFiles()
109         if err != nil {
110                 return err
111         }
112         cfg.DryRun = *optionDryRun
113         cfg.Quiet = *optionQuiet
114         cfg.LogLevel = level
115         cfg.SshConfig = *optionSshConfig
116
117         toSync, err := hostsToSync(names, allHosts, allGroups)
118         if err != nil {
119                 return err
120         }
121         if len(toSync) == 0 {
122                 return fmt.Errorf("no hosts found")
123         }
124
125         isTTY := term.IsTerminal(int(os.Stdout.Fd())) &&
126                 term.IsTerminal(int(os.Stderr.Fd()))
127
128         done := make(chan bool)
129         // Collect events from all hosts and print them
130         events := make(chan Event)
131         go func() {
132                 var failed bool
133                 for {
134                         x := <-events
135                         if x.Host == nil {
136                                 break
137                         }
138                         logEvent(x, cfg.LogLevel, isTTY, &failed)
139                 }
140                 done <- failed
141         }()
142
143         hostsLeft := make(map[string]bool)
144         for _, x := range toSync {
145                 hostsLeft[x.Name] = true
146         }
147         var hostsLeftMutex sync.Mutex // protects hostsLeft
148
149         // Show unfinished hosts on Ctrl-C
150         sigint := make(chan os.Signal, 1)   // buffered for Notify()
151         signal.Notify(sigint, os.Interrupt) // = SIGINT = Ctrl-C
152         go func() {
153                 // Running `ssh` processes get killed by SIGINT which is sent
154                 // to all processes
155
156                 <-sigint
157                 log.Print("Received SIGINT, aborting ...")
158
159                 // Print all queued events
160                 events <- Event{} // poison pill
161                 <-done
162                 // "races" with <-done in the main function and will hang here
163                 // if the other is faster. This is fine because then all hosts
164                 // were synced successfully.
165
166                 hostsLeftMutex.Lock()
167                 var hosts []string
168                 for x := range hostsLeft {
169                         hosts = append(hosts, x)
170                 }
171                 sort.Strings(hosts)
172                 log.Fatalf("Failed to sync %s", strings.Join(hosts, ", "))
173         }()
174
175         // Sync all hosts concurrently
176         var wg sync.WaitGroup
177         for _, x := range toSync {
178                 x := x
179
180                 // Once in sync.Host() and once in the go func below
181                 wg.Add(2)
182
183                 go func() {
184                         sync := Sync{
185                                 host:      x,
186                                 config:    cfg,
187                                 allHosts:  allHosts,
188                                 allGroups: allGroups,
189                                 events:    events,
190                                 isTTY:     isTTY,
191                         }
192                         err := sync.Host(&wg)
193                         if err != nil {
194                                 events <- Event{
195                                         Host:  x,
196                                         Error: err,
197                                 }
198                         }
199                         wg.Done()
200
201                         hostsLeftMutex.Lock()
202                         defer hostsLeftMutex.Unlock()
203                         delete(hostsLeft, x.Name)
204                 }()
205         }
206
207         wg.Wait()
208         events <- Event{} // poison pill
209         failed := <-done
210
211         if failed {
212                 // Exit instead of returning an error to prevent an extra log
213                 // message from main()
214                 os.Exit(1)
215         }
216         return nil
217 }
218
219 // hostsToSync returns the list of hosts to sync based on the command line
220 // arguments.
221 //
222 // Full host and group matches are required to prevent unexpected behavior. No
223 // arguments does not expand to all hosts to prevent accidents; "all" can be
224 // used instead. Both host and group names are permitted as these are unique.
225 //
226 // TODO: Add option to permit partial/glob matches
227 func hostsToSync(names []string, allHosts *config.Hosts,
228         allGroups map[string][]string) ([]*config.Host, error) {
229
230         detectedMap := config.TransitivelyDetectedGroups(allGroups)
231
232         const detectedErr = `
233
234 Groups depending on "detected" groups cannot be used to select hosts as these
235 are only available after the hosts were contacted.
236 `
237
238         nameMap := make(map[string]bool)
239         for _, x := range names {
240                 if detectedMap[x] {
241                         return nil, fmt.Errorf(
242                                 "group %q depends on \"detected\" groups%s",
243                                 x, detectedErr)
244                 }
245                 nameMap[x] = true
246         }
247         nameMatched := make(map[string]bool)
248         // To detect typos we must check all given names but one host can be
249         // matched by multiple names (e.g. two groups with overlapping hosts)
250         hostAdded := make(map[string]bool)
251
252         var res []*config.Host
253         for _, host := range allHosts.List {
254                 if nameMap[host.Name] {
255                         res = append(res, host)
256                         hostAdded[host.Name] = true
257                         nameMatched[host.Name] = true
258                 }
259
260                 groups, err := config.ResolveHostGroups(host.Name,
261                         allGroups, nil)
262                 if err != nil {
263                         return nil, err
264                 }
265                 for _, x := range groups {
266                         if nameMap[x] {
267                                 if !hostAdded[host.Name] {
268                                         res = append(res, host)
269                                         hostAdded[host.Name] = true
270                                 }
271                                 nameMatched[x] = true
272                         }
273                 }
274         }
275
276         // Warn about unmatched names to detect typos
277         if len(nameMap) != len(nameMatched) {
278                 var unmatched []string
279                 for x := range nameMap {
280                         if !nameMatched[x] {
281                                 unmatched = append(unmatched,
282                                         fmt.Sprintf("%q", x))
283                         }
284                 }
285                 sort.Strings(unmatched)
286                 return nil, fmt.Errorf("hosts/groups not found: %s",
287                         strings.Join(unmatched, " "))
288         }
289
290         return res, nil
291 }
292
293 func logEvent(x Event, level safcm.LogLevel, isTTY bool, failed *bool) {
294         // We have multiple event sources so this is somewhat ugly.
295         var prefix, data string
296         var color Color
297         if x.Error != nil {
298                 prefix = "[error]"
299                 data = x.Error.Error()
300                 color = ColorRed
301                 // We logged an error, tell the caller
302                 *failed = true
303         } else if x.Log.Level != 0 {
304                 // LogError and LogDebug3 should not occur here
305                 switch x.Log.Level {
306                 case safcm.LogInfo:
307                         prefix = "[info]"
308                 case safcm.LogVerbose:
309                         prefix = "[verbose]"
310                 case safcm.LogDebug:
311                         prefix = "[debug]"
312                 case safcm.LogDebug2:
313                         prefix = "[debug2]"
314                 default:
315                         prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
316                         color = ColorRed
317                 }
318                 data = x.Log.Text
319         } else {
320                 switch x.ConnEvent.Type {
321                 case rpc.ConnEventStderr:
322                         prefix = "[stderr]"
323                 case rpc.ConnEventDebug:
324                         prefix = "[debug3]"
325                 case rpc.ConnEventUpload:
326                         if level < safcm.LogInfo {
327                                 return
328                         }
329                         prefix = "[info]"
330                         x.ConnEvent.Data = "remote helper upload in progress"
331                 default:
332                         prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
333                         color = ColorRed
334                 }
335                 data = x.ConnEvent.Data
336         }
337
338         host := x.Host.Name
339         if color != 0 {
340                 host = ColorString(isTTY, color, host)
341         }
342         // Make sure to escape control characters to prevent terminal
343         // injection attacks
344         if !x.Escaped {
345                 data = EscapeControlCharacters(isTTY, data)
346         }
347         log.Printf("%-9s [%s] %s", prefix, host, data)
348 }
349
350 func (s *Sync) Host(wg *sync.WaitGroup) error {
351         conn := rpc.NewConn(s.config.LogLevel >= safcm.LogDebug3)
352         // Pass all connection events to main loop
353         go func() {
354                 for {
355                         x, ok := <-conn.Events
356                         if !ok {
357                                 break
358                         }
359                         s.events <- Event{
360                                 Host:      s.host,
361                                 ConnEvent: x,
362                         }
363                 }
364                 wg.Done()
365         }()
366
367         // Connect to remote host
368         err := conn.DialSSH(s.host.SshUser, s.host.Name, s.config.SshConfig)
369         if err != nil {
370                 return err
371         }
372         defer conn.Kill()
373
374         // Collect information about remote host
375         detectedGroups, err := s.hostInfo(conn)
376         if err != nil {
377                 return err
378         }
379
380         // Sync state to remote host
381         err = s.hostSync(conn, detectedGroups)
382         if err != nil {
383                 return err
384         }
385
386         // Terminate connection to remote host
387         err = conn.Send(safcm.MsgQuitReq{})
388         if err != nil {
389                 return err
390         }
391         _, err = conn.Recv()
392         if err != nil {
393                 return err
394         }
395         err = conn.Wait()
396         if err != nil {
397                 return err
398         }
399
400         return nil
401 }
402
403 func (s *Sync) log(level safcm.LogLevel, escaped bool, msg string) {
404         if s.config.LogLevel < level {
405                 return
406         }
407         s.events <- Event{
408                 Host: s.host,
409                 Log: Log{
410                         Level: level,
411                         Text:  msg,
412                 },
413                 Escaped: escaped,
414         }
415 }
416 func (s *Sync) logDebugf(format string, a ...interface{}) {
417         s.log(safcm.LogDebug, false, fmt.Sprintf(format, a...))
418 }
419 func (s *Sync) logVerbosef(format string, a ...interface{}) {
420         s.log(safcm.LogVerbose, false, fmt.Sprintf(format, a...))
421 }
422
423 // sendRecv sends a message over conn and waits for the response. Any MsgLog
424 // messages received before the final (non MsgLog) response are passed to
425 // s.log.
426 func (s *Sync) sendRecv(conn *rpc.Conn, msg safcm.Msg) (safcm.Msg, error) {
427         err := conn.Send(msg)
428         if err != nil {
429                 return nil, err
430         }
431         for {
432                 x, err := conn.Recv()
433                 if err != nil {
434                         return nil, err
435                 }
436                 log, ok := x.(safcm.MsgLog)
437                 if ok {
438                         s.log(log.Level, false, log.Text)
439                         continue
440                 }
441                 return x, nil
442         }
443 }