Пример #1
0
func main() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	path, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}

	err = watcher.Watch(path)
	if err != nil {
		log.Fatal(err)
	}

	build := true
	done := make(chan struct{})

	for {
		select {
		case ev := <-watcher.Event:
			if strings.HasSuffix(ev.Name, ".go") && build && !ev.IsAttrib() {
				build = false
				go gotool(done, os.Args[1:]...)
			}
		case err := <-watcher.Error:
			log.Fatal("error", err)
		case <-done:
			build = true
		}
	}
}
Пример #2
0
func StartWatch(paths []string, recursive bool, excludes []string) (*fsnotify.Watcher, int, error) {
	// TODO: Check and handle a non-recursive watch request
	watched := 0
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		fmt.Println("Error with establishing watcher, fsmonitor.go line 17:", err)
	}

	for _, path := range paths {
		err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
			if info.IsDir() && !(IsSubDir(excludes, path)) {
				func(path string) (err error) {
					err = watcher.Watch(path)
					watched++
					if err != nil {
						fmt.Printf("fsmonitor.go line 25\terror: %v: %v\n", err, path)
						return err
					}
					return nil
					// TODO: try to find out why the number of directories
					//       watched seems to be different between executions
				}(path)
			}
			return err
		})
		if err != nil {
			fmt.Println("Error with walking filepath, fsmonitor.go line 36:", err)
		}
	}
	return watcher, watched, err
}
Пример #3
0
func NewWatcherWithSkipFolders(skipFolders []string) (*Watcher, error) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}
	monitorWatcher := initWatcher(watcher, skipFolders)
	return monitorWatcher, nil
}
Пример #4
0
func NewWatcher() (*Watcher, error) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}
	monitorWatcher := initWatcher(watcher, []string{})
	return monitorWatcher, nil
}
Пример #5
0
func init() {
	var err error

	if watcher, err = fsnotify.NewWatcher(); err != nil {
		log.Fatal(err)
	}

	c = make(chan Update)
	watchlist = make(map[string]watched)

	go listen()
}
Пример #6
0
func createWatcher(dirname string) (*fsnotify.Watcher, error) {
	w, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}

	err = w.Watch(dirname)
	if err != nil {
		return nil, err
	}

	return w, nil
}
Пример #7
0
func NewSession(verbose bool, watch bool) *session {
	s := &session{
		t:        translator.New(),
		verbose:  verbose || watch,
		packages: make(map[string]*packageData),
	}
	if watch {
		var err error
		s.watcher, err = fsnotify.NewWatcher()
		if err != nil {
			panic(err)
		}
	}
	return s
}
Пример #8
0
func main() {

	flag.Parse()
	startup()

	if *render {

		fmt.Println("Rendering Site")
		err := Render_Site()
		if err != nil {
			fmt.Printf("Cant render site:\n%s\n", err)
			return
		}
		return

	}

	if *watch {
		// fs watcher
		watcher, err := fsnotify.NewWatcher()
		if err != nil {
			log.Fatal(err)
		}

		go func() {
			for {
				select {
				case _ = <-watcher.Event:
					log.Println("changes on templatedir, reload")
					startup()

				case err := <-watcher.Error:
					log.Println("error:", err)
				}
			}
		}()

		err = watcher.Watch(config.TemplateDir)
		if err != nil {
			log.Fatal(err)
		}
	}

	http.HandleFunc("/", getRequest)
	colonport := fmt.Sprintf(":%d", config.PortNum)
	log.Fatal(http.ListenAndServe(colonport, nil))
}
Пример #9
0
// TODO: File existence validation, Regex array == File array length validation
func main() {
	var config Configuration
	config.parseConfig()

	var watchers []*fsnotify.Watcher

	done := make(chan bool)

	for index, filename := range config.Files {
		watcher, err := fsnotify.NewWatcher()
		check(err)

		watchers = append(watchers, watcher)

		continueRead := make(chan bool)

		go func() {
			for {
				select {
				case <-watcher.Event:
					//log.Println("event:", ev)
					time.Sleep(15 * time.Second)
					continueRead <- true
				case err := <-watcher.Error:
					log.Println("error:", err)
				}
			}
		}()

		regexes := compileRegex(config.Detect[index])

		go lineReader(config, filename, regexes, continueRead)

		err = watcher.Watch(filename)
		check(err)

		fmt.Println("watching: " + filename)
	}

	<-done

	for _, watcher := range watchers {
		watcher.Close()
	}
}
Пример #10
0
func listenForFiles() {
	watcher, err := fsnotify.NewWatcher()
	checkError(err)

	err = watcher.Watch("files")
	checkError(err)

	for {
		select {
		case ev := <-watcher.Event:
			if ev.IsCreate() {
				localPeer.insert(ev.Name)
			}
		case err := <-watcher.Error:
			checkError(err)
		}
	}
}
Пример #11
0
func NewScanner(snapper *Snapper, share *Share) *Scanner {
	sc := new(Scanner)
	sc.snapper = snapper
	sc.share = share

	// Create fsnotify watcher
	ww, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	sc.watcher = ww

	go watcherLoop(sc)

	// Kick off a scan.
	sc.Start()

	return sc
}
Пример #12
0
func ExampleNewWatcher() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				log.Println("event:", ev)
			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}()

	err = watcher.Watch("/tmp/foo")
	if err != nil {
		log.Fatal(err)
	}
}
Пример #13
0
func SetupWatch(paths []string, excludes []string) (int, *fsnotify.Watcher) {
	var watchedCount int

	paths = CollectPaths(paths)
	excludes = CollectPaths(excludes)

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		fmt.Println("Error establishing watcher: ", err)
	}

	// establish watches
	for _, path := range paths {
		if IndexOf(path, excludes) == -1 {
			err = watcher.Watch(path)
			if err != nil {
				fmt.Println("Error: ", err, "  establishing watch on: ", path)
			}
			watchedCount++
		}
	}
	return watchedCount, watcher
}
Пример #14
0
func NewSession(options *Options) *Session {
	if options.GOROOT == "" {
		options.GOROOT = build.Default.GOROOT
	}
	if options.GOPATH == "" {
		options.GOPATH = build.Default.GOPATH
	}
	options.Verbose = options.Verbose || options.Watch

	s := &Session{
		options:  options,
		Packages: make(map[string]*PackageData),
	}
	s.ImportContext = compiler.NewImportContext(s.ImportPackage)
	if options.Watch {
		var err error
		s.Watcher, err = fsnotify.NewWatcher()
		if err != nil {
			panic(err)
		}
	}
	return s
}
Пример #15
0
func WatchFiles(filesToWatch []string, loadExistingData bool, serverAddress, clientToken string) {
	executionDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}

	b, err := ioutil.ReadFile(executionDir + "datawatch.state")
	var fileIndex map[string]int64

	if err != nil {
		fileIndex = make(map[string]int64)
	} else {
		err := json.Unmarshal(b, &fileIndex)
		if err != nil {
			log.Fatal("State information corrupt. Delete datawatch.state file or repair")
		}
	}

	ticker := time.NewTicker(time.Second * 1)
	go func(fileIndexes *map[string]int64) {
		for {
			select {
			case <-ticker.C:
				log.Println("Writing state")
				b, _ := json.Marshal(fileIndex)
				err = ioutil.WriteFile(executionDir+"datawatch.state", b, 0644)
				if err != nil {
					log.Println("Unable to write state information to disk")
				}
			}
		}

		println("Timer expired")
	}(&fileIndex)

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	for i := 0; i < len(filesToWatch); i++ {
		err := watcher.Watch(filesToWatch[i])
		fileIndex[filesToWatch[i]] = 0
		if err != nil {
			log.Println(err)
		}
	}

	if loadExistingData {
		for i := 0; i < len(filesToWatch); i++ {
			file, err := os.Open(filesToWatch[i])
			if err != nil {
				log.Println(err)
				break
			}

			scanner := bufio.NewScanner(file)
			length := int64(0)

			for scanner.Scan() {
				length += int64(len(scanner.Text()))
				SendLogLine(serverAddress, scanner.Text(), filesToWatch[i], "", clientToken)
			}

			fileIndex[filesToWatch[i]] = length

		}
	}

	log.Println("Watching")

	type KV struct {
		K string
		V int64
	}

	filechangeschan := make(chan *KV)

	go func(fileChangesChannel chan *KV) {
		for {
			select {
			case ev := <-watcher.Event:
				log.Println("event:", ev)

				if ev.IsDelete() {
					fileIndex[ev.Name] = 0 //Reset byte counter

					err := errors.New("")
					for err != nil {
						log.Println("Waiting for file to rotate")
						err = watcher.Watch(ev.Name)
						time.Sleep(1 * time.Second)
					}
				}

				if ev.IsModify() {
					file, err := os.Open(ev.Name)
					if err != nil {
						log.Println(err)
						break
					}

					data, err := ioutil.ReadAll(file)
					farthestNewline := int64(0)

					//Advance cursor
					for i := len(data); int64(i) > 0; i-- {
						if rune(data[i-1]) == '\n' {
							farthestNewline = int64(i - 1)
							break
						}

						if fileIndex[ev.Name] == int64(i-1) {
							farthestNewline = int64(len(data) - 1)
							break
						}
					}

					var newData []byte
					if fileIndex[ev.Name] == farthestNewline {
						newData = []byte{}
					} else {
						newData = data[fileIndex[ev.Name]:farthestNewline]
					}

					log.Println(string(newData))

					fileIndex[ev.Name] = farthestNewline
				}

			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}(filechangeschan)

	for {
		select {
		case <-filechangeschan:

		}
	}

	looper := make(chan int)
	<-looper
}
Пример #16
0
func main() {
	flag.Parse()

	w, err := fsnotify.NewWatcher()
	if err != nil {
		panic(err)
	}

	args := flag.Args()

	tgt := *target
	if tgt == "." && *restart {
		// with -restart if -target isn't specified, use argv[0].
		tgt = args[0]
	}

	var watch_target string

	if _, err := os.Stat(tgt); err != nil {
		// File doesn't exist, look for it in $PATH
		path_tgt, err := exec.LookPath(tgt)
		if err != nil {
			log.Fatal("Can't find target %q", tgt)
		}
		tgt = path_tgt
	}

	if st, err := os.Stat(tgt); err != nil {
		log.Fatal(err)
	} else {
		watch_target = tgt
		if !st.IsDir() {
			watch_target = path.Dir(watch_target)
		}
	}

	log.Println("Monitoring", tgt)
	w.Watch(watch_target)

	if *restart {
		teardown, finished := start(args)
		for e := range w.Event {
			if e.Name != tgt {
				// Skip everything which isn't the file specified by -target
				continue
			}
			// Note: there is no event deduplication since it is assumed
			// that the target is a single file which will receive one event
			close(teardown)
			// Block until the other process terminated
			<-finished
			// TODO: debounce, run on up edge?
			teardown, finished = start(args)
		}
		return
	}

	if len(args) == 0 {
		args = []string{"go", "install"}
	}

	var teardown chan struct{}

	base := filepath.Base
	dir := filepath.Dir

	for e := range w.Event {
		p, _ := filepath.Abs(e.Name)
		if base(dir(p)) == base(p) && false {
			// Special case to avoid changes to built go binary triggering its
			// own rebuild (filename == name of dir enclosing it)
			continue
		}
		if teardown != nil {
			// A closed teardown channel is a signal to not run the target
			// process or if it's running, to kill it.
			close(teardown)
			teardown = nil
		}
		teardown = invoke(args)
	}
}
Пример #17
0
func Init(d *Daemon) (monitors.Monitor, error) {
	pid, err := util.ReadPidInt(d.PidFile)
	if err != nil && !e.Contains(err, "no such file or directory") {
		return nil, e.Forward(err)
	}

	if d.DaemonName == "" {
		return nil, e.New("empty daemon name")
	}
	if d.RestartCmd == "" {
		return nil, e.New("empty restart command")
	}
	if d.RestartArgs == nil {
		return nil, e.New("restart arguments is invalid")
	}
	if d.PidFile == "" {
		return nil, e.New("empty pid file")
	}
	if d.Sleep <= 0 {
		return nil, e.New("sleep is equal or less than zero")
	}
	if d.Tries < 0 {
		return nil, e.New("tries is equal or less than zero")
	}
	if d.Prio < 0 {
		return nil, e.New("prio have to be greater or equal to zero")
	}
	if d.Queue == nil {
		return nil, e.New("invalid queue")
	}
	if d.ExecTimeout <= 0 {
		return nil, e.New("exectution timeout is greater than zero")
	}

	d.MonitorBase = base.New()
	d.pid = pid
	d.killMonitor = make(chan bool)
	d.running = true
	d.status = status.NewStatuses(d.DaemonName, d.Email, definitions.LengthStatusHistory, status.NewStatus, d.SendEvent, nil)

	d.fswatcher, err = fsnotify.NewWatcher()
	if err != nil {
		return nil, e.Forward(err)
	}
	go func() {
	F:
		for {
			select {
			case ev := <-d.fswatcher.Event:
				if ev == nil {
					//watcher closed
					return
				}
				if ev.Name != d.PidFile {
					continue F
				}
				if ev.IsDelete() {
					d.pid = -1
				} else if !(ev.IsCreate() && ev.IsModify()) {
					continue F
				}
				d.changePid()
			case err := <-d.fswatcher.Error:
				if err != nil {
					d.status.Log(status.Verbose, "Pid file %v watcher error: %v", d.PidFile, e.Trace(e.Forward(err)))
				}
			}
		}
	}()

	err = d.fswatcher.Watch(filepath.Dir(d.PidFile))
	if err != nil {
		return nil, e.Push(err, e.New("invalid pid file %v", d.PidFile))
	}

	d.monitor()
	return d, nil
}
Пример #18
0
// WatchFiles tells soy to watch any template files added to this bundle,
// re-compile as necessary, and propagate the updates to your tofu.  It should
// be called once, before adding any files.
func (b *Bundle) WatchFiles(watch bool) *Bundle {
	if watch && b.err == nil && b.watcher == nil {
		b.watcher, b.err = fsnotify.NewWatcher()
	}
	return b
}
Пример #19
0
func StartWatch(dir string, fileIndex *fileindex.SafeFileList) {
	var err error
	watcher, err = fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	fileList := BuildFileIndex(dir)
	fileIndex.Copy(fileList)

	mutex := new(sync.Mutex)
	lock := sync.NewCond(mutex)
	go func() {
		for {
			mutex.Lock()
			lock.Wait()
			fileIndex.UpdateHash()
			log.Println("Updated hash")
			time.Sleep(1 * time.Second)
			mutex.Unlock()
		}
	}()

	go func() {
		defer watcher.Close() //This loop should run as long as the program is running
		for event := range watcher.Event {
			name, err := filepath.Rel(SandwichPath, event.Name)
			fullName := filepath.Join(SandwichPath, name)
			if err != nil {
				log.Fatal(err)
			}
			switch {
			case event.IsCreate():
				info, err := os.Stat(fullName)
				if err == nil && info.IsDir() {
					fileList := BuildFileList("", fullName)
					fileIndex.Concat(fileList)
					log.Println(fullName + " was added to the manifest.")
				} else if err == nil {
					fileItem, err := GetFileItemName(fullName)
					if err == nil { //Otherwise the file was deleted before we could create it
						if utf8.ValidString(fileItem.FileName) {
							fileList.Add(fileItem)
						} else {
							log.Println("Hey bra, you cannot have non-utf8 encoded file names")
						}
					}
				}
			case event.IsDelete():
				fileIndex.Remove(name)
				log.Println(name + " was removed from the manifest.")
			case event.IsModify():
				fileIndex.Remove(name)
				fileItem, err := GetFileItemName(fullName)
				if err == nil { //Otherwise the file was deleted before we could create it
					if utf8.ValidString(fileItem.FileName) {
						fileList.Add(fileItem)
						log.Println(fullName + " was added to the manifest.")
					} else {
						log.Println("Hey bra, you cannot have non-utf8 encoded file names")
					}
				}
			case event.IsRename():
				fileIndex.Remove(name)
				log.Println(name + " was removed from the manifest.")
			}
			lock.Signal()
		}
		log.Println("Watch loop exited")
	}()
}