Skip to content

Commit d8dbf9e

Browse files
committed
add param to bspagent cmd specifying folder for file logging
1 parent 63966a3 commit d8dbf9e

File tree

2 files changed

+92
-19
lines changed

2 files changed

+92
-19
lines changed

cmd/bspagent/main.go

Lines changed: 65 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ import (
55
"context"
66
"flag"
77
"fmt"
8+
"io"
9+
"net/url"
810
"os"
911
"os/signal"
12+
"path"
1013
"strings"
1114
"sync"
1215
"syscall"
@@ -21,6 +24,7 @@ import (
2124
uuid "github.com/satori/go.uuid"
2225
log "github.com/sirupsen/logrus"
2326
"github.com/ubiq/go-ubiq/rlp"
27+
"golang.org/x/sys/unix"
2428
"gopkg.in/avro.v0"
2529
"gopkg.in/natefinch/lumberjack.v2"
2630

@@ -49,6 +53,7 @@ var (
4953
proofChainFlag string
5054
binaryFilePathFlag string
5155
websocketURLsFlag string
56+
logsFolderFlag string = "./logs/"
5257

5358
// stream processing vars
5459
start = ">"
@@ -60,25 +65,7 @@ var (
6065
blockReplica types.BlockReplica
6166
)
6267

63-
func init() {
64-
formatter := runtime.Formatter{ChildFormatter: &log.TextFormatter{
65-
FullTimestamp: true,
66-
}}
67-
formatter.Line = true
68-
log.SetFormatter(&formatter)
69-
bspLoggerOutput := utils.NewLoggerOut(os.Stdout, &lumberjack.Logger{
70-
// logs folder created/searched in directory in which agent was started.
71-
Filename: "./logs/log.log",
72-
MaxSize: 100, // megabytes
73-
MaxBackups: 7,
74-
MaxAge: 10, // days
75-
})
76-
log.SetOutput(&bspLoggerOutput)
77-
log.SetLevel(log.InfoLevel)
78-
log.WithFields(log.Fields{"file": "main.go"}).Info("bsp-agent is running...")
79-
}
80-
81-
func main() {
68+
func parseFlags() {
8269
flag.StringVar(&redisURLFlag, "redis-url", utils.LookupEnvOrString("RedisURL", redisURLFlag), "redis consumer stream url")
8370
flag.StringVar(&avroCodecPathFlag, "avro-codec-path", utils.LookupEnvOrString("CodecPath", avroCodecPathFlag), "local path to AVRO .avsc files housing the specimen/result schemas")
8471
flag.StringVar(&binaryFilePathFlag, "binary-file-path", utils.LookupEnvOrString("BinaryFilePath", binaryFilePathFlag), "local path to AVRO encoded binary files that contain block-replicas")
@@ -88,8 +75,43 @@ func main() {
8875
flag.StringVar(&websocketURLsFlag, "websocket-urls", utils.LookupEnvOrString("WebsocketURLs", websocketURLsFlag), "url to websockets clients separated by space")
8976
flag.IntVar(&segmentLengthFlag, "segment-length", utils.LookupEnvOrInt("SegmentLength", segmentLengthFlag), "number of block specimen/results within a single uploaded avro encoded object")
9077
flag.IntVar(&consumerPendingTimeoutFlag, "consumer-timeout", utils.LookupEnvOrInt("ConsumerPendingTimeout", consumerPendingTimeoutFlag), "number of seconds to wait before pending messages consumer timeout")
78+
flag.StringVar(&logsFolderFlag, "logs-folder", utils.LookupEnvOrString("LogsFolder", logsFolderFlag), "Location where the log files should be placed")
9179
flag.Parse()
80+
}
81+
82+
func init() {
83+
parseFlags()
84+
85+
// setup logger
86+
formatter := runtime.Formatter{ChildFormatter: &log.TextFormatter{
87+
FullTimestamp: true,
88+
}}
89+
formatter.Line = true
90+
log.SetFormatter(&formatter)
9291

92+
var outWriter io.Writer
93+
logLocationURL, err := getLogLocationURL(logsFolderFlag)
94+
if err != nil {
95+
log.Warn("error while setting up file logging: ", err)
96+
outWriter = os.Stdout
97+
} else {
98+
logFilePath := path.Join(logLocationURL.Path, "log.log")
99+
bspLogger := utils.NewLoggerOut(os.Stdout, &lumberjack.Logger{
100+
// logs folder created/searched in directory in which agent was started.
101+
Filename: logFilePath,
102+
MaxSize: 100, // megabytes
103+
MaxBackups: 7,
104+
MaxAge: 10, // days
105+
})
106+
outWriter = &bspLogger
107+
}
108+
109+
log.SetOutput(outWriter)
110+
log.SetLevel(log.InfoLevel)
111+
log.WithFields(log.Fields{"file": "main.go"}).Info("bsp-agent is running...")
112+
}
113+
114+
func main() {
93115
config, err := config.LoadConfig()
94116
if err != nil {
95117
panic(err)
@@ -284,3 +306,27 @@ func processStream(config *config.Config, replicaCodec *goavro.Codec, redisClien
284306
}
285307
}
286308
}
309+
310+
func getLogLocationURL(logPath string) (*url.URL, error) {
311+
logLocation := utils.ExpandPath(logPath)
312+
locationURL, err := url.Parse(logLocation)
313+
if err == nil {
314+
if _, existErr := os.Stat(locationURL.Path); os.IsNotExist(existErr) {
315+
// directory doesn't exist, create
316+
createErr := os.Mkdir(locationURL.Path, os.ModePerm)
317+
if createErr != nil {
318+
return nil, fmt.Errorf("error creating the directory: %v", createErr)
319+
}
320+
}
321+
322+
if !writable(locationURL.Path) {
323+
return nil, fmt.Errorf("write access not present for given log location")
324+
}
325+
}
326+
327+
return locationURL, err
328+
}
329+
330+
func writable(path string) bool {
331+
return unix.Access(path, unix.W_OK) == nil
332+
}

internal/utils/utils.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import (
1010
"fmt"
1111
"net/url"
1212
"os"
13+
"os/user"
14+
"path"
1315
"strconv"
1416
"strings"
1517

@@ -166,3 +168,28 @@ func DecodeAvro(record avro.AvroRecord, buffer []byte) error {
166168

167169
return reader.Read(record, decoder)
168170
}
171+
172+
// ExpandPath expands a file path
173+
// 1. replace tilde with users home dir
174+
// 2. expands embedded environment variables
175+
// 3. cleans the path, e.g. /a/b/../c -> /a/c
176+
// Note, it has limitations, e.g. ~someuser/tmp will not be expanded
177+
func ExpandPath(p string) string {
178+
if strings.HasPrefix(p, "~/") || strings.HasPrefix(p, "~\\") {
179+
if home := HomeDir(); home != "" {
180+
p = home + p[1:]
181+
}
182+
}
183+
return path.Clean(os.ExpandEnv(p))
184+
}
185+
186+
// HomeDir returns full path of home directory for current user
187+
func HomeDir() string {
188+
if home := os.Getenv("HOME"); home != "" {
189+
return home
190+
}
191+
if usr, err := user.Current(); err == nil {
192+
return usr.HomeDir
193+
}
194+
return ""
195+
}

0 commit comments

Comments
 (0)