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/frontend"
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
47 logFunc func(level safcm.LogLevel, escaped bool, msg string)
50 func MainSync(args []string) error {
52 fmt.Fprintf(os.Stderr,
53 "usage: %s sync [<options>] <host|group...>\n",
58 optionDryRun := flag.Bool("n", false,
59 "dry-run, show diff but don't perform any changes")
60 optionQuiet := flag.Bool("q", false,
61 "hide successful, non-trigger commands with no output from host changes listing")
62 optionLog := flag.String("log", "info", "set log `level`; "+
63 "levels: error, info, verbose, debug, debug2, debug3")
64 optionSshConfig := flag.String("sshconfig", "",
65 "`path` to ssh configuration file; used for tests")
67 flag.CommandLine.Parse(args[2:])
69 level, err := safcm.ParseLogLevel(*optionLog)
71 return fmt.Errorf("-log: %v", err)
80 if runtime.GOOS == "windows" {
81 log.Print("WARNING: Windows support is experimental!")
84 cfg, allHosts, allGroups, err := LoadBaseFiles()
88 cfg.DryRun = *optionDryRun
89 cfg.Quiet = *optionQuiet
91 cfg.SshConfig = *optionSshConfig
93 toSync, err := hostsToSync(names, allHosts, allGroups)
98 return fmt.Errorf("no hosts found")
101 isTTY := term.IsTerminal(int(os.Stdout.Fd())) &&
102 term.IsTerminal(int(os.Stderr.Fd()))
104 loop := &frontend.Loop{
105 DebugConn: cfg.LogLevel >= safcm.LogDebug3,
106 LogEventFunc: func(x frontend.Event, failed *bool) {
107 logEvent(x, cfg.LogLevel, isTTY, failed)
109 SyncHostFunc: func(conn *rpc.Conn, host frontend.Host) error {
110 return host.(*Sync).Host(conn)
114 var hosts []frontend.Host
115 for _, x := range toSync {
120 allGroups: allGroups,
123 s.logFunc = func(level safcm.LogLevel, escaped bool,
125 loop.Log(s, level, escaped, msg)
127 hosts = append(hosts, s)
130 succ := loop.Run(hosts)
133 // Exit instead of returning an error to prevent an extra log
134 // message from main()
140 // hostsToSync returns the list of hosts to sync based on the command line
143 // Full host and group matches are required to prevent unexpected behavior. No
144 // arguments does not expand to all hosts to prevent accidents; "all" can be
145 // used instead. Both host and group names are permitted as these are unique.
147 // TODO: Add option to permit partial/glob matches
148 func hostsToSync(names []string, allHosts *config.Hosts,
149 allGroups map[string][]string) ([]*config.Host, error) {
151 detectedMap := config.TransitivelyDetectedGroups(allGroups)
153 const detectedErr = `
155 Groups depending on "detected" groups cannot be used to select hosts as these
156 are only available after the hosts were contacted.
159 nameMap := make(map[string]bool)
160 for _, x := range names {
162 return nil, fmt.Errorf(
163 "group %q depends on \"detected\" groups%s",
168 nameMatched := make(map[string]bool)
169 // To detect typos we must check all given names but one host can be
170 // matched by multiple names (e.g. two groups with overlapping hosts)
171 hostAdded := make(map[string]bool)
173 var res []*config.Host
174 for _, host := range allHosts.List {
175 if nameMap[host.Name] {
176 res = append(res, host)
177 hostAdded[host.Name] = true
178 nameMatched[host.Name] = true
181 groups, err := config.ResolveHostGroups(host.Name,
186 for _, x := range groups {
188 if !hostAdded[host.Name] {
189 res = append(res, host)
190 hostAdded[host.Name] = true
192 nameMatched[x] = true
197 // Warn about unmatched names to detect typos
198 if len(nameMap) != len(nameMatched) {
199 var unmatched []string
200 for x := range nameMap {
202 unmatched = append(unmatched,
203 fmt.Sprintf("%q", x))
206 sort.Strings(unmatched)
207 return nil, fmt.Errorf("hosts/groups not found: %s",
208 strings.Join(unmatched, " "))
214 func logEvent(x frontend.Event, level safcm.LogLevel, isTTY bool, failed *bool) {
215 // We have multiple event sources so this is somewhat ugly.
216 var prefix, data string
220 data = x.Error.Error()
222 // We logged an error, tell the caller
224 } else if x.Log.Level != 0 {
225 if level < x.Log.Level {
228 // LogError and LogDebug3 should not occur here
232 case safcm.LogVerbose:
236 case safcm.LogDebug2:
239 prefix = fmt.Sprintf("[INVALID=%d]", x.Log.Level)
244 switch x.ConnEvent.Type {
245 case rpc.ConnEventStderr:
247 case rpc.ConnEventDebug:
249 case rpc.ConnEventUpload:
250 if level < safcm.LogInfo {
254 x.ConnEvent.Data = "remote helper upload in progress"
256 prefix = fmt.Sprintf("[INVALID=%d]", x.ConnEvent.Type)
259 data = x.ConnEvent.Data
262 host := x.Host.Name()
264 host = ColorString(isTTY, color, host)
266 // Make sure to escape control characters to prevent terminal
269 data = EscapeControlCharacters(isTTY, data)
271 log.Printf("%-9s [%s] %s", prefix, host, data)
274 func (s *Sync) Name() string {
278 func (s *Sync) Dial(conn *rpc.Conn) error {
279 helpers, err := fs.Sub(RemoteHelpers, "remote")
284 // Connect to remote host
285 user := s.host.SshUser
287 user = s.config.SshUser
289 return conn.DialSSH(rpc.SSHConfig{
292 SshConfig: s.config.SshConfig,
293 RemoteHelpers: helpers,
297 func (s *Sync) Host(conn *rpc.Conn) error {
298 // Collect information about remote host
299 detectedGroups, err := s.hostInfo(conn)
304 // Sync state to remote host
305 err = s.hostSync(conn, detectedGroups)
313 func (s *Sync) log(level safcm.LogLevel, escaped bool, msg string) {
314 s.logFunc(level, escaped, msg)
316 func (s *Sync) logDebugf(format string, a ...interface{}) {
317 s.log(safcm.LogDebug, false, fmt.Sprintf(format, a...))
319 func (s *Sync) logVerbosef(format string, a ...interface{}) {
320 s.log(safcm.LogVerbose, false, fmt.Sprintf(format, a...))
323 // sendRecv sends a message over conn and waits for the response. Any MsgLog
324 // messages received before the final (non MsgLog) response are passed to
326 func (s *Sync) sendRecv(conn *rpc.Conn, msg safcm.Msg) (safcm.Msg, error) {
327 err := conn.Send(msg)
332 x, err := conn.Recv()
336 log, ok := x.(safcm.MsgLog)
338 s.log(log.Level, false, log.Text)