passage à gandi dns

This commit is contained in:
Laurent Le Houerou 2019-05-02 22:15:52 +04:00
parent a31a89c128
commit fb3a18b017

137
main.go
View File

@ -1,33 +1,35 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/robfig/cron"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing/object"
githttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"io/ioutil"
"net/http"
"net/smtp"
"os"
"os/signal"
"path"
"regexp"
"strconv"
"strings"
"syscall"
"time"
)
type Configuration struct {
RepositoryUrl string `json:"url"`
Username string `json:"name"`
Email string `json:"email"`
GitLogin string `json:"login"`
GitPassword string `json:"password"`
Username string `json:"name"`
Email string `json:"email"`
GandiKey string `json:"gandikey"`
Domains []string `json:"domains"`
}
type DnsResponse struct {
RecordType string `json:"rrset_type"`
Ttl int `json:"rrset_ttl"`
Name string `json:"rrset_name"`
Values []string `json:"rrset_values"`
}
var (
@ -42,9 +44,9 @@ var date = "unknown"
func main() {
app := cli.NewApp()
app.Name = "watchtower"
app.Name = "dnsupdater"
app.Version = version + " - " + commit + " - " + date
app.Usage = "Automatically update running Docker containers"
app.Usage = "Automatically update dns"
app.Before = before
app.Action = start
app.Flags = []cli.Flag{
@ -142,7 +144,7 @@ func update(c *cli.Context) error {
configPath = c.String("config")
if confPathExists, _ := exists(configPath); !confPathExists {
configPath = "./data";
configPath = "./data"
}
file, _ := os.Open(path.Join(configPath, "conf.json"))
@ -151,26 +153,7 @@ func update(c *cli.Context) error {
configuration := Configuration{}
err := decoder.Decode(&configuration)
Info("Repository : %s", configuration.RepositoryUrl)
Info("Name : %s", configuration.Username)
Info("Email : %s", configuration.Email)
Info("GitLogin : %s", configuration.GitLogin)
err = os.RemoveAll(path.Join(configPath, "data"))
if err != nil {
return err
}
_, err = git.PlainClone(path.Join(configPath, "data"), false, &git.CloneOptions{
URL: configuration.RepositoryUrl,
Progress: os.Stdout,
})
if err != nil {
return err
}
currentIp, err := GetCurrentIp()
currentIp, err := GetCurrentIp(configuration)
if err != nil {
return err
}
@ -185,46 +168,9 @@ func update(c *cli.Context) error {
}
Info("Ip has changed %s -> %s", currentIp, newIp)
SetCurrentIp(currentIp, newIp)
repo, err := git.PlainOpen(path.Join(configPath, "data"))
if err != nil {
return err
}
w, err := repo.Worktree()
if err != nil {
return err
}
_, err = w.Add("templates/home_a.lua")
if err != nil {
return err
}
status, err := w.Status()
if err != nil {
return err
}
fmt.Println(status)
_, err = w.Commit(fmt.Sprintf("Changement d'IP maison : %s -> %s", currentIp, newIp), &git.CommitOptions{
Author: &object.Signature{
Name: configuration.Username,
Email: configuration.Email,
When: time.Now().Local(),
},
})
if err != nil {
return err
}
err = repo.Push(&git.PushOptions{
Auth: &githttp.BasicAuth{
Username: configuration.GitLogin,
Password: configuration.GitPassword,
},
})
if err != nil {
return err
for _, domain := range configuration.Domains {
SetCurrentIp(newIp, domain, configuration)
}
SendStatusMail(fmt.Sprintf(`Home IP has changed : %s -> %s
@ -255,7 +201,7 @@ From: "Laurent Le Houerou" <laurent@lehouerou.net>
Subject: DnsUpdater Status
%s
`,messageText)
`, messageText)
if err := smtp.SendMail(host+":587", auth, from, []string{to}, []byte(message)); err != nil {
fmt.Println("Error SendMail: ", err)
@ -264,31 +210,54 @@ Subject: DnsUpdater Status
}
}
func GetCurrentIp() (string, error) {
b, err := ioutil.ReadFile(path.Join(configPath, "data/templates/home_a.lua"))
func GetCurrentIp(configuration Configuration) (string, error) {
url := "https://dns.api.gandi.net/api/v5/domains/lehouerou.net/records/@/A"
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("X-Api-Key", configuration.GandiKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
re := regexp.MustCompile("\"(.*?)\"")
match := re.FindStringSubmatch(string(b))
return match[1], nil
decoder := json.NewDecoder(resp.Body)
dnsresponse := DnsResponse{}
err = decoder.Decode(&dnsresponse)
if err != nil {
return "", err
}
return dnsresponse.Values[0], nil
}
func SetCurrentIp(oldip string, newip string) error {
b, err := ioutil.ReadFile(path.Join(configPath, "data/templates/home_a.lua"))
func SetCurrentIp(newip string, domain string, configuration Configuration) error {
url := fmt.Sprintf("https://dns.api.gandi.net/api/v5/domains/%s/records/@/A", domain)
fmt.Println("URL:>", url)
var str = fmt.Sprintf("{\"rrset_ttl\": %d,\"rrset_values\": [\"%s\"]}", 600, newip)
fmt.Println("json:", str)
var jsonStr = []byte(str)
req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonStr))
req.Header.Set("X-Api-Key", configuration.GandiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
s := string(b)
s = strings.Replace(s, oldip, newip, 1)
ioutil.WriteFile(path.Join(configPath, "data/templates/home_a.lua"), []byte(s), 0644)
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
return nil
}
func GetOutboundIP() (string, error) {
url := "https://diagnostic.opendns.com/myip"
url := "https://api.ipify.org"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err