cmd/cli: avoid accessing mainLog when possible

By adding a logger field to "prog" struct, and use this field inside its
method instead of always accessing global mainLog variable. This at
least ensure more consistent usage of the logger during ctrld prog
runtime, and also help refactoring the code more easily in the future
(like replacing the logger library).
This commit is contained in:
Cuong Manh Le
2025-06-17 19:20:37 +07:00
committed by Cuong Manh Le
parent fc527dbdfb
commit b9b9cfcade
16 changed files with 323 additions and 278 deletions
+14 -14
View File
@@ -28,61 +28,61 @@ func hasNetworkManager() bool {
return exe != ""
}
func setupNetworkManager() error {
func (p *prog) setupNetworkManager() error {
if !hasNetworkManager() {
return nil
}
if content, _ := os.ReadFile(nmCtrldConfContent); string(content) == nmCtrldConfContent {
mainLog.Load().Debug().Msg("NetworkManager already setup, nothing to do")
p.Debug().Msg("NetworkManager already setup, nothing to do")
return nil
}
err := os.WriteFile(networkManagerCtrldConfFile, []byte(nmCtrldConfContent), os.FileMode(0644))
if os.IsNotExist(err) {
mainLog.Load().Debug().Msg("NetworkManager is not available")
p.Debug().Msg("NetworkManager is not available")
return nil
}
if err != nil {
mainLog.Load().Debug().Err(err).Msg("could not write NetworkManager ctrld config file")
p.Debug().Err(err).Msg("could not write NetworkManager ctrld config file")
return err
}
reloadNetworkManager()
mainLog.Load().Debug().Msg("setup NetworkManager done")
p.reloadNetworkManager()
p.Debug().Msg("setup NetworkManager done")
return nil
}
func restoreNetworkManager() error {
func (p *prog) restoreNetworkManager() error {
if !hasNetworkManager() {
return nil
}
err := os.Remove(networkManagerCtrldConfFile)
if os.IsNotExist(err) {
mainLog.Load().Debug().Msg("NetworkManager is not available")
p.Debug().Msg("NetworkManager is not available")
return nil
}
if err != nil {
mainLog.Load().Debug().Err(err).Msg("could not remove NetworkManager ctrld config file")
p.Debug().Err(err).Msg("could not remove NetworkManager ctrld config file")
return err
}
reloadNetworkManager()
mainLog.Load().Debug().Msg("restore NetworkManager done")
p.reloadNetworkManager()
p.Debug().Msg("restore NetworkManager done")
return nil
}
func reloadNetworkManager() {
func (p *prog) reloadNetworkManager() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
conn, err := dbus.NewSystemConnectionContext(ctx)
if err != nil {
mainLog.Load().Error().Err(err).Msg("could not create new system connection")
p.Error().Err(err).Msg("could not create new system connection")
return
}
defer conn.Close()
waitCh := make(chan string)
if _, err := conn.ReloadUnitContext(ctx, nmSystemdUnitName, "ignore-dependencies", waitCh); err != nil {
mainLog.Load().Debug().Err(err).Msg("could not reload NetworkManager")
p.Debug().Err(err).Msg("could not reload NetworkManager")
return
}
<-waitCh