...

Source file src/github.com/kvaps/dnsmasq-controller/pkg/util/util.go

Documentation: github.com/kvaps/dnsmasq-controller/pkg/util

     1  package util
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/md5"
     6  	"fmt"
     7  	"io"
     8  	"io/ioutil"
     9  	"os"
    10  	"os/exec"
    11  )
    12  
    13  func WriteConfig(orig, dest string, data []byte) (bool, error) {
    14  	// If file exists check hash
    15  	if _, err := os.Stat(orig); !os.IsNotExist(err) {
    16  		hasher := md5.New()
    17  		f, err := os.Open(orig)
    18  		if err != nil {
    19  			return false, err
    20  		}
    21  		defer f.Close()
    22  		if _, err := io.Copy(hasher, f); err != nil {
    23  			return false, err
    24  		}
    25  		oldHash := hasher.Sum(nil)[:16]
    26  
    27  		hasher = md5.New()
    28  		hasher.Write(data)
    29  		newHash := hasher.Sum(nil)
    30  
    31  		if bytes.Equal(oldHash, newHash) {
    32  			return false, nil
    33  		}
    34  		f.Close()
    35  	}
    36  
    37  	err := ioutil.WriteFile(dest, data, 0644)
    38  	if err != nil {
    39  		return false, err
    40  	}
    41  	return true, nil
    42  }
    43  
    44  func TestConfig(f string) error {
    45  	var stderr bytes.Buffer
    46  	dnsmasqBinary, err := exec.LookPath("dnsmasq")
    47  	if err != nil {
    48  		return err
    49  	}
    50  	cmd := &exec.Cmd{
    51  		Path:   dnsmasqBinary,
    52  		Args:   []string{"dnsmasq", "--test", "--conf-file=" + f},
    53  		Stderr: &stderr,
    54  	}
    55  	err = cmd.Run()
    56  	if err != nil {
    57  		err = fmt.Errorf(string(stderr.Bytes()))
    58  	}
    59  	return err
    60  }
    61  

View as plain text