view pkg/imports/queue.go @ 977:4a2ca0e20006

Fixed build error. Copied file to the wrong place and said 'go build' to another wrong place. Argh.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 18 Oct 2018 17:30:53 +0200
parents 2818ad6c7d32
children 544a5cfe07cd
line wrap: on
line source

package imports

import (
	"container/list"
	"context"
	"database/sql"
	"log"
	"sync"

	"gemma.intevation.de/gemma/pkg/auth"
)

type Job interface {
	Who() string
	Do(conn *sql.Conn) error
	CleanUp() error
}

var (
	queueCond = sync.NewCond(new(sync.Mutex))
	queue     = list.New()
)

func init() {
	go importLoop()
}

func AddJob(job Job) {
	queueCond.L.Lock()
	defer queueCond.L.Unlock()
	queue.PushBack(job)
	queueCond.Signal()
}

func importLoop() {
	for {
		var job Job
		queueCond.L.Lock()
		for queue.Len() == 0 {
			queueCond.Wait()
		}
		job = queue.Remove(queue.Front()).(Job)
		queueCond.L.Unlock()

		if err := auth.RunAs(job.Who(), context.Background(), job.Do); err != nil {
			log.Printf("import error: %v\n", err)
		}
		if err := job.CleanUp(); err != nil {
			log.Printf("cleanup error: %v\n", err)
		}
	}
}