예제 #1
0
// Loads the beat specific config and overwrites params based on cmd line
func (pb *Packetbeat) Config(b *beat.Beat) error {

	// Read beat implementation config as needed for setup
	err := cfgfile.Read(&pb.PbConfig, "")

	// CLI flags over-riding config
	if *pb.CmdLineArgs.TopSpeed {
		pb.PbConfig.Interfaces.TopSpeed = true
	}

	if len(*pb.CmdLineArgs.File) > 0 {
		pb.PbConfig.Interfaces.File = *pb.CmdLineArgs.File
	}

	pb.PbConfig.Interfaces.Loop = *pb.CmdLineArgs.Loop
	pb.PbConfig.Interfaces.OneAtATime = *pb.CmdLineArgs.OneAtAtime

	if len(*pb.CmdLineArgs.Dumpfile) > 0 {
		pb.PbConfig.Interfaces.Dumpfile = *pb.CmdLineArgs.Dumpfile
	}

	// assign global singleton as it is used in protocols
	// TODO: Refactor
	config.ConfigSingleton = pb.PbConfig

	return err
}
예제 #2
0
func TestReadConfig(t *testing.T) {
	absPath, err := filepath.Abs("../tests/files/")

	assert.NotNil(t, absPath)
	assert.Nil(t, err)

	config := &Config{}

	err = cfgfile.Read(config, absPath+"/config.yml")

	assert.Nil(t, err)

	assert.Equal(t, uint64(1024), config.Filebeat.SpoolSize)
	assert.Equal(t, "/prospectorConfigs/", config.Filebeat.ConfigDir)

	prospectors := config.Filebeat.Prospectors

	// Check if multiple paths were read in
	assert.Equal(t, 3, len(prospectors))

	// Check if full array can be read. Assumed that are ordered same as in config file
	assert.Equal(t, 2, len(prospectors[0].Paths))
	assert.Equal(t, "/var/log/s*.log", prospectors[0].Paths[1])
	assert.Equal(t, "log", prospectors[0].Input)
	assert.Equal(t, 3, len(prospectors[0].Harvester.Fields))
	assert.Equal(t, 1, len(prospectors[0].Harvester.Fields["review"]))
	assert.Equal(t, "24h", prospectors[0].IgnoreOlder)
	assert.Equal(t, "10s", prospectors[0].ScanFrequency)

	assert.Equal(t, "stdin", prospectors[2].Input)
	assert.Equal(t, 0, len(prospectors[2].Paths))
	assert.Equal(t, "", prospectors[1].ScanFrequency)
}
예제 #3
0
func (tb *Topbeat) Config(b *beat.Beat) error {

	err := cfgfile.Read(&tb.TbConfig, "")
	if err != nil {
		logp.Err("Error reading configuration file: %v", err)
		return err
	}

	if tb.TbConfig.Input.Period != nil {
		tb.period = time.Duration(*tb.TbConfig.Input.Period) * time.Second
	} else {
		tb.period = 1 * time.Second
	}
	if tb.TbConfig.Input.Procs != nil {
		tb.procs = *tb.TbConfig.Input.Procs
	} else {
		tb.procs = []string{".*"} //all processes
	}

	logp.Debug("topbeat", "Init toppbeat")
	logp.Debug("topbeat", "Follow processes %q\n", tb.procs)
	logp.Debug("topbeat", "Period %v\n", tb.period)

	return nil
}
예제 #4
0
func (d *Dockerbeat) Config(b *beat.Beat) error {

	err := cfgfile.Read(&d.TbConfig, "")
	if err != nil {
		logp.Err("Error reading configuration file: %v", err)
		return err
	}

	//init the period
	if d.TbConfig.Input.Period != nil {
		d.period = time.Duration(*d.TbConfig.Input.Period) * time.Second
	} else {
		d.period = 1 * time.Second
	}
	//init the socket
	if d.TbConfig.Input.Socket != nil {
		d.socket = *d.TbConfig.Input.Socket
	} else {
		d.socket = "unix:///var/run/docker.sock" // default docker socket location
	}

	logp.Debug("dockerbeat", "Init dockerbeat")
	logp.Debug("dockerbeat", "Follow docker socket %q\n", d.socket)
	logp.Debug("dockerbeat", "Period %v\n", d.period)

	return nil
}
예제 #5
0
파일: beat.go 프로젝트: j0nix/topbeat
// LoadConfig inits the config file and reads the default config information
// into Beat.Config. It exists the processes in case of errors.
func (b *Beat) LoadConfig() {

	err := cfgfile.Read(&b.Config, "")
	if err != nil {
		// logging not yet initialized, so using fmt.Printf
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}

	err = logp.Init(b.Name, &b.Config.Logging)
	if err != nil {
		fmt.Printf("Error initializing logging: %v\n", err)
		os.Exit(1)
	}

	logp.Debug("beat", "Initializing output plugins")

	if err := publisher.Publisher.Init(b.Name, b.Version, b.Config.Output, b.Config.Shipper); err != nil {
		logp.Critical(err.Error())
		os.Exit(1)
	}

	b.Events = publisher.Publisher.Client()

	logp.Debug("beat", "Init %s", b.Name)
}
예제 #6
0
func TestReadConfig(t *testing.T) {
	absPath, err := filepath.Abs("../tests/files/")

	assert.NotNil(t, absPath)
	assert.Nil(t, err)

	config := &Config{}

	err = cfgfile.Read(config, absPath+"/config.yml")

	assert.Nil(t, err)

	files := config.Filebeat.Files

	// Check if multiple paths were read in
	assert.Equal(t, 3, len(files))

	// Check if full array can be read. Assumed that are ordered same as in config file
	assert.Equal(t, 2, len(files[0].Paths))
	assert.Equal(t, "/var/log/s*.log", files[0].Paths[1])
	assert.Equal(t, "log", files[0].Input)
	assert.Equal(t, 3, len(files[0].Fields))
	assert.Equal(t, 1, len(files[0].Fields["review"]))
	assert.Equal(t, "24h", files[0].IgnoreOlder)

	assert.Equal(t, "stdin", files[2].Input)
	assert.Equal(t, 0, len(files[2].Paths))

}
예제 #7
0
// Config Uwsgibeat according to uwsgibeat.yml.
func (ub *Uwsgibeat) Config(b *beat.Beat) error {
	err := cfgfile.Read(&ub.UbConfig, "")
	if err != nil {
		logp.Err("Error reading configuration file: %v", err)
		return err
	}

	var u string
	if ub.UbConfig.Input.URL != "" {
		u = ub.UbConfig.Input.URL
	} else {
		u = "127.0.0.1:1717"
	}
	ub.url, err = url.Parse(u)
	if err != nil {
		logp.Err("Invalid uWSGI stats server address: %v", err)
		return err
	}

	if ub.UbConfig.Input.Period != nil {
		ub.period = time.Duration(*ub.UbConfig.Input.Period) * time.Second
	} else {
		ub.period = 1 * time.Second
	}

	logp.Debug(selector, "Init uwsgibeat")
	logp.Debug(selector, "Watch %v", ub.url)
	logp.Debug(selector, "Period %v", ub.period)

	return nil
}
예제 #8
0
파일: beat.go 프로젝트: ruflin/dfbeat
func (beat *Beat) ConfigSetup(beater Beater, inputConfig interface{}) {

	config := &ConfigSettings{
	//Input: inputConfig,
	}

	err := cfgfile.Read(config)

	beat.Config = *config

	if err != nil {
		logp.Debug("Log read error", "Error %v\n", err)
	}

	logp.Init(beat.Name, &beat.Config.Logging)

	logp.Debug("main", "Initializing output plugins")

	if err := publisher.Publisher.Init(beat.Config.Output, beat.Config.Shipper); err != nil {
		logp.Critical(err.Error())
		os.Exit(1)
	}

	beat.events = publisher.Publisher.Queue

	logp.Debug(beat.Name, "Init %s", beat.Name)

	if err := beater.Init(beat); err != nil {

		logp.Critical(err.Error())
		os.Exit(1)
	}
}
예제 #9
0
func (eb *Winlogbeat) Config(b *beat.Beat) error {
	// Read configuration.
	err := cfgfile.Read(&eb.config, "")
	if err != nil {
		return fmt.Errorf("Error reading configuration file. %v", err)
	}

	// Validate configuration.
	err = eb.config.Winlogbeat.Validate()
	if err != nil {
		return fmt.Errorf("Error validating configuration file. %v", err)
	}
	debugf("Configuration validated. config=%v", eb.config)

	// Registry file grooming.
	if eb.config.Winlogbeat.RegistryFile == "" {
		eb.config.Winlogbeat.RegistryFile = config.DefaultRegistryFile
	}
	eb.config.Winlogbeat.RegistryFile, err = filepath.Abs(
		eb.config.Winlogbeat.RegistryFile)
	if err != nil {
		return fmt.Errorf("Error getting absolute path of registry file %s. %v",
			eb.config.Winlogbeat.RegistryFile, err)
	}
	logp.Info("State will be read from and persisted to %s",
		eb.config.Winlogbeat.RegistryFile)

	return nil
}
예제 #10
0
파일: beat.go 프로젝트: urso/topbeat
// LoadConfig inits the config file and reads the default config information
// into Beat.Config. It exists the processes in case of errors.
func (b *Beat) LoadConfig() {

	err := cfgfile.Read(&b.Config, "")
	if err != nil {
		// logging not yet initialized, so using fmt.Printf
		fmt.Printf("Loading config file error: %v\n", err)
		os.Exit(1)
	}

	err = logp.Init(b.Name, &b.Config.Logging)
	if err != nil {
		fmt.Printf("Error initializing logging: %v\n", err)
		os.Exit(1)
	}

	// Disable stderr logging if requested by cmdline flag
	logp.SetStderr()

	logp.Debug("beat", "Initializing output plugins")

	if err := publisher.Publisher.Init(b.Name, b.Config.Output, b.Config.Shipper); err != nil {
		fmt.Printf("Error Initialising publisher: %v\n", err)
		logp.Critical(err.Error())
		os.Exit(1)
	}

	b.Events = publisher.Publisher.Client()

	logp.Debug("beat", "Init %s", b.Name)
}
예제 #11
0
// Config Gzipbeat according to gzipbeat.yml.
func (gb *Gzipbeat) Config(b *beat.Beat) error {
	err := cfgfile.Read(&gb.config, "")
	if err != nil {
		logp.Err("Error reading configuration file: %v", err)
		return err
	}

	return nil
}
예제 #12
0
파일: pingbeat.go 프로젝트: sreev/pingbeat
func (p *Pingbeat) Config(b *beat.Beat) error {
	// Read in provided config file, bail if problem
	err := cfgfile.Read(&p.config, "")
	if err != nil {
		logp.Err("Error reading configuration file: %v", err)
		return err
	}

	// Use period provided in config or default to 5s
	if p.config.Input.Period != nil {
		p.period = time.Duration(*p.config.Input.Period) * time.Second
	} else {
		p.period = 5 * time.Second
	}
	logp.Debug("pingbeat", "Period %v\n", p.period)

	// Check if we can use privileged (i.e. raw socket) ping,
	// else use a UDP ping
	if *p.config.Input.Privileged {
		p.pingType = "ip"
	} else {
		p.pingType = "udp"
	}
	logp.Debug("pingbeat", "Using %v for pings\n", p.pingType)

	// Check whether IPv4/IPv6 pings are requested in config
	// Default to just IPv4 pings
	if &p.config.Input.UseIPv4 != nil {
		p.useIPv4 = *p.config.Input.UseIPv4
	} else {
		p.useIPv4 = true
	}
	if &p.config.Input.UseIPv6 != nil {
		p.useIPv6 = *p.config.Input.UseIPv6
	} else {
		p.useIPv6 = false
	}
	logp.Debug("pingbeat", "IPv4: %v, IPv6: %v\n", p.useIPv4, p.useIPv6)

	// Fill the IPv4/IPv6 targets maps
	p.ipv4targets = make(map[string][2]string)
	p.ipv6targets = make(map[string][2]string)
	if p.config.Input.Targets != nil {
		for tag, targets := range *p.config.Input.Targets {
			for i := 0; i < len(targets); i++ {
				p.AddTarget(targets[i], tag)
			}
		}
	} else {
		logp.Critical("Error: no targets specified, cannot continue!")
		os.Exit(1)
	}

	return nil
}
예제 #13
0
// mergeConfigFiles reads in all config files given by list configFiles and merges them into config
func mergeConfigFiles(configFiles []string, config *Config) error {

	for _, file := range configFiles {
		tmpConfig := &Config{}
		cfgfile.Read(tmpConfig, file)

		config.Filebeat.Files = append(config.Filebeat.Files, tmpConfig.Filebeat.Files...)
	}

	return nil
}
예제 #14
0
func (h *Httpbeat) Config(b *beat.Beat) error {

	err := cfgfile.Read(&h.HbConfig, "")
	if err != nil {
		logp.Err("Error reading configuration file: %v", err)
		return err
	}

	logp.Info("httpbeat", "Init httpbeat")

	return nil
}
예제 #15
0
func TestJournalCfgIsOptional(t *testing.T) {
	var settings Settings
	cfgfile.Read(&settings, "./testfiles/minimal.yml")
	err := settings.SetDefaults()
	assert.Nil(t, err, fmt.Sprintf("Unexected error %v", err))
	jcfg := settings.AmqpInput.Journal
	assert.NotNil(t, jcfg, "JournalConfig be populated with defaults")
	assert.NotNil(t, jcfg.BufferSizeBlocks)
	assert.NotNil(t, jcfg.JournalDir)
	assert.NotNil(t, jcfg.MaxDelayMs)
	assert.NotNil(t, jcfg.MaxFileSizeBytes)
}
예제 #16
0
// mergeConfigFiles reads in all config files given by list configFiles and merges them into config
func mergeConfigFiles(configFiles []string, config *Config) error {

	for _, file := range configFiles {
		logp.Info("Additional configs loaded from: %s", file)

		tmpConfig := &Config{}
		cfgfile.Read(tmpConfig, file)

		config.Filebeat.Prospectors = append(config.Filebeat.Prospectors, tmpConfig.Filebeat.Prospectors...)
	}

	return nil
}
예제 #17
0
// Config extracts settings from the config file
func (mb *Amqpbeat) Config(b *beat.Beat) error {

	// Config loading goes here
	err := cfgfile.Read(&mb.config, "")
	utils.FailOnError(err, "Error reading configuration file")
	//if err != nil {
	//		logp.Err("Error reading configuration file: %v", err)
	//		return err
	//	}

	logp.Debug("amq", " is configured")
	return nil
}
예제 #18
0
// Config setups up the filebeat configuration by fetch all additional config files
func (fb *Filebeat) Config(b *beat.Beat) error {

	// Load Base config
	err := cfgfile.Read(&fb.FbConfig, "")

	if err != nil {
		return fmt.Errorf("Error reading config file: %v", err)
	}

	// Check if optional config_dir is set to fetch additional prospector config files
	fb.FbConfig.FetchConfigs()

	return nil
}
예제 #19
0
func TestReadConfig2(t *testing.T) {
	// Tests with different params from config file
	absPath, err := filepath.Abs("../tests/files/")

	assert.NotNil(t, absPath)
	assert.Nil(t, err)

	config := &Config{}

	// Reads second config file
	err = cfgfile.Read(config, absPath+"/config2.yml")
	assert.Nil(t, err)

	assert.Equal(t, uint64(0), config.Filebeat.SpoolSize)
}
예제 #20
0
파일: topbeat.go 프로젝트: vjsamuel/topbeat
func (tb *Topbeat) Config(b *beat.Beat) error {

	err := cfgfile.Read(&tb.TbConfig, "")
	if err != nil {
		logp.Err("Error reading configuration file: %v", err)
		return err
	}

	if tb.TbConfig.Input.Period != nil {
		tb.period = time.Duration(*tb.TbConfig.Input.Period) * time.Second
	} else {
		tb.period = 10 * time.Second
	}
	if tb.TbConfig.Input.Procs != nil {
		tb.procs = *tb.TbConfig.Input.Procs
	} else {
		tb.procs = []string{".*"} //all processes
	}

	if tb.TbConfig.Input.Stats.System != nil {
		tb.sysStats = *tb.TbConfig.Input.Stats.System
	} else {
		tb.sysStats = true
	}
	if tb.TbConfig.Input.Stats.Proc != nil {
		tb.procStats = *tb.TbConfig.Input.Stats.Proc
	} else {
		tb.procStats = true
	}
	if tb.TbConfig.Input.Stats.Filesystem != nil {
		tb.fsStats = *tb.TbConfig.Input.Stats.Filesystem
	} else {
		tb.fsStats = true
	}

	if !tb.sysStats && !tb.procStats && !tb.fsStats {
		return errors.New("Invalid statistics configuration")
	}

	logp.Debug("topbeat", "Init toppbeat")
	logp.Debug("topbeat", "Follow processes %q\n", tb.procs)
	logp.Debug("topbeat", "Period %v\n", tb.period)
	logp.Debug("topbeat", "System statistics %t\n", tb.sysStats)
	logp.Debug("topbeat", "Process statistics %t\n", tb.procStats)
	logp.Debug("topbeat", "File system statistics %t\n", tb.fsStats)

	return nil
}
예제 #21
0
func (p *Pingbeat) Config(b *beat.Beat) error {
	err := cfgfile.Read(&p.config, "")
	if err != nil {
		logp.Err("Error reading configuration file: %v", err)
		return err
	}

	if p.config.Input.Period != nil {
		p.period = time.Duration(*p.config.Input.Period) * time.Second
	} else {
		p.period = 1 * time.Second
	}
	logp.Debug("pingbeat", "Period %v\n", p.period)

	if *p.config.Input.Privileged {
		p.pingType = "ip"
	} else {
		p.pingType = "udp"
	}
	logp.Debug("pingbeat", "Using %v for pings\n", p.pingType)

	if &p.config.Input.UseIPv4 != nil {
		p.useIPv4 = *p.config.Input.UseIPv4
	} else {
		p.useIPv4 = true
	}
	if &p.config.Input.UseIPv6 != nil {
		p.useIPv6 = *p.config.Input.UseIPv6
	} else {
		p.useIPv6 = false
	}
	logp.Debug("pingbeat", "IPv4: %v, IPv6: %v\n", p.useIPv4, p.useIPv6)

	p.ipv4targets = make(map[string][2]string)
	p.ipv6targets = make(map[string][2]string)
	if p.config.Input.Targets != nil {
		for tag, targets := range *p.config.Input.Targets {
			for i := 0; i < len(targets); i++ {
				p.AddTarget(targets[i], tag)
			}
		}
	} else {
		logp.Critical("Error: no targets specified, cannot continue!")
		os.Exit(1)
	}

	return nil
}
예제 #22
0
// Config setups up the filebeat configuration by fetch all additional config files
func (fb *Filebeat) Config(b *beat.Beat) error {

	// Load Base config
	err := cfgfile.Read(&fb.FbConfig, "")

	if err != nil {
		return fmt.Errorf("Error reading config file: %v", err)
	}

	// This is optiona
	if configDirPath != "" {
		logp.Info("Additional config files are fetched from:", configDirPath)
		fb.FbConfig.FetchConfigs(configDirPath)
	}

	return nil
}
예제 #23
0
func (eb *Winlogbeat) Config(b *beat.Beat) error {
	// Read configuration.
	err := cfgfile.Read(&eb.config, "")
	if err != nil {
		logp.Err("Error reading configuration file. %v", err)
		return err
	}

	// Validate configuration.
	err = eb.config.Winlogbeat.Validate()
	if err != nil {
		logp.Err("Error validating configuration file. %v", err)
		return err
	}
	debugf("Init winlogbeat. Config: %v", eb.config)

	return nil
}
예제 #24
0
func (eb *Eventbeat) Config(b *beat.Beat) error {
	// Read configuration.
	err := cfgfile.Read(&eb.config, "")
	if err != nil {
		logp.Err("Error reading configuration file: %v", err)
		return err
	}

	// Validate configuration.
	err = eb.config.Eventbeat.Validate()
	if err != nil {
		logp.Err("Error validating configuration file: %v", err)
		return err
	}
	logp.Debug("eventbeat", "Init eventbeat. Config: %v", eb.config)

	return nil
}
예제 #25
0
파일: beat.go 프로젝트: hydro2k/topbeat
// Inits the config file and reads the default config information into Beat.Config
// This is Output, Logging and Shipper config params
func (b *Beat) LoadConfig() {

	err := cfgfile.Read(&b.Config)

	if err != nil {
		logp.Debug("Log read error", "Error %v\n", err)
	}

	logp.Init(b.Name, &b.Config.Logging)

	logp.Debug("main", "Initializing output plugins")

	if err := publisher.Publisher.Init(b.Name, b.Config.Output, b.Config.Shipper); err != nil {
		logp.Critical(err.Error())
		os.Exit(1)
	}

	logp.Debug(b.Name, "Init %s", b.Name)
}
예제 #26
0
func (rb *AmqpBeat) ConfigWithFile(b *beat.Beat, filePath string) error {
	err := cfgfile.Read(&rb.RbConfig, filePath)
	if err != nil {
		logp.Err("Error reading configuration file:'%s' %v", filePath, err)
		return err
	}

	err = rb.RbConfig.CheckRequired()
	if err != nil {
		return err
	}

	err = rb.RbConfig.SetDefaults()
	if err != nil {
		return err
	}

	return nil
}
예제 #27
0
func TestReadConfig(t *testing.T) {
	absPath, err := filepath.Abs("./tests/files/")

	assert.NotNil(t, absPath)
	assert.Nil(t, err)

	config := &ConfigSettings{}

	err = cfgfile.Read(config, absPath+"/config.yml")
	assert.Nil(t, err)

	urls := config.Httpbeat.Urls
	assert.Equal(t, 2, len(urls))

	assert.Equal(t, "http://example.org/1", urls[0].Url)
	assert.Equal(t, "get", urls[0].Method)
	assert.Equal(t, int64(5), *urls[0].Period)
	assert.Equal(t, "body", urls[0].Body)
	assert.Equal(t, "foo1", urls[0].Username)
	assert.Equal(t, "bar1", urls[0].Password)
	assert.Equal(t, "proxyUser", urls[0].ProxyUsername)
	assert.Equal(t, "proxyPass", urls[0].ProxyPassword)
	assert.Equal(t, "proxy", urls[0].ProxyHost)
	assert.Equal(t, "3128", urls[0].ProxyPort)
	assert.Equal(t, int64(120), *urls[0].Timeout)
	assert.Equal(t, 2, len(urls[0].Headers))

	assert.Equal(t, "http://example.org/2", urls[1].Url)
	assert.Equal(t, "post", urls[1].Method)
	assert.Equal(t, int64(10), *urls[1].Period)
	assert.Equal(t, "", urls[1].Username)
	assert.Equal(t, "", urls[1].Password)
	assert.Equal(t, "", urls[1].ProxyUsername)
	assert.Equal(t, "", urls[1].ProxyPassword)
	assert.Equal(t, "", urls[1].ProxyHost)
	assert.Equal(t, "", urls[1].ProxyPort)
	assert.Equal(t, 0, len(urls[1].Headers))
}
예제 #28
0
파일: main.go 프로젝트: tsg/topbeat
func main() {

	over := make(chan bool)

	// Use our own FlagSet, because some libraries pollute the global one
	var cmdLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)

	cfgfile.CmdLineFlags(cmdLine, Name)
	logp.CmdLineFlags(cmdLine)
	service.CmdLineFlags(cmdLine)

	publishDisabled := cmdLine.Bool("N", false, "Disable actual publishing for testing")
	printVersion := cmdLine.Bool("version", false, "Print version and exit")

	cmdLine.Parse(os.Args[1:])

	if *printVersion {
		fmt.Printf("%s version %s (%s)\n", Name, Version, runtime.GOARCH)
		return
	}

	err := cfgfile.Read(&Config)

	logp.Init(Name, &Config.Logging)

	logp.Debug("main", "Initializing output plugins")
	if err = publisher.Publisher.Init(*publishDisabled, Config.Output,
		Config.Shipper); err != nil {

		logp.Critical(err.Error())
		os.Exit(1)
	}

	topbeat := &Topbeat{}

	if err = topbeat.Init(Config.Input, publisher.Publisher.Queue); err != nil {
		logp.Critical(err.Error())
		os.Exit(1)
	}

	// Up to here was the initialization, now about running

	if cfgfile.IsTestConfig() {
		// all good, exit with 0
		os.Exit(0)
	}
	service.BeforeRun()

	// run the Beat code in background
	go func() {
		err := topbeat.Run()
		if err != nil {
			logp.Critical("Sniffer main loop failed: %v", err)
			os.Exit(1)
		}
		over <- true
	}()

	service.HandleSignals(topbeat.Stop)

	// Startup successful, disable stderr logging if requested by
	// cmdline flag
	logp.SetStderr()

	logp.Debug("main", "Starting topbeat")

	// Wait for the goroutines to finish
	for _ = range over {
		if !topbeat.IsAlive() {
			break
		}
	}

	logp.Debug("main", "Cleanup")
	service.Cleanup()
}
예제 #29
0
func main() {

	// Use our own FlagSet, because some libraries pollute the global one
	var cmdLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)

	cfgfile.CmdLineFlags(cmdLine, Name)
	logp.CmdLineFlags(cmdLine)
	service.CmdLineFlags(cmdLine)
	publisher.CmdLineFlags(cmdLine)

	file := cmdLine.String("I", "", "file")
	loop := cmdLine.Int("l", 1, "Loop file. 0 - loop forever")
	oneAtAtime := cmdLine.Bool("O", false, "Read packets one at a time (press Enter)")
	topSpeed := cmdLine.Bool("t", false, "Read packets as fast as possible, without sleeping")
	printVersion := cmdLine.Bool("version", false, "Print version and exit")
	dumpfile := cmdLine.String("dump", "", "Write all captured packets to this libpcap file.")

	cmdLine.Parse(os.Args[1:])

	sniff := new(sniffer.SnifferSetup)

	if *printVersion {
		fmt.Printf("Packetbeat version %s (%s)\n", Version, runtime.GOARCH)
		return
	}

	err := cfgfile.Read(&config.ConfigSingleton)

	logp.Init(Name, &config.ConfigSingleton.Logging)

	// CLI flags over-riding config
	if *topSpeed {
		config.ConfigSingleton.Interfaces.TopSpeed = true
	}
	if len(*file) > 0 {
		config.ConfigSingleton.Interfaces.File = *file
	}
	config.ConfigSingleton.Interfaces.Loop = *loop
	config.ConfigSingleton.Interfaces.OneAtATime = *oneAtAtime
	if len(*dumpfile) > 0 {
		config.ConfigSingleton.Interfaces.Dumpfile = *dumpfile
	}

	logp.Debug("main", "Initializing output plugins")
	if err = publisher.Publisher.Init(config.ConfigSingleton.Output, config.ConfigSingleton.Shipper); err != nil {

		logp.Critical(err.Error())
		os.Exit(1)
	}

	if err = procs.ProcWatcher.Init(config.ConfigSingleton.Procs); err != nil {
		logp.Critical(err.Error())
		os.Exit(1)
	}

	logp.Debug("main", "Initializing protocol plugins")
	for proto, plugin := range EnabledProtocolPlugins {
		err = plugin.Init(false, publisher.Publisher.Queue)
		if err != nil {
			logp.Critical("Initializing plugin %s failed: %v", proto, err)
			os.Exit(1)
		}
		protos.Protos.Register(proto, plugin)
	}

	tcpProc, err := tcp.NewTcp(&protos.Protos)
	if err != nil {
		logp.Critical(err.Error())
		os.Exit(1)
	}
	udpProc, err := udp.NewUdp(&protos.Protos)
	if err != nil {
		logp.Critical(err.Error())
		os.Exit(1)
	}

	over := make(chan bool)

	stopCb := func() {
		sniff.Stop()
	}

	logp.Debug("main", "Initializing filters")
	afterInputsQueue, err := filters.FiltersRun(
		config.ConfigSingleton.Filter,
		EnabledFilterPlugins,
		publisher.Publisher.Queue,
		stopCb)
	if err != nil {
		logp.Critical("%v", err)
		os.Exit(1)
	}

	logp.Debug("main", "Initializing sniffer")
	err = sniff.Init(false, afterInputsQueue, tcpProc, udpProc)
	if err != nil {
		logp.Critical("Initializing sniffer failed: %v", err)
		os.Exit(1)
	}

	// This needs to be after the sniffer Init but before the sniffer Run.
	if err = droppriv.DropPrivileges(config.ConfigSingleton.RunOptions); err != nil {
		logp.Critical(err.Error())
		os.Exit(1)
	}

	// Up to here was the initialization, now about running

	if cfgfile.IsTestConfig() {
		// all good, exit with 0
		os.Exit(0)
	}
	service.BeforeRun()

	// run the sniffer in background
	go func() {
		err := sniff.Run()
		if err != nil {
			logp.Critical("Sniffer main loop failed: %v", err)
			os.Exit(1)
		}
		over <- true
	}()

	service.HandleSignals(stopCb)

	// Startup successful, disable stderr logging if requested by
	// cmdline flag
	logp.SetStderr()

	logp.Debug("main", "Waiting for the sniffer to finish")

	// Wait for the goroutines to finish
	for _ = range over {
		if !sniff.IsAlive() {
			break
		}
	}

	logp.Debug("main", "Cleanup")

	if service.WithMemProfile() {
		// wait for all TCP streams to expire
		time.Sleep(tcp.TCP_STREAM_EXPIRY * 1.2)
		tcpProc.PrintTcpMap()
	}
	service.Cleanup()
}
예제 #30
0
func loadFile(fileName string) *Settings {
	var settings Settings
	cfgfile.Read(&settings, fileName)
	return &settings
}