summaryrefslogtreecommitdiff
path: root/spooler.go
blob: 8febf31509b76836b25198c8ff5889774e477517 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/go-yaml/yaml"
	"io/ioutil"
	"log"
	//	"time"
)

// parse a request file and return a SCORSHmessage
func parse_request(fname string, msg *SCORSHmsg) error {

	debug.log("[parse_request] message at start: %s\n", msg)

	data, err := ioutil.ReadFile(fname)
	if err != nil {
		log.Printf("Unable to open file: %s\n", fname)
		return SCORSHerr(SCORSH_ERR_NO_FILE)
	}

	debug.log("[parse_request] file contains: \n%s\n", data)

	debug.log("[parse_request] reading message from file: %s\n", fname)

	err = yaml.Unmarshal([]byte(data), msg)
	if err != nil {
		return fmt.Errorf("Error parsing message: %s", err)
	}
	debug.log("[parse_request] got message: %s\n", msg)
	return nil
}

func spooler(watcher *fsnotify.Watcher, worker chan SCORSHmsg) {

	log.Println("Spooler started correctly")

	var msg *SCORSHmsg
	msg = new(SCORSHmsg)

	for {
		select {
		case event := <-watcher.Events:
			if event.Op == fsnotify.Write {
				//time.Sleep(1000 * time.Millisecond)
				debug.log("[spooler] new file %s detected\n", event.Name)
				err := parse_request(event.Name, msg)
				if err != nil {
					log.Printf("Invalid packet received. [%s]\n", err)
				}
				debug.log("[spooler] read message: %s\n", msg)
				worker <- *msg
			}
		case err := <-watcher.Errors:
			log.Println("error:", err)
		}
	}
}

func StartSpooler(master *SCORSHmaster) error {

	watcher, err := fsnotify.NewWatcher()

	if err != nil {
		return fmt.Errorf("Error creating watcher: %s\n", err)
	}

	err = watcher.Add(master.Spooldir)
	if err != nil {
		return fmt.Errorf("Error adding folder: %s\n", err)
	}

	go spooler(watcher, master.Spooler)

	return nil
}