Пример #1
0
func main() {
	db, err := mgo.Dial(os.Getenv("MONGO_URL"))
	if err != nil {
		log.Error("Failed to connect to MongoDB", "error", err)
		os.Exit(1)
		return
	}
	defer db.Close()

	ops, errs := gtm.Tail(db, &gtm.Options{
		OpLogCollectionName: &OplogCollection,
		Filter: func(op *gtm.Op) bool {
			return op.Namespace == "dg.lists"
		},
	})

	for {
		select {
		case err = <-errs:
			log.Error("Error from oplog tail", "error", err)
		case <-ops:
			log.Info("Change event")
			Reload()
		}
	}
}
Пример #2
0
func main() {

	log.Debug("Starting up...")

	dev, err := i2c.New(0x77, 1)
	if err != nil {
		log.Error("Error: %v", err)
	}
	bme, err := bme280.NewI2CDriver(dev)
	if err != nil {
		log.Error("Error: %v", err)
	}

	for {
		weather, err := bme.Readenv()

		density := atmosphere.AirDensity(atmosphere.TemperatureC(weather.Temp),
			atmosphere.Pressure(weather.Press*100),
			atmosphere.RelativeHumidity(weather.Hum))
		if err != nil {
			log.Error("Error: %v", err)
		} else {
			log.Debug(fmt.Sprintf("Temperature (degC) %2.2f, pressure (mbar) %4.2f, humidity %2.2f, Density %2.3f kg/m3, CorrFact %1.4f",
				weather.Temp, weather.Press, weather.Hum, float64(density), float64(density*0.8)))
		}

		<-time.After(5 * time.Second)
	}
}
Пример #3
0
func uploadPodcast(r *http.Request) (uploadFile UploadFile, err error) {
	file, header, err := r.FormFile("file")
	if err != nil {
		return uploadFile, err
	}
	defer file.Close()

	target := filepath.Join(common.Storage, header.Filename)
	out, err := os.Create(target)
	if err != nil {
		return uploadFile, err
	}
	defer out.Close()

	// write the content from POST to the file
	_, err = io.Copy(out, file)
	if err != nil {
		return uploadFile, err
	}

	filetype, invalid := isLegalFileFormat(target)
	if invalid {
		log.Error("invalid filetype detected", "file", target, "filetype", filetype)
		deleteError := os.Remove(target)
		if deleteError != nil {
			log.Error("could not delete invalid file", "file", target, "filetype", filetype)
		}
	}

	fileInfo, _ := out.Stat()
	uploadFile.Name = header.Filename
	uploadFile.Size = fileInfo.Size()
	return uploadFile, nil
}
Пример #4
0
func main() {

	app := cli.NewApp()
	app.Name = "Cabify Store"
	app.Usage = "Cabify"
	app.Version = "0.0.1"

	app.Flags = []cli.Flag{
		cli.StringFlag{"config, c", "config.yaml", "config file to use", "APP_CONFIG"},
	}

	app.Commands = []cli.Command{
		{
			Name:  "server",
			Usage: "Run Cabify Store http server",
			Action: func(c *cli.Context) {
				cfg, err := getConfig(c)
				if err != nil {
					log.Error(err.Error())
					return
				}

				svc := service.CabifyService{}

				if err = svc.Run(cfg); err != nil {
					log.Error(err.Error())
				}

				log.Info("Cabify Store server started")
			},
		},
	}
	app.Run(os.Args)
}
Пример #5
0
func moveMP3toStorageDirectory(watchdir, storage string) {
	files, err := ioutil.ReadDir(watchdir)
	if err != nil {
		log.Error("scan error", "error", err)
		return
	}

	for _, file := range files {
		if !file.IsDir() {
			if strings.HasSuffix(file.Name(), "mp3") {
				source := filepath.Join(watchdir, file.Name())
				target := filepath.Join(storage, file.Name())

				// first copy file
				log.Info("about to copy file", "source", source, "target", target)
				err := copyFileContents(source, target)
				if err != nil {
					log.Error("copy error", "error", err)
					return
				}

				// then delete original file
				err = os.Remove(source)
				if err != nil {
					log.Error("error deleting source file", "error", err)
				}
			}
			log.Debug("only process mp3 files")
		}
	}
}
Пример #6
0
// Write out the new files
func Write() error {
	var err error
	var result Item

	// Create the temp files
	wl, err := os.Create("/etc/dansguardian/exceptionlist_db")
	if err != nil {
		log.Error("Failed to create temporary whitelist", "error", err)
		return err
	}
	defer wl.Close()

	gl, err := os.Create("/etc/dansguardian/greylist_db")
	if err != nil {
		log.Error("Failed to create temporary greylist", "error", err)
		return err
	}
	defer gl.Close()

	bl, err := os.Create("/etc/dansguardian/blacklist_db")
	if err != nil {
		log.Error("Failed to create temporary blacklist", "error", err)
		return err
	}
	defer bl.Close()

	// Get the list
	session, err := mgo.Dial(os.Getenv("MONGO_URL"))
	if err != nil {
		log.Error("Failed to connect to MongoDB", "error", err)
		return err
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	i := session.DB("dg").C("lists").Find(nil).Iter()
	for i.Next(&result) {
		switch result.List {
		case "whitelist":
			_, err = wl.WriteString(fmt.Sprintf("%s\n", result.Name))
		case "greylist":
			_, err = gl.WriteString(fmt.Sprintf("%s\n", result.Name))
		case "blacklist":
			_, err = bl.WriteString(fmt.Sprintf("%s\n", result.Name))
		}
	}

	return err
}
Пример #7
0
func TestAudioToBracelet(t *testing.T) {
	llog.Info("Start test")
	audio, err := s.GetAudio("./test.amr")
	if err != nil {
		llog.Error("Erorr", "err", err)
		t.FailNow()
	}

	length := len(audio)
	// Divide file in parts
	var parts int
	if length%s.BufferSize == 0 {
		parts = length / s.BufferSize
	} else {
		parts = length/s.BufferSize + 1
	}

	from := Expect{"ARA": Data{"", 1, "666"}, "ASA": Data{"", 1, "666"}, "ARD": Data{"", 1, ""}}
	to := Expect{"RAU": Data{"", 1, ""}, "SAE": Data{"", 1, ""}} // "SAU": Data{"", parts, ""},

	br := Registration(from, to, t)
	br.Lock()
	br.Commands["666"] = audio
	br.Unlock()

	command := fmt.Sprintf("RAU&M%v&%v&%v&%v&%v&%v", br.Clients[0], 666, length, parts, 10, "DF")
	br, from, to = SendInstruction(br, from, to, command, "ARD", false, t)

	if !(from.Done() && to.Done()) {
		t.Fail()
	}
	br.Logger.Info("End of the test")
	server.RemoveBracelet(TestingID)
	llog.Info("End test")
}
Пример #8
0
func SendInstruction(br *s.Bracelet, from, to Expect, command string, header string, check bool, t *testing.T) (*s.Bracelet, Expect, Expect) {
	if command != "" {
		if _, err := br.Write(command); err != nil {
			llog.Error("Err", "error", err)
			t.Fatal("Can't write message to bracelet")
		}
		br.Logger.Info("Execute", "command", command)
		to.Check(command, "to bracelet")
	}
	ch := make(chan struct{}, 200)
	for i := 0; i < 200; i++ {
		ch <- struct{}{}
	}
	go Listen(br, from, to, t, ch)
	for {
		if header == "" {
			time.Sleep(time.Second * 5)
			break
		}
		if from[header].Msg == "" {
			time.Sleep(time.Second * 5)
			continue
		}
		if !from.CheckStatus(header) && check {
			t.Fatal("Wrong code")
		}
		break
	}
	Wait()
	close(ch)
	return br, from, to
}
Пример #9
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)
	}
}
Пример #10
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
}
Пример #11
0
// Reload Dansguardian configurations
func Reload() {
	err := Write()
	if err != nil {
		log.Error("Failed to write new files; not reloading Dansguardian", "error", err)
		return
	}

	// Tell dansguardian to reload
	cmd := exec.Command("/usr/sbin/dansguardian", "-g")
	err = cmd.Run()
	if err != nil {
		log.Error("Failed to reload dansguardian", "error", err)
	}

	return
}
Пример #12
0
func (a *albumJob) startDownloader() {
	defer a.downloadSync.Done()

	for item := range a.downloadQueue {
		buf := a.bufferPool.Get()

		log.Debug("Processing album item",
			"artist", item.Artist,
			"title", item.Title,
			"url", item.ItemURL,
		)

		err := downloadURL(buf, item.DownloadURL)
		if err != nil {
			log.Error("Unable to download item",
				"download_url", item.DownloadURL,
				"error", err,
			)
			return
		}
		a.zipQueue <- zipFile{
			Filename: item.Name(),
			Buffer:   buf,
		}
		log.Info("Processed album item",
			"download_url", item.DownloadURL,
			"filename", item.Name(),
		)
	}
}
Пример #13
0
func (p *Peer) handleTCPRequest(conn net.Conn) {
	defer conn.Close()

	b := make([]byte, 1024)
	reader := bufio.NewReader(conn)
	_, err := reader.Read(b)

	if err != nil {
		log.Error("Read error", log.Ctx{"error": err})
		return
	}

	// decode
	r, err := decode(b, p.config.EncryptionKey)

	if err != nil {
		p.logger.Error("Decode error", log.Ctx{"error": err})
		return
	}

	switch r.(type) {
	case *joinRequest:

		p.store.peerAdd(r.(*joinRequest).Peer)

		joinResponse := &joinResponse{
			Peer:  p.store.toPeer(),
			Peers: p.store.toMap(),
		}

		r, err := encode(joinResponse, p.config.EncryptionKey, p.config.UDPBufferSize)
		if err != nil {
			p.logger.Error("Encode error", log.Ctx{"error": err})
			return
		}

		_, err = conn.Write(r)
		if err != nil {
			p.logger.Error("Write error", log.Ctx{"error": err})
		}

		return
	default:
		log.Error("Unknown type")
	}

}
Пример #14
0
// This function logs a fatal error and kills the process.
func fatalErr(err error, prefix string) {
	if err != nil {
		defer db.Close()
		msg := fmt.Sprintf("%s: %s", prefix, err.Error())
		log.Error(msg)
		panic(msg)
	}
}
Пример #15
0
func loadConfig(c *Config) {
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		log.Error("Fatal error config file.", "error", err)
	} else {
		c.Alert = viper.Get("alert")
	}

}
Пример #16
0
func main() {
	options := cfg.GetOptions()

	log.Info("Server is ready!", "port", options.Port, "token", options.Token)
	log.Info(fmt.Sprintf("Listening for post requests on http://localhost:%s/events", options.Port))
	log.Info(fmt.Sprintf("SSE streaming avaliable on http://localhost:%s/stream", options.Port))

	es := eventsource.New(
		eventsource.DefaultSettings(),
		func(req *http.Request) [][]byte {
			return [][]byte{
				[]byte("X-Accel-Buffering: no"),
				[]byte("Access-Control-Allow-Origin: *"),
				[]byte("Cache-Control: no-cache"),
			}
		},
	)

	defer es.Close()

	r := mux.NewRouter()

	r.Handle("/stream", es)

	r.HandleFunc("/event/{event}/{id}", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			if token, ok := r.Header["X-Token"]; ok {
				if token[0] == options.Token {
					event := mux.Vars(r)["event"]
					id := mux.Vars(r)["id"]

					data, err := ioutil.ReadAll(r.Body)
					if err != nil {
						log.Error("Cannot read body", "err", err)
					}

					es.SendEventMessage(string(data), event, id)
					log.Info("Message has been sent", "id", id, "event", event)

				} else {
					log.Warn("The request has wrong token", "token", token[0])
					http.Error(w, "The request has wrong token", http.StatusUnauthorized)
				}
			} else {
				log.Warn("The request doesn't contain authentication token")
				http.Error(w, "The request doesn't contain authentication token", http.StatusUnauthorized)
			}
		} else {
			log.Warn("Received wrong http request")
			http.Error(w, "POST requests only", http.StatusMethodNotAllowed)
		}
	})

	r.Handle("/", http.FileServer(http.Dir("./public")))
	http.ListenAndServe(fmt.Sprintf(":%s", options.Port), r)
}
Пример #17
0
func init() {
	cfg, err := ini.Load("./config.ini")

	if err != nil {
		log.Error("Cannot read ./config.ini;", "err", err)
	}

	options.Port = cfg.Section("").Key("port").String()
	options.Token = cfg.Section("").Key("token").String()
}
Пример #18
0
func genSessionID() ([]byte, error) {
	sessionID := make([]byte, 16)
	_, err := io.ReadFull(rand.Reader, sessionID)
	if err != nil {
		log.Error("Unable to create session because unable to read random bytes", "error", err)
		return nil, err
	}

	return sessionID, err
}
Пример #19
0
func downloadURL(buf *bytes.Buffer, url string) error {
	log.Debug("Downloading item", "download_url", url)
	response, err := http.Get(url)
	if err != nil {
		log.Error("Unable to request album item", "download_url", url)
		return err
	}
	defer response.Body.Close()
	io.Copy(buf, response.Body)

	return nil
}
Пример #20
0
func loadUsersCSV() error {
	// Open and parse existing users from the uat file
	usersFile, err := os.OpenFile("users.csv", os.O_RDWR|os.O_CREATE, 0664)
	if err != nil {
		log.Error("Failed to open users file", "error", err.Error())
		return err
	}
	defer usersFile.Close()

	csvReader := csv.NewReader(usersFile)
	rawCSV, err := csvReader.ReadAll()
	if err != nil {
		log.Error("Failed to read CSV file", "error", err.Error())
		return err
	}

	for _, row := range rawCSV {
		u := User{row[0], row[1]}
		Users[u.Username] = u
	}

	return nil
}
Пример #21
0
func TestMain(m *testing.M) {
	Log := llog.New()
	h, _ := llog.FileHandler("./test.txt", llog.LogfmtFormat())
	Log.SetHandler(h)
	server = s.NewServer(Log, ":81234")
	n, err := nats.Connect("nats://localhost:4222")
	if err != nil {
		llog.Error("Can't connect to NATS", "error", err)
		return
	}
	nc, _ := nats.NewEncodedConn(n, nats.JSON_ENCODER)
	l, err := net.Listen("tcp", ":8080")
	if err != nil {
		nc.Close()
		llog.Error("Can't listen on provided port", "error", err)
		return
	}
	server.BC = l
	server.NC = nc
	server.Loc, _ = time.LoadLocation(s.BraceletLocation)
	log.Println("Connections established")
	os.Exit(m.Run())
}
Пример #22
0
func (tr *CabifyResource) OrderSum(c *gin.Context) {
	var data api.Order
	var arr []string
	var summ float32

	summ = 0
	log.Info("Started")

	err := c.Bind(&data)
	if err != nil {
		c.JSON(400, api.NewError("problem decoding body"))
		return
	}

	log.Info("Items parcing, data is: " + data.Items)

	arr = strings.Split(data.Items, ",")
	if arr == nil {
		log.Error("Empty order list, please fill it")
	}

	var VOUCHER_cnt = strings.Count(data.Items, api.VOUCHER)
	var TSHIRT_cnt = strings.Count(data.Items, api.TSHIRT)
	var MUG_cnt = strings.Count(data.Items, api.MUG)

	log.Info("The number of " + api.VOUCHER + " occurence = " + strconv.Itoa(int(VOUCHER_cnt)))
	log.Info("The number of " + api.TSHIRT + " occurence = " + strconv.Itoa(int(TSHIRT_cnt)))
	log.Info("The number of " + api.MUG + " occurence = " + strconv.Itoa(int(MUG_cnt)))

	if TSHIRT_cnt >= 3 {
		summ = summ + float32(TSHIRT_cnt*api.CFO_DISCONT_TSHIRT_PRICE)
	} else if (TSHIRT_cnt < 3) && (TSHIRT_cnt > 0) {
		summ = summ + api.TSHIRT_PRICE
	}

	if VOUCHER_cnt > 0 {
		summ = summ + api.VOUCHER_PRICE

		if math.Mod(float64(MUG_cnt), 2) == 0 {
			summ = summ + float32(int(VOUCHER_cnt/2))*api.VOUCHER_PRICE
		}
	}

	summ = summ + float32(MUG_cnt)*api.MUG_PRICE

	c.JSON(200, gin.H{
		"Order Summ": fmt.Sprintf("%.2f", summ),
		"Status":     "Success",
	})
}
Пример #23
0
func (a *albumJob) startZipper() {
	defer a.zipSync.Done()

	zipBuffer := zip.NewWriter(a.zipWriter)
	defer zipBuffer.Close()

	for file := range a.zipQueue {
		filename := file.Filename
		log.Debug("Creating new item in archive",
			"filename", filename,
		)

		f, err := zipBuffer.Create(filename)
		if err != nil {
			log.Error("Unable to create new item in archive",
				"filename", filename,
			)
			return
		}

		log.Debug("Copying buffer into zip file",
			"filename", filename,
		)

		_, err = io.Copy(f, file.Buffer)
		if err != nil {
			log.Error("Unable to copy buffer into zip file",
				"filename", filename,
			)
			return
		}
		a.bufferPool.Put(file.Buffer)
		zipBuffer.Flush()
	}
	log.Debug("Archive completed")
}
Пример #24
0
// FileList returns slice of UploadedFiles
func FileList() []UploadFile {
	items := []UploadFile{}
	log.Debug("opening dir", "dirname", common.Storage)

	list, err := ioutil.ReadDir(common.Storage)
	if err != nil {
		log.Error("storage error", "error", err)
	}

	for _, file := range list {
		newFile := UploadFile{}
		if file.Mode().IsRegular() {
			newFile.Name = file.Name()
			newFile.Size = file.Size()
		}
		items = append(items, newFile)
	}
	return items
}
Пример #25
0
func initSocket() *socketio.Server {
	server, err := socketio.NewServer(nil)
	if err != nil {
		fmt.Println("Failed to start socket server")
		return nil
	}

	server.On("connection", func(so socketio.Socket) {
		fmt.Printf("New socket.io connection: %s", so.Id())
		so.Join(socketRoom)
		so.On("disconnection", func() {
			// no op
		})
	})

	server.On("error", func(so socketio.Socket, err error) {
		log.Error("Error on socket.io server", "error", err.Error())
	})

	return server
}
Пример #26
0
func isLegalFileFormat(target string) (filetype string, invalid bool) {
	file, err := os.Open(target)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// why 512 bytes ? see http://golang.org/pkg/net/http/#DetectContentType
	buff := make([]byte, 512)
	_, err = file.Read(buff)

	if err != nil {
		log.Error("unable to determine filetype", "file", target, "message", err)
		return "unknown", true
	}

	filetype = http.DetectContentType(buff)
	if filetype != "application/octet-stream" {
		return filetype, true
	}
	return filetype, false
}
Пример #27
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
	}
}
Пример #28
0
// Logs a non-fatal error.
func checkErr(err error, prefix string) {
	if err != nil {
		msg := fmt.Sprintf("%s: %s", prefix, err.Error())
		log.Error(msg)
	}
}