github.com/ahjdzx/deis@v1.1.1/cache/image/main.go (about)

     1  package main
     2  
     3  import (
     4  	"log"
     5  	"net"
     6  	"os"
     7  	"os/exec"
     8  	"os/signal"
     9  	"syscall"
    10  	"time"
    11  
    12  	"github.com/coreos/go-etcd/etcd"
    13  )
    14  
    15  const (
    16  	timeout   time.Duration = 10 * time.Second
    17  	ttl       time.Duration = timeout * 2
    18  	redisWait time.Duration = 5 * time.Second
    19  )
    20  
    21  func main() {
    22  	host := getopt("HOST", "127.0.0.1")
    23  
    24  	etcdPort := getopt("ETCD_PORT", "4001")
    25  	etcdPath := getopt("ETCD_PATH", "/deis/cache")
    26  
    27  	externalPort := getopt("EXTERNAL_PORT", "6379")
    28  
    29  	client := etcd.NewClient([]string{"http://" + host + ":" + etcdPort})
    30  
    31  	go launchRedis()
    32  
    33  	go publishService(client, host, etcdPath, externalPort, uint64(ttl.Seconds()))
    34  
    35  	// Wait for terminating signal
    36  	exitChan := make(chan os.Signal, 2)
    37  	signal.Notify(exitChan, syscall.SIGTERM, syscall.SIGINT)
    38  	<-exitChan
    39  }
    40  
    41  func launchRedis() {
    42  	cmd := exec.Command("/app/bin/redis-server", "/app/redis.conf")
    43  	cmd.Stdout = os.Stdout
    44  	cmd.Stderr = os.Stderr
    45  
    46  	err := cmd.Start()
    47  
    48  	if err != nil {
    49  		log.Printf("Error starting Redis: %v", err)
    50  		os.Exit(1)
    51  	}
    52  
    53  	// Wait until the redis server is available
    54  	for {
    55  		_, err := net.DialTimeout("tcp", "127.0.0.1:6379", redisWait)
    56  		if err == nil {
    57  			log.Println("deis-cache running...")
    58  			break
    59  		}
    60  	}
    61  
    62  	err = cmd.Wait()
    63  	log.Printf("Redis finished by error: %v", err)
    64  }
    65  
    66  func publishService(client *etcd.Client, host string, etcdPath string,
    67  	externalPort string, ttl uint64) {
    68  
    69  	for {
    70  		setEtcd(client, etcdPath+"/host", host, ttl)
    71  		setEtcd(client, etcdPath+"/port", externalPort, ttl)
    72  		time.Sleep(timeout)
    73  	}
    74  }
    75  
    76  func setEtcd(client *etcd.Client, key, value string, ttl uint64) {
    77  	_, err := client.Set(key, value, ttl)
    78  	if err != nil {
    79  		log.Println(err)
    80  	}
    81  }
    82  
    83  func getopt(name, dfault string) string {
    84  	value := os.Getenv(name)
    85  	if value == "" {
    86  		value = dfault
    87  	}
    88  	return value
    89  }