Exemple #1
0
func main() {
	var err error
	connPoolConfig := pgx.ConnPoolConfig{
		ConnConfig: pgx.ConnConfig{
			Host:     "127.0.0.1",
			User:     "******",
			Password: "******",
			Database: "url_shortener",
			Logger:   log.New("module", "pgx"),
		},
		MaxConnections: 5,
		AfterConnect:   afterConnect,
	}
	pool, err = pgx.NewConnPool(connPoolConfig)
	if err != nil {
		log.Crit("Unable to create connection pool", "error", err)
		os.Exit(1)
	}

	http.HandleFunc("/", urlHandler)

	log.Info("Starting URL shortener on localhost:8080")
	err = http.ListenAndServe("localhost:8080", nil)
	if err != nil {
		log.Crit("Unable to start web server", "error", err)
		os.Exit(1)
	}
}
Exemple #2
0
// GetData retrieves and calculates the metrics to be displayed in the report page.
func getData(data *Info) error {
	currentFolder, err := osext.ExecutableFolder()
	if err != nil {
		log.Error("Could not retrieve current folder. Attempting to use dot(.) instead...", "error", err)
		currentFolder = "."
	}

	dbFilePath := currentFolder + "/values.db"
	db, err := sql.Open("sqlite3", dbFilePath)
	if err != nil {
		log.Crit("Failed to opend database", "error", err, "path", dbFilePath)
		return err
	}
	defer db.Close()

	rows, err := db.Query("SELECT timestamp, ping, download, upload FROM bandwidth")
	if err != nil {
		log.Crit("Could not retrieve data from database", "error", err)
		return err
	}
	defer rows.Close()

	min := 10000.0 // Unfortunately, I don't see myself with a 10000Mbit/s connection anytime soon...
	max := 0.0
	counter := 0
	average := 0.0
	data.Points = [][]interface{}{{map[string]string{"type": "datetime", "label": "Time"}, "Download", "Upload"}}

	for rows.Next() {
		var timestamp string
		var ping, download, upload float64
		rows.Scan(&timestamp, &ping, &download, &upload)

		if download < min {
			min = download
		}

		if download > max {
			max = download
		}

		average += download
		counter++

		// Timestamp is presented as YYYY-MM-DD HH:MI:SS.Milli+0000
		split := strings.Split(timestamp, " ")
		dateOnly := strings.Split(string(split[0]), "-")
		timeOnly := strings.Split(string(split[1]), ".")
		timeOnly = strings.Split(string(timeOnly[0]), ":")
		axis := fmt.Sprintf("Date(%s, %s, %s, %s, %s, %s)", dateOnly[0], dateOnly[1], dateOnly[2], timeOnly[0], timeOnly[1], timeOnly[2])

		data.Points = append(data.Points, []interface{}{axis, download, upload})
	}
	data.MinValue = min
	data.MaxValue = max
	data.AvgValue = average / float64(counter)
	data.LastValue = data.Points[len(data.Points)-1][1].(float64)

	return nil
}
Exemple #3
0
func displayPage(w http.ResponseWriter, r *http.Request, dynamicData interface{}) {
	templateString, err := staticBox.String("index.tmpl")
	if err != nil {
		log.Crit("template", "error", err)
	}

	tmplMessage, err := template.New("messsage").Parse(templateString)
	if err != nil {
		log.Crit("template", "error", err)
	}
	tmplMessage.Execute(w, dynamicData)
}
Exemple #4
0
func buildCmd(c *cli.Context) {
	exit := func(err error) {
		if err == nil {
			os.Exit(0)
		} else {
			log.Crit("command failed", "err", err)
			os.Exit(1)
		}
	}

	opts := &Options{
		Version:    c.String("version"),
		SrcPath:    c.String("src"),
		TargetPath: c.String("target"),
	}

	platforms := c.String("platforms")
	if platforms == "" {
		opts.Platforms = defaultPlatforms
	} else {
		opts.Platforms = make([]Platform, 0)
		for _, pString := range strings.Split(platforms, " ") {
			parts := strings.Split(pString, "_")
			if len(parts) != 2 {
				exit(fmt.Errorf("Invalid platform string: %v", pString))
			}
			opts.Platforms = append(opts.Platforms, Platform{parts[0], parts[1]})
		}
	}

	exit(Build(opts))
}
Exemple #5
0
func main() {
	// read environment vars
	common.ReadEnvironment()

	// initialise mux router
	router := mux.NewRouter()

	// setup statics
	poddy.CreateStaticBox(router)

	// setup watchdirectory
	if common.Watch != "" {
		check, err := os.Stat(common.Watch)
		if err != nil || !check.IsDir() {
			log.Error("error setting up watchdirectory (point to directory?)")
		} else {
			poddy.EnableWatchdirectory(common.Watch)
		}
	}

	// http handles
	router.HandleFunc("/", poddy.IndexPage)
	router.HandleFunc("/add-podcast", poddy.AddPodcast)
	router.HandleFunc("/feed", poddy.Feed)
	router.PathPrefix("/download").Handler(http.StripPrefix("/download", http.FileServer(http.Dir("storage/"))))

	// start server
	log.Info("poddy is running/listening", "host", common.Host, "port", common.Port)
	err := http.ListenAndServe(fmt.Sprintf("%s:%d", common.Host, common.Port), router)
	if err != nil {
		log.Crit("daemon could not bind on interface", "host", common.Host, "port", common.Port)
		os.Exit(1)
	}
}
func main() {
	r, err := nca.NewRunnerFromFile("config.yml")
	if err != nil {
		log.Crit("Startup failed", "error", err)
		os.Exit(1)
	}

	r.Run()
}
Exemple #7
0
func main() {
	app.Version(fmt.Sprintf("NCR version %s (runtime version %s)", version, runtime.Version()))
	kingpin.MustParse(app.Parse(os.Args[1:]))

	r, err := ncr.NewRunnerFromFile(*cfgfile)
	if err != nil {
		log.Crit("Startup failed", "error", err)
		os.Exit(1)
	}

	r.Run()
}
Exemple #8
0
// Speed generates the report page.
func Speed(w http.ResponseWriter, r *http.Request) {
	currentFolder, err := osext.ExecutableFolder()
	if err != nil {
		log.Error("Could not retrieve current folder. Attempting to use dot(.) instead...", "error", err)
		currentFolder = "."
	}

	files := []string{currentFolder + "/html/templates/speed.html"}
	t, err := template.ParseFiles(files...)
	if err != nil {
		log.Crit("Failed to load template", "error", err, "templates", files)
		return
	}

	data := Info{}
	getData(&data)

	err = t.Execute(w, data)
	if err != nil {
		log.Crit("Failed to apply data to template", "error", err, "data", data)
		return
	}
}
Exemple #9
0
func main() {
	rootLog.Info("Started")

	// For each registered protocol, we add the corresponding flags for its
	// destination.
	protocolFlags := make(map[string]*string)
	for name, _ := range protocols {
		protocolFlags[name] = flag.String(name+"-destination", "",
			"destination to forward "+name+" traffic to")
	}

	// Parse all flags.
	flag.Parse()

	// First off, handle flags that cause us to exit instead of actually listening
	checkExitFlags()
	validateFlags()

	// Find out what we've got enabled
	enabledProtocols := []Protocol{}
	protoDestinations := make(map[string]*net.TCPAddr)
	descString := ""
	for name, flag := range protocolFlags {
		if len(*flag) > 0 {
			// Validate that we can parse this address
			addr, err := net.ResolveTCPAddr("tcp", *flag)
			if err != nil {
				log.Crit("Invalid TCP address",
					"addr", *flag,
					"err", err,
				)
				return
			}

			protoDestinations[name] = addr
			enabledProtocols = append(enabledProtocols, protocols[name])
			descString += name + ","
		}
	}

	if len(enabledProtocols) == 0 {
		rootLog.Crit("No protocols were enabled")
		return
	}

	log.Debug("Enabled protocols: " + descString[0:len(descString)-1])

	// Start listening
	addr := fmt.Sprintf("%s:%d", flagListenHost, flagListenPort)
	l, err := net.Listen("tcp", addr)
	if err != nil {
		rootLog.Crit("Could not open listener", "err", err)
		return
	}
	defer l.Close()

	rootLog.Info("Started listening", "addr", addr)
	for {
		conn, err := l.Accept()
		if err != nil {
			rootLog.Error("Error accepting connection", "err", err)
			continue
		}

		p := NewProxy(conn, rootLog)
		p.EnabledProtocols = enabledProtocols
		p.ProtoDestinations = protoDestinations
		go p.Start()
	}
}
Exemple #10
0
// Fatal logs a critical message and exits the process with status code 1.
// This function is meant to be used by initialization code to prevent the application from even
// starting up when something is obviously wrong.
// In particular this function should probably not be used when serving requests.
func Fatal(msg string, ctx ...interface{}) {
	log.Crit(msg, ctx...)
	os.Exit(1)
}