]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - cmd/safcm/sync.go
6358f0cb60feb4570cc5dae1a9e0e24bce6a69ed
[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
127         done := make(chan bool)
128         // Collect events from all hosts and print them
129         events := make(chan Event)
130         go func() {
131                 var failed bool
132                 for {
133                         x := <-events
134                         if x.Host == nil {
135                                 break
136                         }
137                         logEvent(x, cfg.LogLevel, isTTY, &failed)
138                 }
139                 done <- failed
140         }()
141
142         hostsLeft := make(map[string]bool)
143         for _, x := range toSync {
144                 hostsLeft[x.Name] = true
145         }
146         var hostsLeftMutex sync.Mutex // protects hostsLeft
147
148         // Show unfinished hosts on Ctrl-C
149         sigint := make(chan os.Signal, 1)   // buffered for Notify()
150         signal.Notify(sigint, os.Interrupt) // = SIGINT = Ctrl-C
151         go func() {
152                 // Running `ssh` processes get killed by SIGINT which is sent
153                 // to all processes
154
155                 <-sigint
156                 log.Print("Received SIGINT, aborting ...")
157
158                 // Print all queued events
159                 events <- Event{} // poison pill
160                 <-done
161                 // "races" with <-done in the main function and will hang here
162                 // if the other is faster. This is fine because then all hosts
163                 // were synced successfully.
164
165                 hostsLeftMutex.Lock()
166                 var hosts []string
167                 for x := range hostsLeft {
168                         hosts = append(hosts, x)
169                 }
170                 sort.Strings(hosts)
171                 log.Fatalf("Failed to sync %s", strings.Join(hosts, ", "))
172         }()
173
174         // Sync all hosts concurrently
175         var wg sync.WaitGroup
176         for _, x := range toSync {
177                 x := x
178
179                 // Once in sync.Host() and once in the go func below
180                 wg.Add(2)
181
182                 go func() {
183                         sync := Sync{
184                                 host:      x,
185                                 config:    cfg,
186                                 allHosts:  allHosts,
187                                 allGroups: allGroups,
188                                 events:    events,
189                                 isTTY:     isTTY,
190                         }
191                         err := sync.Host(&wg)
192                         if err != nil {
193                                 events <- Event{
194                                         Host:  x,
195                                         Error: err,
196                                 }
197                         }
198                         wg.Done()
199
200                         hostsLeftMutex.Lock()
201                         defer hostsLeftMutex.Unlock()
202                         delete(hostsLeft, x.Name)
203                 }()
204         }
205
206         wg.Wait()
207         events <- Event{} // poison pill
208         failed := <-done
209
210         if failed {
211                 // Exit instead of returning an error to prevent an extra log
212                 // message from main()
213                 os.Exit(1)
214         }
215         return nil
216 }
217
218 // hostsToSync returns the list of hosts to sync based on the command line
219 // arguments.
220 //
221 // Full host and group matches are required to prevent unexpected behavior. No
222 // arguments does not expand to all hosts to prevent accidents; "all" can be
223 // used instead. Both host and group names are permitted as these are unique.
224 //
225 // TODO: Add option to permit partial/glob matches
226 func hostsToSync(names []string, allHosts *config.Hosts,
227         allGroups map[string][]string) ([]*config.Host, error) {
228
229         detectedMap := config.TransitivelyDetectedGroups(allGroups)
230
231         const detectedErr = `
232
233 Groups depending on "detected" groups cannot be used to select hosts as these
234 are only available after the hosts were contacted.
235 `
236
237         nameMap := make(map[string]bool)
238         for _, x := range names {
239                 if detectedMap[x] {
240                         return nil, fmt.Errorf(
241                                 "group %q depends on \"detected\" groups%s",
242                                 x, detectedErr)
243                 }
244                 nameMap[x] = true
245         }
246         nameMatched := make(map[string]bool)
247         // To detect typos we must check all given names but one host can be
248         // matched by multiple names (e.g. two groups with overlapping hosts)
249         hostMatched := make(map[string]bool)
250
251         var res []*config.Host
252         for _, host := range allHosts.List {
253                 if nameMap[host.Name] {
254                         res = append(res, host)
255                         hostMatched[host.Name] = true
256                         nameMatched[host.Name] = true
257                 }
258
259                 groups, err := config.ResolveHostGroups(host.Name,
260                         allGroups, nil)
261                 if err != nil {
262                         return nil, err
263                 }
264                 for _, x := range groups {
265                         if nameMap[x] {
266                                 if !hostMatched[host.Name] {
267                                         res = append(res, host)
268                                         hostMatched[host.Name] = true
269                                 }
270                                 nameMatched[x] = true
271                         }
272                 }
273         }
274
275         // Warn about unmatched names to detect typos
276         if len(nameMap) != len(nameMatched) {
277                 var unmatched []string
278                 for x := range nameMap {
279                         if !nameMatched[x] {
280                                 unmatched = append(unmatched,
281                                         fmt.Sprintf("%q", x))
282                         }
283                 }
284                 sort.Strings(unmatched)
285                 return nil, fmt.Errorf("hosts/groups not found: %s",
286                         strings.Join(unmatched, " "))
287         }
288
289         return res, nil
290 }
291
292 func logEvent(x Event, level safcm.LogLevel, isTTY bool, failed *bool) {
293         // We have multiple event sources so this is somewhat ugly.
294         var prefix, data string
295         var color Color
296         if x.Error != nil {
297                 prefix = "[error]"
298                 data = x.Error.Error()
299                 color = ColorRed
300                 // We logged an error, tell the caller
301                 *failed = true
302         } else if x.Log.Level != 0 {
303                 // LogError and LogDebug3 should not occur here
304                 switch x.Log.Level {
305                 case safcm.LogInfo:
306                         prefix = "[info]"
307                 case safcm.LogVerbose:
308                         prefix = "[verbose]"
309                 case safcm.LogDebug:
310                         prefix = "[debug]"
311                 case safcm.LogDebug2:
312                         prefix = "[debug2]"
313                 default:
314                         prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
315                         color = ColorRed
316                 }
317                 data = x.Log.Text
318         } else {
319                 switch x.ConnEvent.Type {
320                 case rpc.ConnEventStderr:
321                         prefix = "[stderr]"
322                 case rpc.ConnEventDebug:
323                         prefix = "[debug3]"
324                 case rpc.ConnEventUpload:
325                         if level < safcm.LogInfo {
326                                 return
327                         }
328                         prefix = "[info]"
329                         x.ConnEvent.Data = "remote helper upload in progress"
330                 default:
331                         prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
332                         color = ColorRed
333                 }
334                 data = x.ConnEvent.Data
335         }
336
337         host := x.Host.Name
338         if color != 0 {
339                 host = ColorString(isTTY, color, host)
340         }
341         // Make sure to escape control characters to prevent terminal
342         // injection attacks
343         if !x.Escaped {
344                 data = EscapeControlCharacters(isTTY, data)
345         }
346         log.Printf("%-9s [%s] %s", prefix, host, data)
347 }
348
349 func (s *Sync) Host(wg *sync.WaitGroup) error {
350         conn := rpc.NewConn(s.config.LogLevel >= safcm.LogDebug3)
351         // Pass all connection events to main loop
352         go func() {
353                 for {
354                         x, ok := <-conn.Events
355                         if !ok {
356                                 break
357                         }
358                         s.events <- Event{
359                                 Host:      s.host,
360                                 ConnEvent: x,
361                         }
362                 }
363                 wg.Done()
364         }()
365
366         // Connect to remote host
367         err := conn.DialSSH(s.host.SshUser, s.host.Name, s.config.SshConfig)
368         if err != nil {
369                 return err
370         }
371         defer conn.Kill()
372
373         // Collect information about remote host
374         detectedGroups, err := s.hostInfo(conn)
375         if err != nil {
376                 return err
377         }
378
379         // Sync state to remote host
380         err = s.hostSync(conn, detectedGroups)
381         if err != nil {
382                 return err
383         }
384
385         // Terminate connection to remote host
386         err = conn.Send(safcm.MsgQuitReq{})
387         if err != nil {
388                 return err
389         }
390         _, err = conn.Recv()
391         if err != nil {
392                 return err
393         }
394         err = conn.Wait()
395         if err != nil {
396                 return err
397         }
398
399         return nil
400 }
401
402 func (s *Sync) logf(level safcm.LogLevel, escaped bool,
403         format string, a ...interface{}) {
404
405         if s.config.LogLevel < level {
406                 return
407         }
408         s.events <- Event{
409                 Host: s.host,
410                 Log: Log{
411                         Level: level,
412                         Text:  fmt.Sprintf(format, a...),
413                 },
414                 Escaped: escaped,
415         }
416 }
417 func (s *Sync) logDebugf(format string, a ...interface{}) {
418         s.logf(safcm.LogDebug, false, format, a...)
419 }
420 func (s *Sync) logVerbosef(format string, a ...interface{}) {
421         s.logf(safcm.LogVerbose, false, format, a...)
422 }
423
424 // sendRecv sends a message over conn and waits for the response. Any MsgLog
425 // messages received before the final (non MsgLog) response are passed to
426 // s.log.
427 func (s *Sync) sendRecv(conn *rpc.Conn, msg safcm.Msg) (safcm.Msg, error) {
428         err := conn.Send(msg)
429         if err != nil {
430                 return nil, err
431         }
432         for {
433                 x, err := conn.Recv()
434                 if err != nil {
435                         return nil, err
436                 }
437                 log, ok := x.(safcm.MsgLog)
438                 if ok {
439                         s.logf(log.Level, false, "%s", log.Text)
440                         continue
441                 }
442                 return x, nil
443         }
444 }