Exemple #1
0
func initConfig() {
	// defaults
	viper.SetDefault("adminroot", "/admin/") // front end location of admin
	viper.SetDefault("admindir", "./admin")  // location of admin assets (relative to site directory)
	viper.SetDefault("contentdir", "content")

	// config name and location
	viper.SetConfigName("config")

	viper.AddConfigPath("/etc/topiary")
	viper.AddConfigPath(".")

	// read config
	err := viper.ReadInConfig()

	if err != nil {
		fmt.Println("No topiary config found. Using defaults.")
	}

	// watch config ; TODO : config to turn this on/off
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
	})
}
Exemple #2
0
func watchConfig() {
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		utils.CheckErr(buildSite(true))
		if !viper.GetBool("DisableLiveReload") {
			// Will block forever trying to write to a channel that nobody is reading if livereload isn't initialized
			livereload.ForceRefresh()
		}
	})
}
Exemple #3
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".nessusControl") // name of config file (without extension)
	viper.AddConfigPath("$HOME")          // adding home directory as first search path
	viper.AutomaticEnv()                  // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		viper.WatchConfig()
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}
Exemple #4
0
func (c *Conf) SetupNotificationConfig(filename string, config NotificationServiceConfig) {
	viperConfig := viper.New()

	c.setupHome(viperConfig, viper.GetString("Home"))
	viperConfig.SetConfigName(filename)

	if err := viperConfig.ReadInConfig(); err != nil {
		log.Printf("Cannot read notification config: %s", err)
	}
	viperConfig.Unmarshal(config)

	viper.OnConfigChange(func(in fsnotify.Event) { viperConfig.ReadInConfig(); viperConfig.Unmarshal(config) })
	viper.WatchConfig()

	c.notificationConfigs = append(c.notificationConfigs, config)
}
Exemple #5
0
func realMain(c *cli.Context) {
	// Create the underlying connection
	bot := ircx.Classic(c.String("server"), c.String("name"))
	bot.Config.MaxRetries = 10
	if usr := c.String("user"); usr != "" {
		bot.Config.User = usr
	}
	bot.Config.Password = c.String("pass")

	channels := strings.Split(c.String("channels"), ",")

	// Create a new bogon
	bogon, err := bogon.New(bot, c.String("name"), channels)
	if err != nil {
		log.Fatalf("Unable to start new bogon: %s", err)
	}

	// Setup & add config
	viper.AutomaticEnv()

	// Add config file if provided
	if cfg := c.String("config"); cfg != "" {
		viper.SetConfigFile(cfg)
		viper.WatchConfig()
		if err := viper.ReadInConfig(); err != nil {
			log.Fatalf("Unable to read config: %s", err)
		}
	}

	// Add viper provider
	config.RegisterProvider(viperprovider.V{})

	// Set up commands
	if err := commandSetup(bogon, c); err != nil {
		log.Fatalf("error setting up commands: %s", err)
	}

	if cfg := c.String("admin"); cfg != "" {
		bogon.AdminSocket(cfg)
	}

	// Connect!
	if err := bogon.Connect(); err != nil {
		log.Fatalf("Unable to connect: %s", err)
	}
	bogon.Start()
}
Exemple #6
0
Fichier : root.go Projet : bep/alfn
func startup() error {

	var config lib.Config

	if err := viper.Unmarshal(&config); err != nil {
		return err
	}

	serverAndPort := fmt.Sprintf("%s:%d", serverInterface, serverPort)

	if config.Feed.Link == "" {
		config.Feed.Link = "http://" + serverAndPort
	}

	if config.Feed.MaxItems <= 0 {
		config.Feed.MaxItems = 10
	}

	// enable live reloading of config
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config", e.Name, "changed ...")
		if err := viper.Unmarshal(&config); err != nil {
			fmt.Println("error: Failed to reload config: ", err)
			return
		}
		shutdownIfNeededAndStart(config)
	})

	viper.WatchConfig()

	shutdownIfNeededAndStart(config)

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "application/rss+xml; charset=utf-8")
		fmt.Fprintf(w, app().GetFeed())
	})

	fmt.Printf("\nStarting server on http://%s ...\n\n", serverAndPort)

	graceful.Run(serverAndPort, 10*time.Second, mux)

	app().Shutdown()

	fmt.Println("\nStopped ...")
	return nil
}
func initByConfigFile() {
	log.Println("init params by configfile..")
	viper.SetConfigName("gate-conf")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".") // optionally look for config in the working directory
	viper.AddConfigPath("$HOME/.seckilling/")
	viper.AddConfigPath("/etc/seckilling/")

	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		log.Panicf("Fatal error config file: %s \n", err)
	}

	if viper.GetBool("watch") {
		viper.WatchConfig()
	}
	viper.OnConfigChange(func(e fsnotify.Event) {
		log.Println("Config file changed:", e.Name)
	})

	log.Printf("loading config %s \n", viper.ConfigFileUsed())
}
Exemple #8
0
func initConfig() {
	// defaults
	viper.SetDefault("AdminLocation", "/admin/") // TODO : some helper to convert strings to paths ? ie: path("admin") -> "/admin/"
	viper.SetDefault("contentdir", "content")

	// config name and location
	viper.SetConfigName("config")

	viper.AddConfigPath("/etc/topiary")
	viper.AddConfigPath(".")

	// read config
	err := viper.ReadInConfig()

	if err != nil {
		fmt.Println("No topiary config found. Using defaults.")
	}

	// watch config ; TODO : config to turn this on/off
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
	})
}
Exemple #9
0
func main() {
	app := cli.NewApp()
	app.Name = "MumbleDJ"
	app.Usage = "A Mumble bot that plays audio from various media sites."
	app.Version = DJ.Version
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "config, c",
			Value: os.ExpandEnv("$HOME/.config/mumbledj/config.yaml"),
			Usage: "location of MumbleDJ configuration file",
		},
		cli.StringFlag{
			Name:  "server, s",
			Value: "127.0.0.1",
			Usage: "address of Mumble server to connect to",
		},
		cli.StringFlag{
			Name:  "port, o",
			Value: "64738",
			Usage: "port of Mumble server to connect to",
		},
		cli.StringFlag{
			Name:  "username, u",
			Value: "MumbleDJ",
			Usage: "username for the bot",
		},
		cli.StringFlag{
			Name:  "password, p",
			Value: "",
			Usage: "password for the Mumble server",
		},
		cli.StringFlag{
			Name:  "channel, n",
			Value: "",
			Usage: "channel the bot enters after connecting to the Mumble server",
		},
		cli.StringFlag{
			Name:  "cert, e",
			Value: "",
			Usage: "path to PEM certificate",
		},
		cli.StringFlag{
			Name:  "key, k",
			Value: "",
			Usage: "path to PEM key",
		},
		cli.StringFlag{
			Name:  "accesstokens, a",
			Value: "",
			Usage: "list of access tokens separated by spaces",
		},
		cli.BoolFlag{
			Name:  "insecure, i",
			Usage: "if present, the bot will not check Mumble certs for consistency",
		},
		cli.BoolFlag{
			Name:  "debug, d",
			Usage: "if present, all debug messages will be shown",
		},
	}

	hiddenFlags := make([]cli.Flag, len(viper.AllKeys()))
	for i, configValue := range viper.AllKeys() {
		hiddenFlags[i] = cli.StringFlag{
			Name:   configValue,
			Hidden: true,
		}
	}
	app.Flags = append(app.Flags, hiddenFlags...)

	app.Action = func(c *cli.Context) error {
		if c.Bool("debug") {
			logrus.SetLevel(logrus.InfoLevel)
		}

		for _, configValue := range viper.AllKeys() {
			if c.GlobalIsSet(configValue) {
				if strings.Contains(c.String(configValue), ",") {
					viper.Set(configValue, strings.Split(c.String(configValue), ","))
				} else {
					viper.Set(configValue, c.String(configValue))
				}
			}
		}

		viper.SetConfigFile(c.String("config"))
		if err := viper.ReadInConfig(); err != nil {
			logrus.WithFields(logrus.Fields{
				"file":  c.String("config"),
				"error": err.Error(),
			}).Warnln("An error occurred while reading the configuration file. Using default configuration...")
			if _, err := os.Stat(c.String("config")); os.IsNotExist(err) {
				createConfigWhenNotExists()
			}
		} else {
			if duplicateErr := bot.CheckForDuplicateAliases(); duplicateErr != nil {
				logrus.WithFields(logrus.Fields{
					"issue": duplicateErr.Error(),
				}).Fatalln("An issue was discoverd in your configuration.")
			}
			createNewConfigIfNeeded()
			viper.WatchConfig()
		}

		if c.GlobalIsSet("server") {
			viper.Set("connection.address", c.String("server"))
		}
		if c.GlobalIsSet("port") {
			viper.Set("connection.port", c.String("port"))
		}
		if c.GlobalIsSet("username") {
			viper.Set("connection.username", c.String("username"))
		}
		if c.GlobalIsSet("password") {
			viper.Set("connection.password", c.String("password"))
		}
		if c.GlobalIsSet("channel") {
			viper.Set("defaults.channel", c.String("channel"))
		}
		if c.GlobalIsSet("cert") {
			viper.Set("connection.cert", c.String("cert"))
		}
		if c.GlobalIsSet("key") {
			viper.Set("connection.key", c.String("key"))
		}
		if c.GlobalIsSet("accesstokens") {
			viper.Set("connection.access_tokens", c.String("accesstokens"))
		}
		if c.GlobalIsSet("insecure") {
			viper.Set("connection.insecure", c.Bool("insecure"))
		}

		if err := DJ.Connect(); err != nil {
			logrus.WithFields(logrus.Fields{
				"error": err.Error(),
			}).Fatalln("An error occurred while connecting to the server.")
		}

		if viper.GetString("defaults.channel") != "" {
			defaultChannel := strings.Split(viper.GetString("defaults.channel"), "/")
			DJ.Client.Do(func() {
				DJ.Client.Self.Move(DJ.Client.Channels.Find(defaultChannel...))
			})
		}

		DJ.Client.Do(func() {
			DJ.Client.Self.SetComment(viper.GetString("defaults.comment"))
		})
		<-DJ.KeepAlive

		return nil
	}

	app.Run(os.Args)
}
Exemple #10
0
func (c *Conf) EnableAutoUpdate() {
	viper.OnConfigChange(func(in fsnotify.Event) { c.Update() })
	viper.WatchConfig()
}
Exemple #11
0
func Run() {

	viper.SetConfigName("config")
	viper.AddConfigPath("/root/work/src/vishnu")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.WatchConfig()
	Dictionnary := viper.Get("Dictionnary")
	dlign, err := ioutil.ReadFile(Dictionnary.(string))
	check(err)
	fmt.Print(string(dlign))
	rp1, err := regexp.Compile(".+:")
	users := rp1.FindAllString(string(dlign), -1) // type id []string
	fmt.Println(users)
	rp2, err := regexp.Compile(":.+")
	passwords := rp2.FindAllString(string(dlign), -1) // type id []string
	fmt.Println(passwords)
	// TODO : Must try/except for every usercleaned/passworcleaned my ssh connection
	for j := 0; j <= len(users)-1; j++ {
		usercleaned := strings.TrimSuffix(users[j], ":")
		passwordcleaned := strings.TrimPrefix(passwords[j], ":")
		fmt.Println(usercleaned)
		fmt.Println(passwordcleaned)
	}
	sshConfig := &ssh.ClientConfig{
		User: usercleaned,
		Auth: []ssh.AuthMethod{
			ssh.Password(passwordcleaned),
		},
	}
	//TODO : Must fix this fixed ip
	client := &SSHClient{
		Config: sshConfig,
		Host:   "127.0.0.1",
		Port:   22,
	}

	cmdlsroot := &SSHCommand{
		Path:   "ls -l $LC_DIR",
		Env:    []string{"LC_DIR=/"},
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	cmdlsb := &SSHCommand{
		Path:   "lsb_release -a",
		Env:    []string{"LC_DIR=/"},
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}

	cmduname := &SSHCommand{
		Path:   "uname -r",
		Env:    []string{"LC_DIR=/"},
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	cmdps := &SSHCommand{
		Path:   "ps faux",
		Env:    []string{"LC_DIR=/"},
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}

	fmt.Printf("Running command: %s\n", cmdlsb.Path)
	if err := client.RunCommand(cmdlsb); err != nil {
		fmt.Fprintf(os.Stderr, "command run error: %s\n", err)
		os.Exit(1)
	}
	fmt.Printf("Running command: %s\n", cmdlsroot.Path)
	if err := client.RunCommand(cmdlsroot); err != nil {
		fmt.Fprintf(os.Stderr, "command run error: %s\n", err)
		os.Exit(1)
	}
	fmt.Printf("Running command: %s\n", cmduname.Path)
	if err := client.RunCommand(cmduname); err != nil {
		fmt.Fprintf(os.Stderr, "command run error: %s\n", err)
		os.Exit(1)
	}
	fmt.Printf("Running command: %s\n", cmdps.Path)
	if err := client.RunCommand(cmdps); err != nil {
		fmt.Fprintf(os.Stderr, "command run error: %s\n", err)
		os.Exit(1)
	}

}
Exemple #12
-1
func init() {
	viper.SetConfigName("conf")
	viper.AddConfigPath(".")
	viper.WatchConfig()
	viper.ReadInConfig()
	viper.Unmarshal(&conf)
	viper.OnConfigChange(func(e fsnotify.Event) {
		if err := viper.Unmarshal(&conf); err != nil {
			log.Println(err.Error())
		} else {
			log.Println("config auto reload!")
		}
	})

	r = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: conf.RedisPass,
	})

	scheduler.Every().Day().At("00:00").Run(func() {
		if time.Now().Day() == 1 {
			length := r.ZCard("Shan8Bot:K").Val()
			if length < 25 {
				return
			}
			i := rand.Int63n(length-25) + 25
			for _, v := range r.ZRangeWithScores("Shan8Bot:K", i, i).Val() {
				log.Println("add 100K for ", v.Member)
				r.ZIncrBy("Shan8Bot:K", 100, v.Member.(string))
			}
		}
	})
}