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/>.
31 "ruderich.org/simon/safcm"
32 "ruderich.org/simon/safcm/cmd/safcm/config"
33 "ruderich.org/simon/safcm/rpc"
39 config *config.Config // global configuration
40 allHosts *config.Hosts // known hosts
41 allGroups map[string][]string // known groups
43 events chan<- Event // all events generated by/for this host
51 // Only one of Error, Log and ConnEvent is set in a single event
54 ConnEvent rpc.ConnEvent
56 Escaped bool // true if untrusted input is already escaped
64 func MainSync(args []string) error {
66 fmt.Fprintf(os.Stderr,
67 "usage: %s sync [<options>] <host|group...>\n",
72 optionDryRun := flag.Bool("n", false,
73 "dry-run, show diff but don't perform any changes")
74 optionQuiet := flag.Bool("q", false,
75 "hide successful, non-trigger commands with no output from host changes listing")
76 optionLog := flag.String("log", "info", "set log `level`; "+
77 "levels: error, info, verbose, debug, debug2, debug3")
79 flag.CommandLine.Parse(args[2:])
81 var level safcm.LogLevel
84 level = safcm.LogError
88 level = safcm.LogVerbose
90 level = safcm.LogDebug
92 level = safcm.LogDebug2
94 level = safcm.LogDebug3
96 return fmt.Errorf("invalid -log value %q", *optionLog)
105 cfg, allHosts, allGroups, err := LoadBaseFiles()
109 cfg.DryRun = *optionDryRun
110 cfg.Quiet = *optionQuiet
113 toSync, err := hostsToSync(names, allHosts, allGroups)
117 if len(toSync) == 0 {
118 return fmt.Errorf("no hosts found")
121 isTTY := term.IsTerminal(int(os.Stdout.Fd()))
123 done := make(chan bool)
124 // Collect events from all hosts and print them
125 events := make(chan Event)
133 logEvent(x, cfg.LogLevel, isTTY, &failed)
138 // Sync all hosts concurrently
139 var wg sync.WaitGroup
140 for _, x := range toSync {
143 // Once in sync.Host() and once in the go func below
151 allGroups: allGroups,
155 err := sync.Host(&wg)
167 events <- Event{} // poison pill
171 // Exit instead of returning an error to prevent an extra log
172 // message from main()
178 // hostsToSync returns the list of hosts to sync based on the command line
181 // Full host and group matches are required to prevent unexpected behavior. No
182 // arguments does not expand to all hosts to prevent accidents; "all" can be
183 // used instead. Both host and group names are permitted as these are unique.
185 // TODO: Add option to permit partial/glob matches
186 func hostsToSync(names []string, allHosts *config.Hosts,
187 allGroups map[string][]string) ([]*config.Host, error) {
189 detectedMap := make(map[string]bool)
190 for _, x := range config.TransitivelyDetectedGroups(allGroups) {
191 detectedMap[x] = true
194 const detectedErr = `
196 Groups depending on "detected" groups cannot be used to select hosts as these
197 are only available after the hosts were contacted.
200 nameMap := make(map[string]bool)
201 for _, x := range names {
203 return nil, fmt.Errorf(
204 "group %q depends on \"detected\" groups%s",
209 nameMatched := make(map[string]bool)
210 // To detect typos we must check all given names but only want to add
212 hostMatched := make(map[string]bool)
214 var res []*config.Host
215 for _, host := range allHosts.List {
216 if nameMap[host.Name] {
217 res = append(res, host)
218 hostMatched[host.Name] = true
219 nameMatched[host.Name] = true
222 groups, err := config.ResolveHostGroups(host.Name,
227 for _, x := range groups {
229 if !hostMatched[host.Name] {
230 res = append(res, host)
231 hostMatched[host.Name] = true
233 nameMatched[x] = true
238 // Warn about unmatched names to detect typos
239 if len(nameMap) != len(nameMatched) {
240 var unmatched []string
241 for x := range nameMap {
243 unmatched = append(unmatched,
244 fmt.Sprintf("%q", x))
247 sort.Strings(unmatched)
248 return nil, fmt.Errorf("hosts/groups not found: %s",
249 strings.Join(unmatched, " "))
255 func logEvent(x Event, level safcm.LogLevel, isTTY bool, failed *bool) {
256 // We have multiple event sources so this is somewhat ugly.
257 var prefix, data string
261 data = x.Error.Error()
263 // We logged an error, tell the caller
265 } else if x.Log.Level != 0 {
266 // LogError and LogDebug3 should not occur here
270 case safcm.LogVerbose:
274 case safcm.LogDebug2:
277 prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
282 switch x.ConnEvent.Type {
283 case rpc.ConnEventStderr:
285 case rpc.ConnEventDebug:
287 case rpc.ConnEventUpload:
288 if level < safcm.LogInfo {
292 x.ConnEvent.Data = "remote helper upload in progress"
294 prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
297 data = x.ConnEvent.Data
302 host = ColorString(isTTY, color, host)
304 // Make sure to escape control characters to prevent terminal
307 data = EscapeControlCharacters(isTTY, data)
309 log.Printf("%-9s [%s] %s", prefix, host, data)
312 func (s *Sync) Host(wg *sync.WaitGroup) error {
313 conn := rpc.NewConn(s.config.LogLevel >= safcm.LogDebug3)
314 // Pass all connection events to main loop
317 x, ok := <-conn.Events
329 // Connect to remote host
330 err := conn.DialSSH(s.host.SshUser, s.host.Name)
336 // Collect information about remote host
337 detectedGroups, err := s.hostInfo(conn)
342 // Sync state to remote host
343 err = s.hostSync(conn, detectedGroups)
348 // Terminate connection to remote host
349 err = conn.Send(safcm.MsgQuitReq{})
365 func (s *Sync) logf(level safcm.LogLevel, escaped bool,
366 format string, a ...interface{}) {
368 if s.config.LogLevel < level {
375 Text: fmt.Sprintf(format, a...),
380 func (s *Sync) logDebugf(format string, a ...interface{}) {
381 s.logf(safcm.LogDebug, false, format, a...)
383 func (s *Sync) logVerbosef(format string, a ...interface{}) {
384 s.logf(safcm.LogVerbose, false, format, a...)
387 // sendRecv sends a message over conn and waits for the response. Any MsgLog
388 // messages received before the final (non MsgLog) response are passed to
390 func (s *Sync) sendRecv(conn *rpc.Conn, msg safcm.Msg) (safcm.Msg, error) {
391 err := conn.Send(msg)
396 x, err := conn.Recv()
400 log, ok := x.(safcm.MsgLog)
402 s.logf(log.Level, false, "%s", log.Text)