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()))
127 done := make(chan bool)
128 // Collect events from all hosts and print them
129 events := make(chan Event)
137 logEvent(x, cfg.LogLevel, isTTY, &failed)
142 hostsLeft := make(map[string]bool)
143 for _, x := range toSync {
144 hostsLeft[x.Name] = true
146 var hostsLeftMutex sync.Mutex // protects hostsLeft
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
152 // Running `ssh` processes get killed by SIGINT which is sent
156 log.Print("Received SIGINT, aborting ...")
158 // Print all queued events
159 events <- Event{} // poison pill
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.
165 hostsLeftMutex.Lock()
167 for x := range hostsLeft {
168 hosts = append(hosts, x)
171 log.Fatalf("Failed to sync %s", strings.Join(hosts, ", "))
174 // Sync all hosts concurrently
175 var wg sync.WaitGroup
176 for _, x := range toSync {
179 // Once in sync.Host() and once in the go func below
187 allGroups: allGroups,
191 err := sync.Host(&wg)
200 hostsLeftMutex.Lock()
201 defer hostsLeftMutex.Unlock()
202 delete(hostsLeft, x.Name)
207 events <- Event{} // poison pill
211 // Exit instead of returning an error to prevent an extra log
212 // message from main()
218 // hostsToSync returns the list of hosts to sync based on the command line
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.
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) {
229 detectedMap := config.TransitivelyDetectedGroups(allGroups)
231 const detectedErr = `
233 Groups depending on "detected" groups cannot be used to select hosts as these
234 are only available after the hosts were contacted.
237 nameMap := make(map[string]bool)
238 for _, x := range names {
240 return nil, fmt.Errorf(
241 "group %q depends on \"detected\" groups%s",
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)
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
259 groups, err := config.ResolveHostGroups(host.Name,
264 for _, x := range groups {
266 if !hostMatched[host.Name] {
267 res = append(res, host)
268 hostMatched[host.Name] = true
270 nameMatched[x] = true
275 // Warn about unmatched names to detect typos
276 if len(nameMap) != len(nameMatched) {
277 var unmatched []string
278 for x := range nameMap {
280 unmatched = append(unmatched,
281 fmt.Sprintf("%q", x))
284 sort.Strings(unmatched)
285 return nil, fmt.Errorf("hosts/groups not found: %s",
286 strings.Join(unmatched, " "))
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
298 data = x.Error.Error()
300 // We logged an error, tell the caller
302 } else if x.Log.Level != 0 {
303 // LogError and LogDebug3 should not occur here
307 case safcm.LogVerbose:
311 case safcm.LogDebug2:
314 prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
319 switch x.ConnEvent.Type {
320 case rpc.ConnEventStderr:
322 case rpc.ConnEventDebug:
324 case rpc.ConnEventUpload:
325 if level < safcm.LogInfo {
329 x.ConnEvent.Data = "remote helper upload in progress"
331 prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
334 data = x.ConnEvent.Data
339 host = ColorString(isTTY, color, host)
341 // Make sure to escape control characters to prevent terminal
344 data = EscapeControlCharacters(isTTY, data)
346 log.Printf("%-9s [%s] %s", prefix, host, data)
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
354 x, ok := <-conn.Events
366 // Connect to remote host
367 err := conn.DialSSH(s.host.SshUser, s.host.Name, s.config.SshConfig)
373 // Collect information about remote host
374 detectedGroups, err := s.hostInfo(conn)
379 // Sync state to remote host
380 err = s.hostSync(conn, detectedGroups)
385 // Terminate connection to remote host
386 err = conn.Send(safcm.MsgQuitReq{})
402 func (s *Sync) logf(level safcm.LogLevel, escaped bool,
403 format string, a ...interface{}) {
405 if s.config.LogLevel < level {
412 Text: fmt.Sprintf(format, a...),
417 func (s *Sync) logDebugf(format string, a ...interface{}) {
418 s.logf(safcm.LogDebug, false, format, a...)
420 func (s *Sync) logVerbosef(format string, a ...interface{}) {
421 s.logf(safcm.LogVerbose, false, format, a...)
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
427 func (s *Sync) sendRecv(conn *rpc.Conn, msg safcm.Msg) (safcm.Msg, error) {
428 err := conn.Send(msg)
433 x, err := conn.Recv()
437 log, ok := x.(safcm.MsgLog)
439 s.logf(log.Level, false, "%s", log.Text)