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 nameMap := make(map[string]bool)
190 for _, x := range names {
193 nameMatched := make(map[string]bool)
194 // To detect typos we must check all given names but only want to add
196 hostMatched := make(map[string]bool)
198 var res []*config.Host
199 for _, host := range allHosts.List {
200 if nameMap[host.Name] {
201 res = append(res, host)
202 hostMatched[host.Name] = true
203 nameMatched[host.Name] = true
206 // TODO: don't permit groups which contain "detected" groups
207 // because these are not available yet
208 groups, err := config.ResolveHostGroups(host.Name,
213 for _, x := range groups {
215 if !hostMatched[host.Name] {
216 res = append(res, host)
217 hostMatched[host.Name] = true
219 nameMatched[x] = true
224 // Warn about unmatched names to detect typos
225 if len(nameMap) != len(nameMatched) {
226 var unmatched []string
227 for x := range nameMap {
229 unmatched = append(unmatched,
230 fmt.Sprintf("%q", x))
233 sort.Strings(unmatched)
234 return nil, fmt.Errorf("hosts/groups not found: %s",
235 strings.Join(unmatched, " "))
241 func logEvent(x Event, level safcm.LogLevel, isTTY bool, failed *bool) {
242 // We have multiple event sources so this is somewhat ugly.
243 var prefix, data string
247 data = x.Error.Error()
249 // We logged an error, tell the caller
251 } else if x.Log.Level != 0 {
252 // LogError and LogDebug3 should not occur here
256 case safcm.LogVerbose:
260 case safcm.LogDebug2:
263 prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
268 switch x.ConnEvent.Type {
269 case rpc.ConnEventStderr:
271 case rpc.ConnEventDebug:
273 case rpc.ConnEventUpload:
274 if level < safcm.LogInfo {
278 x.ConnEvent.Data = "remote helper upload in progress"
280 prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
283 data = x.ConnEvent.Data
288 host = ColorString(isTTY, color, host)
290 // Make sure to escape control characters to prevent terminal
293 data = EscapeControlCharacters(isTTY, data)
295 log.Printf("%-9s [%s] %s", prefix, host, data)
298 func (s *Sync) Host(wg *sync.WaitGroup) error {
299 conn := rpc.NewConn(s.config.LogLevel >= safcm.LogDebug3)
300 // Pass all connection events to main loop
303 x, ok := <-conn.Events
315 // Connect to remote host
316 err := conn.DialSSH(s.host.SshUser, s.host.Name)
322 // Collect information about remote host
323 detectedGroups, err := s.hostInfo(conn)
328 // Sync state to remote host
329 err = s.hostSync(conn, detectedGroups)
334 // Terminate connection to remote host
335 err = conn.Send(safcm.MsgQuitReq{})
351 func (s *Sync) logf(level safcm.LogLevel, escaped bool,
352 format string, a ...interface{}) {
354 if s.config.LogLevel < level {
361 Text: fmt.Sprintf(format, a...),
366 func (s *Sync) logDebugf(format string, a ...interface{}) {
367 s.logf(safcm.LogDebug, false, format, a...)
369 func (s *Sync) logVerbosef(format string, a ...interface{}) {
370 s.logf(safcm.LogVerbose, false, format, a...)
373 // sendRecv sends a message over conn and waits for the response. Any MsgLog
374 // messages received before the final (non MsgLog) response are passed to
376 func (s *Sync) sendRecv(conn *rpc.Conn, msg safcm.Msg) (safcm.Msg, error) {
377 err := conn.Send(msg)
382 x, err := conn.Recv()
386 log, ok := x.(safcm.MsgLog)
388 s.logf(log.Level, false, "%s", log.Text)