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/>.
33 "ruderich.org/simon/safcm"
34 "ruderich.org/simon/safcm/cmd/safcm/config"
35 "ruderich.org/simon/safcm/rpc"
41 config *config.Config // global configuration
42 allHosts *config.Hosts // known hosts
43 allGroups map[string][]string // known groups
45 events chan<- Event // all events generated by/for this host
53 // Only one of Error, Log and ConnEvent is set in a single event
56 ConnEvent rpc.ConnEvent
58 Escaped bool // true if untrusted input is already escaped
66 func MainSync(args []string) error {
68 fmt.Fprintf(os.Stderr,
69 "usage: %s sync [<options>] <host|group...>\n",
74 optionDryRun := flag.Bool("n", false,
75 "dry-run, show diff but don't perform any changes")
76 optionQuiet := flag.Bool("q", false,
77 "hide successful, non-trigger commands with no output from host changes listing")
78 optionLog := flag.String("log", "info", "set log `level`; "+
79 "levels: error, info, verbose, debug, debug2, debug3")
80 optionSshConfig := flag.String("sshconfig", "",
81 "`path` to ssh configuration file; used for tests")
83 flag.CommandLine.Parse(args[2:])
85 var level safcm.LogLevel
88 level = safcm.LogError
92 level = safcm.LogVerbose
94 level = safcm.LogDebug
96 level = safcm.LogDebug2
98 level = safcm.LogDebug3
100 return fmt.Errorf("invalid -log value %q", *optionLog)
109 if runtime.GOOS == "windows" {
110 log.Print("WARNING: Windows support is experimental!")
113 cfg, allHosts, allGroups, err := LoadBaseFiles()
117 cfg.DryRun = *optionDryRun
118 cfg.Quiet = *optionQuiet
120 cfg.SshConfig = *optionSshConfig
122 toSync, err := hostsToSync(names, allHosts, allGroups)
126 if len(toSync) == 0 {
127 return fmt.Errorf("no hosts found")
130 isTTY := term.IsTerminal(int(os.Stdout.Fd())) &&
131 term.IsTerminal(int(os.Stderr.Fd()))
133 done := make(chan bool)
134 // Collect events from all hosts and print them
135 events := make(chan Event)
143 logEvent(x, cfg.LogLevel, isTTY, &failed)
148 hostsLeft := make(map[string]bool)
149 for _, x := range toSync {
150 hostsLeft[x.Name] = true
152 var hostsLeftMutex sync.Mutex // protects hostsLeft
154 // Show unfinished hosts on Ctrl-C
155 sigint := make(chan os.Signal, 1) // buffered for Notify()
156 signal.Notify(sigint, os.Interrupt) // = SIGINT = Ctrl-C
158 // Running `ssh` processes get killed by SIGINT which is sent
162 log.Print("Received SIGINT, aborting ...")
164 // Print all queued events
165 events <- Event{} // poison pill
167 // "races" with <-done in the main function and will hang here
168 // if the other is faster. This is fine because then all hosts
169 // were synced successfully.
171 hostsLeftMutex.Lock()
173 for x := range hostsLeft {
174 hosts = append(hosts, x)
177 log.Fatalf("Failed to sync %s", strings.Join(hosts, ", "))
180 // Sync all hosts concurrently
181 var wg sync.WaitGroup
182 for _, x := range toSync {
185 // Once in sync.Host() and once in the go func below
193 allGroups: allGroups,
197 err := sync.Host(&wg)
206 hostsLeftMutex.Lock()
207 defer hostsLeftMutex.Unlock()
208 delete(hostsLeft, x.Name)
213 events <- Event{} // poison pill
217 // Exit instead of returning an error to prevent an extra log
218 // message from main()
224 // hostsToSync returns the list of hosts to sync based on the command line
227 // Full host and group matches are required to prevent unexpected behavior. No
228 // arguments does not expand to all hosts to prevent accidents; "all" can be
229 // used instead. Both host and group names are permitted as these are unique.
231 // TODO: Add option to permit partial/glob matches
232 func hostsToSync(names []string, allHosts *config.Hosts,
233 allGroups map[string][]string) ([]*config.Host, error) {
235 detectedMap := config.TransitivelyDetectedGroups(allGroups)
237 const detectedErr = `
239 Groups depending on "detected" groups cannot be used to select hosts as these
240 are only available after the hosts were contacted.
243 nameMap := make(map[string]bool)
244 for _, x := range names {
246 return nil, fmt.Errorf(
247 "group %q depends on \"detected\" groups%s",
252 nameMatched := make(map[string]bool)
253 // To detect typos we must check all given names but one host can be
254 // matched by multiple names (e.g. two groups with overlapping hosts)
255 hostAdded := make(map[string]bool)
257 var res []*config.Host
258 for _, host := range allHosts.List {
259 if nameMap[host.Name] {
260 res = append(res, host)
261 hostAdded[host.Name] = true
262 nameMatched[host.Name] = true
265 groups, err := config.ResolveHostGroups(host.Name,
270 for _, x := range groups {
272 if !hostAdded[host.Name] {
273 res = append(res, host)
274 hostAdded[host.Name] = true
276 nameMatched[x] = true
281 // Warn about unmatched names to detect typos
282 if len(nameMap) != len(nameMatched) {
283 var unmatched []string
284 for x := range nameMap {
286 unmatched = append(unmatched,
287 fmt.Sprintf("%q", x))
290 sort.Strings(unmatched)
291 return nil, fmt.Errorf("hosts/groups not found: %s",
292 strings.Join(unmatched, " "))
298 func logEvent(x Event, level safcm.LogLevel, isTTY bool, failed *bool) {
299 // We have multiple event sources so this is somewhat ugly.
300 var prefix, data string
304 data = x.Error.Error()
306 // We logged an error, tell the caller
308 } else if x.Log.Level != 0 {
309 // LogError and LogDebug3 should not occur here
313 case safcm.LogVerbose:
317 case safcm.LogDebug2:
320 prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
325 switch x.ConnEvent.Type {
326 case rpc.ConnEventStderr:
328 case rpc.ConnEventDebug:
330 case rpc.ConnEventUpload:
331 if level < safcm.LogInfo {
335 x.ConnEvent.Data = "remote helper upload in progress"
337 prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
340 data = x.ConnEvent.Data
345 host = ColorString(isTTY, color, host)
347 // Make sure to escape control characters to prevent terminal
350 data = EscapeControlCharacters(isTTY, data)
352 log.Printf("%-9s [%s] %s", prefix, host, data)
355 func (s *Sync) Host(wg *sync.WaitGroup) error {
356 conn := rpc.NewConn(s.config.LogLevel >= safcm.LogDebug3)
357 // Pass all connection events to main loop
360 x, ok := <-conn.Events
372 // Connect to remote host
373 user := s.host.SshUser
375 user = s.config.SshUser
377 err := conn.DialSSH(user, s.host.Name, s.config.SshConfig)
383 // Collect information about remote host
384 detectedGroups, err := s.hostInfo(conn)
389 // Sync state to remote host
390 err = s.hostSync(conn, detectedGroups)
395 // Terminate connection to remote host
396 err = conn.Send(safcm.MsgQuitReq{})
412 func (s *Sync) log(level safcm.LogLevel, escaped bool, msg string) {
413 if s.config.LogLevel < level {
425 func (s *Sync) logDebugf(format string, a ...interface{}) {
426 s.log(safcm.LogDebug, false, fmt.Sprintf(format, a...))
428 func (s *Sync) logVerbosef(format string, a ...interface{}) {
429 s.log(safcm.LogVerbose, false, fmt.Sprintf(format, a...))
432 // sendRecv sends a message over conn and waits for the response. Any MsgLog
433 // messages received before the final (non MsgLog) response are passed to
435 func (s *Sync) sendRecv(conn *rpc.Conn, msg safcm.Msg) (safcm.Msg, error) {
436 err := conn.Send(msg)
441 x, err := conn.Recv()
445 log, ok := x.(safcm.MsgLog)
447 s.log(log.Level, false, log.Text)