From 1758037def00d8db811bc7d8c0f23cb9bbdf0623 Mon Sep 17 00:00:00 2001 From: caffeinated92 Date: Wed, 13 Nov 2024 13:58:47 +0400 Subject: [PATCH 1/4] set ExpectedUser as the owner of files in working dir --- cluster/cluster_key.go | 2 +- cluster/cluster_topo.go | 5 +--- graphite/carbonapi.go | 54 +++++++++++++++-------------------- graphite/graphite.go | 6 +++- server/server.go | 62 +++++++++++++++++++++++++++++++++-------- utils/misc/files.go | 24 +++++++++++++--- 6 files changed, 100 insertions(+), 53 deletions(-) diff --git a/cluster/cluster_key.go b/cluster/cluster_key.go index 65a1660f8..5e10b0442 100644 --- a/cluster/cluster_key.go +++ b/cluster/cluster_key.go @@ -243,7 +243,7 @@ func (cluster *Cluster) keyToFile(filename string, key *rsa.PrivateKey) { file, err := os.Create(filename) if err != nil { - cluster.LogModulePrintf(cluster.Conf.Verbose, config.ConstLogModConfigLoad, config.LvlInfo, "Failed to generate file: %s", err) + cluster.LogModulePrintf(cluster.Conf.Verbose, config.ConstLogModConfigLoad, config.LvlInfo, "Failed to generate file %s: %s", filename, err) } defer file.Close() b := x509.MarshalPKCS1PrivateKey(key) diff --git a/cluster/cluster_topo.go b/cluster/cluster_topo.go index 0d7b4d6d2..f5475d520 100644 --- a/cluster/cluster_topo.go +++ b/cluster/cluster_topo.go @@ -57,10 +57,7 @@ func (cluster *Cluster) newServerList() error { if cluster.Conf.Hosts != "" { for k, url := range cluster.hostList { // Source name will equal to cluster name - cluster.Servers[k], err = cluster.newServerMonitor(url, cluster.GetDbUser(), cluster.GetDbPass(), false, cluster.GetDomain(), cluster.Name) - if err != nil { - cluster.LogModulePrintf(cluster.Conf.Verbose, config.ConstLogModTopology, config.LvlErr, "Could not open connection to server %s : %s", cluster.Servers[k].URL, err) - } + cluster.Servers[k], _ = cluster.newServerMonitor(url, cluster.GetDbUser(), cluster.GetDbPass(), false, cluster.GetDomain(), cluster.Name) cluster.Servers[k].SetPlacement(k, cluster.Conf.ProvAgents, cluster.Conf.SlapOSDBPartitions, cluster.Conf.SchedulerReceiverPorts) if cluster.Conf.Verbose { diff --git a/graphite/carbonapi.go b/graphite/carbonapi.go index c1135ea8d..615298a48 100644 --- a/graphite/carbonapi.go +++ b/graphite/carbonapi.go @@ -18,9 +18,9 @@ import ( "github.com/signal18/replication-manager/config" pb "github.com/signal18/replication-manager/graphite/carbonzipper/carbonzipperpb" - "github.com/signal18/replication-manager/graphite/carbonzipper/mlog" "github.com/signal18/replication-manager/graphite/carbonzipper/mstats" "github.com/signal18/replication-manager/graphite/expr" + clog "github.com/sirupsen/logrus" "github.com/bradfitz/gomemcache/memcache" ecache "github.com/dgryski/go-expirecache" @@ -64,7 +64,7 @@ var findCache bytesCache var defaultTimeZone = time.Local -var logger mlog.Level +var LogApi = clog.New() // Zipper is API entry to carbonzipper var Zipper zipper @@ -290,7 +290,7 @@ func renderHandler(w http.ResponseWriter, r *http.Request, stats *renderStats) { if tstr := r.FormValue("cacheTimeout"); tstr != "" { t, err := strconv.Atoi(tstr) if err != nil { - logger.Logf("failed to parse cacheTimeout: %v: %v", tstr, err) + LogApi.Warnf("failed to parse cacheTimeout: %v: %v", tstr, err) } else { cacheTimeout = int32(t) } @@ -364,7 +364,7 @@ func renderHandler(w http.ResponseWriter, r *http.Request, stats *renderStats) { stats.zipperRequests++ glob, err = Zipper.Find(m.Metric) if err != nil { - logger.Logf("Find: %v: %v", m.Metric, err) + LogApi.Warnf("Find: %v: %v", m.Metric, err) continue } b, err := glob.Marshal() @@ -391,7 +391,7 @@ func renderHandler(w http.ResponseWriter, r *http.Request, stats *renderStats) { if err == nil { rptr = &r } else { - logger.Logf("Render: %v: %v", m.GetPath(), err) + LogApi.Warnf("Render: %v: %v", m.GetPath(), err) } rch <- rptr Limiter.leave() @@ -414,7 +414,7 @@ func renderHandler(w http.ResponseWriter, r *http.Request, stats *renderStats) { if r := recover(); r != nil { var buf [1024]byte runtime.Stack(buf[:], false) - logger.Logf("panic during eval: %s: %s\n%s\n", cacheKey, r, string(buf[:])) + LogApi.Errorf("panic during eval: %s: %s\n%s\n", cacheKey, r, string(buf[:])) } }() exprs, err := expr.EvalExpr(exp, from32, until32, metricMap) @@ -667,34 +667,26 @@ func RunCarbonApi(conf *config.Config) { var memsize int = 200 var cpus int = 0 var tz string = "" - var logdir string = conf.WorkingDir interval := 60 * time.Second graphiteHost := "" - logtostdout := false idleconns := 10 pidFile := "" - if logdir == "" { - mlog.SetRawStream(os.Stdout) - } else { - mlog.SetOutput(logdir, "carbonapi", logtostdout) - } - expvar.NewString("BuildVersion").Set(BuildVersion) - logger.Logln("starting carbonapi", BuildVersion) + LogApi.Println("starting carbonapi", BuildVersion) Limiter = newLimiter(l) if z == "" { - logger.Fatalln("no zipper provided") + LogApi.Fatalln("no zipper provided") } if _, err := url.Parse(z); err != nil { - logger.Fatalln("unable to parze zipper:", err) + LogApi.Fatalln("unable to parze zipper:", err) } - logger.Logln("using zipper", z) + LogApi.Println("using zipper", z) Zipper = zipper{ z: z, client: &http.Client{ @@ -707,11 +699,11 @@ func RunCarbonApi(conf *config.Config) { switch cacheType { case "memcache": if mc == "" { - logger.Fatalln("memcache cache requested but no memcache servers provided") + LogApi.Fatalln("memcache cache requested but no memcache servers provided") } servers := strings.Split(mc, ",") - logger.Logln("using memcache servers:", servers) + LogApi.Println("using memcache servers:", servers) queryCache = &memcachedCache{client: memcache.New(servers...)} findCache = &memcachedCache{client: memcache.New(servers...)} @@ -741,21 +733,21 @@ func RunCarbonApi(conf *config.Config) { if tz != "" { fields := strings.Split(tz, ",") if len(fields) != 2 { - logger.Fatalf("expected two fields for tz,seconds, got %d", len(fields)) + LogApi.Fatalf("expected two fields for tz,seconds, got %d", len(fields)) } var err error offs, err := strconv.Atoi(fields[1]) if err != nil { - logger.Fatalf("unable to parse seconds: %s: %s", fields[1], err) + LogApi.Fatalf("unable to parse seconds: %s: %s", fields[1], err) } defaultTimeZone = time.FixedZone(fields[0], offs) - logger.Logf("using fixed timezone %s, offset %d ", defaultTimeZone.String(), offs) + LogApi.Infof("using fixed timezone %s, offset %d ", defaultTimeZone.String(), offs) } if cpus != 0 { - logger.Logln("using GOMAXPROCS", cpus) + LogApi.Println("using GOMAXPROCS", cpus) runtime.GOMAXPROCS(cpus) } @@ -772,9 +764,9 @@ func RunCarbonApi(conf *config.Config) { host = graphiteHost } - logger.Logln("Using graphite host", host) + LogApi.Println("Using graphite host", host) - logger.Logln("setting stats interval to", interval) + LogApi.Println("setting stats interval to", interval) // register our metrics with graphite graphite := g2g.NewGraphite(host, interval, 10*time.Second) @@ -811,14 +803,14 @@ func RunCarbonApi(conf *config.Config) { t0 := time.Now() renderHandler(w, r, &stats) since := time.Since(t0) - logger.Logln(r.RequestURI, since.Nanoseconds()/int64(time.Millisecond), stats.zipperRequests) + LogApi.Infoln(r.RequestURI, since.Nanoseconds()/int64(time.Millisecond), stats.zipperRequests) } if pidFile != "" { pidfile.SetPidfilePath(pidFile) err := pidfile.Write() if err != nil { - logger.Fatalln("error during pidfile.Write():", err) + LogApi.Fatalln("error during pidfile.Write():", err) } } @@ -839,10 +831,10 @@ func RunCarbonApi(conf *config.Config) { r.HandleFunc("/lb_check", lbcheckHandler) r.HandleFunc("/", usageHandler) - logger.Logln("listening on port", port) + LogApi.Println("listening on port", port) handler := handlers.CompressHandler(r) handler = handlers.CORS()(handler) - handler = handlers.CombinedLoggingHandler(mlog.GetOutput(), handler) + handler = handlers.CombinedLoggingHandler(LogApi.Out, handler) err := gracehttp.Serve(&http.Server{ Addr: ":" + strconv.Itoa(port), @@ -850,6 +842,6 @@ func RunCarbonApi(conf *config.Config) { }) if err != nil { - logger.Fatalln(err) + LogApi.Fatalln(err) } } diff --git a/graphite/graphite.go b/graphite/graphite.go index 0da492c5c..758588f14 100644 --- a/graphite/graphite.go +++ b/graphite/graphite.go @@ -6,6 +6,7 @@ import ( "net" "net/http" "os" + "os/exec" "os/signal" "os/user" "path/filepath" @@ -23,6 +24,7 @@ import ( ) var Log = logrus.New() +var User, _ = user.Current() // Graphite is a struct that defines the relevant properties of a graphite // connection @@ -245,6 +247,8 @@ func RunCarbon(conf *config.Config) error { os.Exit(1) } + exec.Command("chown", fmt.Sprintf("%s:%s", User.Uid, User.Gid), conf.WorkingDir+"/carbon.conf").Run() + carbon.Log = Log app := carbon.New(conf.WorkingDir + "/carbon.conf") @@ -253,7 +257,7 @@ func RunCarbon(conf *config.Config) error { } app.Config.Common.Logfile = conf.WorkingDir + "/carbon.log" - // log.Fatal(app.Config.Whisper.SchemasFilename) + app.Config.Common.User = User.Username cfg := app.Config var runAsUser *user.User diff --git a/server/server.go b/server/server.go index 8249344f2..11fbf2bd7 100644 --- a/server/server.go +++ b/server/server.go @@ -17,6 +17,7 @@ import ( "io" "log/syslog" "net" + "os/exec" "os/signal" "os/user" "runtime" @@ -40,7 +41,9 @@ import ( "github.com/spf13/viper" "golang.org/x/oauth2" "google.golang.org/grpc" + "gopkg.in/natefinch/lumberjack.v2" + "github.com/sirupsen/logrus" clog "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus" lSyslog "github.com/sirupsen/logrus/hooks/syslog" @@ -1673,6 +1676,15 @@ func (repman *ReplicationManager) Run() error { // Defer to recover and log panics defer repman.LogPanicToFile() + ExpectedUser := repman.OsUser + + if repman.OsUser.Uid == "0" && repman.Conf.MonitoringSystemUser != "" { + u, err := user.Lookup(repman.Conf.MonitoringSystemUser) + if err == nil { + ExpectedUser = u + } + } + repman.Version = Version repman.Fullversion = FullVersion repman.Arch = GoArch @@ -1750,7 +1762,7 @@ func (repman *ReplicationManager) Run() error { loglen := repman.termlength - 9 - (len(strings.Split(repman.Conf.Hosts, ",")) * 3) repman.tlog = s18log.NewTermLog(loglen) repman.Logs = s18log.NewHttpLog(80) - repman.InitServicePlans() + repman.InitServicePlans(ExpectedUser) repman.ServiceOrchestrators = repman.Conf.GetOrchestratorsProv() repman.InitGrants() repman.InitRoles() @@ -1802,6 +1814,7 @@ func (repman *ReplicationManager) Run() error { // Initialize go-carbon if repman.Conf.GraphiteEmbedded { + graphite.User = ExpectedUser graphite.Log = repman.clog graphite.Log.AddHook(&writer.Hook{ // Send logs with level higher than warning to stderr Writer: os.Stderr, @@ -1819,6 +1832,26 @@ func (repman *ReplicationManager) Run() error { "httpport": repman.Conf.GraphiteCarbonServerPort, }).Info("Carbon server started") time.Sleep(2 * time.Second) + + carbonApiLog := &lumberjack.Logger{ + Filename: repman.Conf.WorkingDir + "/carbonapi.log", // Log file name + MaxSize: repman.Conf.LogRotateMaxSize, + MaxBackups: repman.Conf.LogRotateMaxBackup, + MaxAge: repman.Conf.LogRotateMaxAge, + Compress: true, // Compress rotated log files + } + + // Set Logrus to write only to the log file + graphite.LogApi.SetOutput(carbonApiLog) + + // Optional: Configure log level and formatter + graphite.LogApi.SetLevel(config.ToLogrusLevel(repman.Conf.LogGraphiteLevel)) + graphite.LogApi.SetFormatter(&logrus.TextFormatter{ + DisableColors: true, + TimestampFormat: "2006-01-02 15:04:05", + FullTimestamp: true, + }) + go graphite.RunCarbonApi(&repman.Conf) repman.Logrus.WithField("apiport", repman.Conf.GraphiteCarbonApiPort).Info("Carbon server API started") } @@ -1830,16 +1863,6 @@ func (repman *ReplicationManager) Run() error { repman.Logrus.Infof("repman.Conf.ShareDir : %s", repman.Conf.ShareDir) repman.initKeys() - repman.LimitPrivileges() - - for _, gl := range repman.ClusterList { - repman.StartCluster(gl) - } - for _, cluster := range repman.Clusters { - cluster.SetClusterList(repman.Clusters) - - cluster.SetCarbonLogger(repman.clog) - } // repman.currentCluster.SetCfgGroupDisplay(strClusters) if repman.Conf.ApiServ { @@ -1850,6 +1873,16 @@ func (repman *ReplicationManager) Run() error { go repman.httpserver() } + repman.LimitPrivileges() + + for _, gl := range repman.ClusterList { + repman.StartCluster(gl) + } + for _, cluster := range repman.Clusters { + cluster.SetClusterList(repman.Clusters) + cluster.SetCarbonLogger(repman.clog) + } + if _, err := os.Stat(conf.WorkingDir + "/cloud18.toml"); os.IsNotExist(err) { repman.Conf.ReadCloud18Config(repman.ViperConfig) } @@ -2239,7 +2272,7 @@ func (repman *ReplicationManager) DownloadFile(url string, file string) error { return nil } -func (repman *ReplicationManager) InitServicePlans() error { +func (repman *ReplicationManager) InitServicePlans(u *user.User) error { var err error if !repman.Conf.Test { @@ -2265,6 +2298,11 @@ func (repman *ReplicationManager) InitServicePlans() error { return err } + if repman.OsUser.Uid == "0" && u.Uid != "0" { + exec.Command("chown", fmt.Sprintf("%s:%s", u.Uid, u.Gid), repman.Conf.WorkingDir+"/serviceplan.csv").Run() + exec.Command("chown", fmt.Sprintf("%s:%s", u.Uid, u.Gid), repman.Conf.WorkingDir+"/serviceplan.json").Run() + } + file, err := os.ReadFile(repman.Conf.WorkingDir + "/serviceplan.json") if err != nil { repman.Logrus.Errorf("failed opening file because: %s", err.Error()) diff --git a/utils/misc/files.go b/utils/misc/files.go index 780084a6f..9f15d00dc 100644 --- a/utils/misc/files.go +++ b/utils/misc/files.go @@ -5,8 +5,9 @@ import ( "fmt" "io" "io/fs" - "log" "os" + "os/exec" + "os/user" "path/filepath" "strings" "time" @@ -254,7 +255,6 @@ func CopyFilesWithSuffix(srcDir, dstDir string, suffixes ...string) error { for _, sfx := range suffixes { if strings.HasSuffix(d.Name(), sfx) { destPath := filepath.Join(dstDir, d.Name()) - log.Printf("Copying %s to %s\n", path, destPath) err := CopyFile(path, destPath) if err != nil { return err @@ -278,7 +278,6 @@ func CopyFilesWithPrefix(srcDir, dstDir string, prefixes ...string) error { for _, pfx := range prefixes { if strings.HasPrefix(d.Name(), pfx) { destPath := filepath.Join(dstDir, d.Name()) - log.Printf("Copying %s to %s\n", path, destPath) err := CopyFile(path, destPath) if err != nil { return err @@ -302,7 +301,6 @@ func CopyFilesContainFilenames(srcDir, dstDir string, substrings ...string) erro for _, substr := range substrings { if strings.Contains(d.Name(), substr) { destPath := filepath.Join(dstDir, d.Name()) - log.Printf("Copying %s to %s\n", path, destPath) err := CopyFile(path, destPath) if err != nil { return err @@ -314,3 +312,21 @@ func CopyFilesContainFilenames(srcDir, dstDir string, substrings ...string) erro return nil }) } + +func CloseAndChown(f *os.File, u *user.User) (err error) { + defer func() { + e := ChownFile(f, u) + if err == nil { + err = e + } + }() + + err = f.Close() + + return +} + +func ChownFile(f *os.File, u *user.User) error { + cmd := exec.Command("chown", fmt.Sprintf("%s:%s", u.Uid, u.Gid), f.Name()) + return cmd.Run() +} From 41711e7177d3ff6df8b1d01ee107cacb081202b8 Mon Sep 17 00:00:00 2001 From: caffeinated92 Date: Wed, 13 Nov 2024 16:16:54 +0400 Subject: [PATCH 2/4] implement logrotate daily for carbonapi log --- server/server.go | 15 ++++++++++++++- server/server_log.go | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/server/server.go b/server/server.go index 11fbf2bd7..7a8a7fe64 100644 --- a/server/server.go +++ b/server/server.go @@ -58,6 +58,7 @@ import ( "github.com/signal18/replication-manager/opensvc" "github.com/signal18/replication-manager/regtest" "github.com/signal18/replication-manager/repmanv3" + "github.com/signal18/replication-manager/utils/cron" "github.com/signal18/replication-manager/utils/githelper" "github.com/signal18/replication-manager/utils/misc" "github.com/signal18/replication-manager/utils/s18log" @@ -126,6 +127,7 @@ type ReplicationManager struct { v3Config Repmanv3Config `json:"-"` cloud18CheckSum hash.Hash `json:"-"` clog *clog.Logger `json:"-"` + cApiLog *clog.Logger `json:"-"` Logrus *log.Logger `json:"-"` IsSavingConfig bool `json:"isSavingConfig"` HasSavingConfigQueue bool `json:"hasSavingConfigQueue"` @@ -133,6 +135,7 @@ type ReplicationManager struct { CanConnectVault bool `json:"canConnectVault"` IsExportPush bool `json:"-"` errorConnectVault error `json:"-"` + globalScheduler *cron.Cron `json:"-"` CheckSumConfig map[string]hash.Hash `json:"-"` fileHook log.Hook repmanv3.UnimplementedClusterPublicServiceServer `json:"-"` @@ -1675,6 +1678,7 @@ func (repman *ReplicationManager) Run() error { // Defer to recover and log panics defer repman.LogPanicToFile() + repman.globalScheduler = cron.New() ExpectedUser := repman.OsUser @@ -1691,6 +1695,7 @@ func (repman *ReplicationManager) Run() error { repman.Os = GoOS repman.MemProfile = memprofile repman.CpuProfile = cpuprofile + repman.cApiLog = clog.New() repman.clog = clog.New() repman.CheckSumConfig = make(map[string]hash.Hash) @@ -1833,6 +1838,8 @@ func (repman *ReplicationManager) Run() error { }).Info("Carbon server started") time.Sleep(2 * time.Second) + graphite.LogApi = repman.cApiLog + carbonApiLog := &lumberjack.Logger{ Filename: repman.Conf.WorkingDir + "/carbonapi.log", // Log file name MaxSize: repman.Conf.LogRotateMaxSize, @@ -1840,7 +1847,6 @@ func (repman *ReplicationManager) Run() error { MaxAge: repman.Conf.LogRotateMaxAge, Compress: true, // Compress rotated log files } - // Set Logrus to write only to the log file graphite.LogApi.SetOutput(carbonApiLog) @@ -1852,6 +1858,11 @@ func (repman *ReplicationManager) Run() error { FullTimestamp: true, }) + // Set up a daily job to check and rotate the log file at midnight + repman.globalScheduler.AddFunc("@daily", func() { + repman.CheckAndRotateLog(carbonApiLog, ExpectedUser) + }) + go graphite.RunCarbonApi(&repman.Conf) repman.Logrus.WithField("apiport", repman.Conf.GraphiteCarbonApiPort).Info("Carbon server API started") } @@ -1873,6 +1884,8 @@ func (repman *ReplicationManager) Run() error { go repman.httpserver() } + repman.globalScheduler.Start() + repman.LimitPrivileges() for _, gl := range repman.ClusterList { diff --git a/server/server_log.go b/server/server_log.go index 8961c1d88..cf1c705cb 100644 --- a/server/server_log.go +++ b/server/server_log.go @@ -2,13 +2,16 @@ package server import ( "fmt" + "os" + "os/exec" + "os/user" "runtime/debug" "time" "github.com/signal18/replication-manager/config" "github.com/signal18/replication-manager/utils/s18log" - "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus" + "gopkg.in/natefinch/lumberjack.v2" ) // State Levels @@ -96,7 +99,7 @@ func (repman *ReplicationManager) LogModulePrintf(forcingLog bool, module int, l func (repman *ReplicationManager) LogPanicToFile() { if r := recover(); r != nil { - repman.Logrus.WithFields(logrus.Fields{ + repman.Logrus.WithFields(log.Fields{ "cluster": "none", "panic": r, "stacktrace": string(debug.Stack()), @@ -132,3 +135,30 @@ func (repman *ReplicationManager) UpdateFileHookLogLevel(hook *s18log.RotateFile return nil } + +// checkAndRotateLog checks if the log file has any content before rotating +func (repman *ReplicationManager) CheckAndRotateLog(logFile *lumberjack.Logger, u *user.User) { + defer repman.LogPanicToFile() + fileInfo, err := os.Stat(logFile.Filename) + if err != nil { + if os.IsNotExist(err) { + fmt.Println("Log file does not exist, no rotation needed.") + return + } + fmt.Println("Error checking log file:", err) + return + } + + // Only rotate if the file has content (size > 0) + if fileInfo.Size() > 0 { + err := logFile.Rotate() + if err != nil { + fmt.Println("Failed to rotate log file:", err) + } else { + exec.Command("chown", fmt.Sprintf("%s:%s", u.Uid, u.Gid), logFile.Filename).Run() + fmt.Println("Log file rotated.") + } + } else { + fmt.Println("Log file is empty, no rotation performed.") + } +} From 8cbaba0ada82bf40bea4c4f9e5165f4a1634646c Mon Sep 17 00:00:00 2001 From: caffeinated92 Date: Thu, 14 Nov 2024 11:29:14 +0700 Subject: [PATCH 3/4] file permission compatibility with old versions before limit privileges --- server/server.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/server/server.go b/server/server.go index 7a8a7fe64..83015352c 100644 --- a/server/server.go +++ b/server/server.go @@ -1686,6 +1686,11 @@ func (repman *ReplicationManager) Run() error { u, err := user.Lookup(repman.Conf.MonitoringSystemUser) if err == nil { ExpectedUser = u + + // Compatibility with old version, for files with root level permission in workingdir + uid, _ := strconv.Atoi(ExpectedUser.Uid) + gid, _ := strconv.Atoi(ExpectedUser.Gid) + misc.ChownR(repman.Conf.WorkingDir, uid, gid) } } From 0342c1d1bb5093959e7f084856abdd4f82dc94ee Mon Sep 17 00:00:00 2001 From: caffeinated92 Date: Thu, 14 Nov 2024 11:33:59 +0700 Subject: [PATCH 4/4] move chown to LimitPrivileges function --- server/server.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/server/server.go b/server/server.go index 83015352c..66e8f5352 100644 --- a/server/server.go +++ b/server/server.go @@ -1621,6 +1621,9 @@ func (repman *ReplicationManager) LimitPrivileges() { repman.LogModulePrintf(repman.Conf.Verbose, config.ConstLogModGeneral, config.LvlInfo, "Setting uid and gid to target user: %s, uid: %d, gid: %d", targetUser.Username, uidInt, gidInt) + // Compatibility with old version, for files with root level permission in workingdir + misc.ChownR(repman.Conf.WorkingDir, uidInt, gidInt) + // Set GID (Group ID) err = syscall.Setgid(gidInt) if err != nil { @@ -1686,11 +1689,6 @@ func (repman *ReplicationManager) Run() error { u, err := user.Lookup(repman.Conf.MonitoringSystemUser) if err == nil { ExpectedUser = u - - // Compatibility with old version, for files with root level permission in workingdir - uid, _ := strconv.Atoi(ExpectedUser.Uid) - gid, _ := strconv.Atoi(ExpectedUser.Gid) - misc.ChownR(repman.Conf.WorkingDir, uid, gid) } }