ddns/redis.go

101 lines
1.9 KiB
Go
Raw Normal View History

package main
import (
"crypto/sha1"
"fmt"
"github.com/garyburd/redigo/redis"
"strings"
2014-07-12 23:37:01 +02:00
"time"
)
const HostExpirationSeconds int = 10 * 24 * 60 * 60 // 10 Days
2014-07-16 14:14:16 +02:00
type RedisConnection struct {
*redis.Pool
}
2014-07-16 14:14:16 +02:00
func OpenConnection(server string) *RedisConnection {
return &RedisConnection{newPool(server)}
}
2014-07-16 14:14:16 +02:00
func newPool(server string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
2014-07-16 14:14:16 +02:00
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
func (self *RedisConnection) GetHost(name string) *Host {
2014-07-16 14:14:16 +02:00
conn := self.Get()
defer conn.Close()
host := Host{Hostname: name}
2014-07-12 23:37:01 +02:00
if self.HostExist(name) {
2014-07-16 14:14:16 +02:00
data, err := redis.Values(conn.Do("HGETALL", host.Hostname))
2014-07-12 23:37:01 +02:00
HandleErr(err)
2014-07-12 23:37:01 +02:00
HandleErr(redis.ScanStruct(data, &host))
}
return &host
}
func (self *RedisConnection) SaveHost(host *Host) {
2014-07-16 14:14:16 +02:00
conn := self.Get()
defer conn.Close()
_, err := conn.Do("HMSET", redis.Args{}.Add(host.Hostname).AddFlat(host)...)
HandleErr(err)
2014-07-16 14:14:16 +02:00
_, err = conn.Do("EXPIRE", host.Hostname, HostExpirationSeconds)
HandleErr(err)
}
func (self *RedisConnection) HostExist(name string) bool {
2014-07-16 14:14:16 +02:00
conn := self.Get()
defer conn.Close()
exists, err := redis.Bool(conn.Do("EXISTS", name))
HandleErr(err)
return exists
}
type Host struct {
Hostname string `redis:"-"`
Ip string `redis:"ip"`
Token string `redis:"token"`
}
func (self *Host) GenerateAndSetToken() {
hash := sha1.New()
hash.Write([]byte(fmt.Sprintf("%d", time.Now().UnixNano())))
hash.Write([]byte(self.Hostname))
self.Token = fmt.Sprintf("%x", hash.Sum(nil))
}
// Returns true when this host has a IPv4 Address and false if IPv6
func (self *Host) IsIPv4() bool {
2014-07-12 23:37:01 +02:00
if strings.Contains(self.Ip, ".") {
return true
}
2014-07-12 23:37:01 +02:00
return false
}