1 // "sync" sub-command: sync data to remote hosts
3 // Copyright (C) 2021 Simon Ruderich
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.
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.
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/>.
32 "ruderich.org/simon/safcm"
33 "ruderich.org/simon/safcm/cmd/safcm/config"
34 "ruderich.org/simon/safcm/rpc"
40 config *config.Config // global configuration
41 allHosts *config.Hosts // known hosts
42 allGroups map[string][]string // known groups
44 events chan<- Event // all events generated by/for this host
52 // Only one of Error, Log and ConnEvent is set in a single event
55 ConnEvent rpc.ConnEvent
57 Escaped bool // true if untrusted input is already escaped
65 func MainSync(args []string) error {
67 fmt.Fprintf(os.Stderr,
68 "usage: %s sync [<options>] <host|group...>\n",
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")
82 flag.CommandLine.Parse(args[2:])
84 var level safcm.LogLevel
87 level = safcm.LogError
91 level = safcm.LogVerbose
93 level = safcm.LogDebug
95 level = safcm.LogDebug2
97 level = safcm.LogDebug3
99 return fmt.Errorf("invalid -log value %q", *optionLog)
108 cfg, allHosts, allGroups, err := LoadBaseFiles()
112 cfg.DryRun = *optionDryRun
113 cfg.Quiet = *optionQuiet
115 cfg.SshConfig = *optionSshConfig
117 toSync, err := hostsToSync(names, allHosts, allGroups)
121 if len(toSync) == 0 {
122 return fmt.Errorf("no hosts found")
125 isTTY := term.IsTerminal(int(os.Stdout.Fd())) &&
126 term.IsTerminal(int(os.Stderr.Fd()))
128 done := make(chan bool)
129 // Collect events from all hosts and print them
130 events := make(chan Event)
138 logEvent(x, cfg.LogLevel, isTTY, &failed)
143 hostsLeft := make(map[string]bool)
144 for _, x := range toSync {
145 hostsLeft[x.Name] = true
147 var hostsLeftMutex sync.Mutex // protects hostsLeft
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
153 // Running `ssh` processes get killed by SIGINT which is sent
157 log.Print("Received SIGINT, aborting ...")
159 // Print all queued events
160 events <- Event{} // poison pill
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.
166 hostsLeftMutex.Lock()
168 for x := range hostsLeft {
169 hosts = append(hosts, x)
172 log.Fatalf("Failed to sync %s", strings.Join(hosts, ", "))
175 // Sync all hosts concurrently
176 var wg sync.WaitGroup
177 for _, x := range toSync {
180 // Once in sync.Host() and once in the go func below
188 allGroups: allGroups,
192 err := sync.Host(&wg)
201 hostsLeftMutex.Lock()
202 defer hostsLeftMutex.Unlock()
203 delete(hostsLeft, x.Name)
208 events <- Event{} // poison pill
212 // Exit instead of returning an error to prevent an extra log
213 // message from main()
219 // hostsToSync returns the list of hosts to sync based on the command line
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.
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) {
230 detectedMap := config.TransitivelyDetectedGroups(allGroups)
232 const detectedErr = `
234 Groups depending on "detected" groups cannot be used to select hosts as these
235 are only available after the hosts were contacted.
238 nameMap := make(map[string]bool)
239 for _, x := range names {
241 return nil, fmt.Errorf(
242 "group %q depends on \"detected\" groups%s",
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)
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
260 groups, err := config.ResolveHostGroups(host.Name,
265 for _, x := range groups {
267 if !hostAdded[host.Name] {
268 res = append(res, host)
269 hostAdded[host.Name] = true
271 nameMatched[x] = true
276 // Warn about unmatched names to detect typos
277 if len(nameMap) != len(nameMatched) {
278 var unmatched []string
279 for x := range nameMap {
281 unmatched = append(unmatched,
282 fmt.Sprintf("%q", x))
285 sort.Strings(unmatched)
286 return nil, fmt.Errorf("hosts/groups not found: %s",
287 strings.Join(unmatched, " "))
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
299 data = x.Error.Error()
301 // We logged an error, tell the caller
303 } else if x.Log.Level != 0 {
304 // LogError and LogDebug3 should not occur here
308 case safcm.LogVerbose:
312 case safcm.LogDebug2:
315 prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
320 switch x.ConnEvent.Type {
321 case rpc.ConnEventStderr:
323 case rpc.ConnEventDebug:
325 case rpc.ConnEventUpload:
326 if level < safcm.LogInfo {
330 x.ConnEvent.Data = "remote helper upload in progress"
332 prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
335 data = x.ConnEvent.Data
340 host = ColorString(isTTY, color, host)
342 // Make sure to escape control characters to prevent terminal
345 data = EscapeControlCharacters(isTTY, data)
347 log.Printf("%-9s [%s] %s", prefix, host, data)
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
355 x, ok := <-conn.Events
367 // Connect to remote host
368 err := conn.DialSSH(s.host.SshUser, s.host.Name, s.config.SshConfig)
374 // Collect information about remote host
375 detectedGroups, err := s.hostInfo(conn)
380 // Sync state to remote host
381 err = s.hostSync(conn, detectedGroups)
386 // Terminate connection to remote host
387 err = conn.Send(safcm.MsgQuitReq{})
403 func (s *Sync) logf(level safcm.LogLevel, escaped bool,
404 format string, a ...interface{}) {
406 if s.config.LogLevel < level {
413 Text: fmt.Sprintf(format, a...),
418 func (s *Sync) logDebugf(format string, a ...interface{}) {
419 s.logf(safcm.LogDebug, false, format, a...)
421 func (s *Sync) logVerbosef(format string, a ...interface{}) {
422 s.logf(safcm.LogVerbose, false, format, a...)
425 // sendRecv sends a message over conn and waits for the response. Any MsgLog
426 // messages received before the final (non MsgLog) response are passed to
428 func (s *Sync) sendRecv(conn *rpc.Conn, msg safcm.Msg) (safcm.Msg, error) {
429 err := conn.Send(msg)
434 x, err := conn.Recv()
438 log, ok := x.(safcm.MsgLog)
440 s.logf(log.Level, false, "%s", log.Text)