github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/containers/compilers/rump/go/stub/bootstrap_udp.go (about)

     1  // +build udp
     2  
     3  package main
     4  
     5  import (
     6  	"bytes"
     7  	"encoding/json"
     8  	"errors"
     9  	"io/ioutil"
    10  	"log"
    11  	"net"
    12  	"net/http"
    13  	"strings"
    14  )
    15  
    16  func bootstrap() error {
    17  	log.Printf("bootstrapping using instance listener on port %v", BROADCAST_LISTENING_PORT)
    18  	listenerIp, err := getListenerIp()
    19  	if err != nil {
    20  		return errors.New("getting listener ip: " + err.Error())
    21  	}
    22  	env, err := registerWithListener(listenerIp)
    23  	if err != nil {
    24  		return errors.New("registering with listener: " + err.Error())
    25  	}
    26  	if err := setEnv(env); err != nil {
    27  		return errors.New("setting env: " + err.Error())
    28  	}
    29  	return nil
    30  }
    31  
    32  func getListenerIp() (string, error) {
    33  	log.Printf("listening for udp heartbeat...")
    34  	socket, err := net.ListenUDP("udp4", &net.UDPAddr{
    35  		IP:   net.IPv4(0, 0, 0, 0),
    36  		Port: 9967,
    37  	})
    38  	if err != nil {
    39  		return "", err
    40  	}
    41  	for {
    42  		log.Printf("UDP Server listening on %s:%v", "0.0.0.0", 9967)
    43  		data := make([]byte, 4096)
    44  		_, remoteAddr, err := socket.ReadFromUDP(data)
    45  		if err != nil {
    46  			return "", err
    47  		}
    48  		log.Printf("received an ip from %s with data: %s", remoteAddr.IP.String(), string(data))
    49  		if strings.Contains(string(data), "unik") {
    50  			data = bytes.Trim(data, "\x00")
    51  			return strings.Split(string(data), ":")[1], nil
    52  		}
    53  	}
    54  }
    55  
    56  func registerWithListener(listenerIp string) (map[string]string, error) {
    57  	//get MAC Addr
    58  	ifaces, err := net.Interfaces()
    59  	if err != nil {
    60  		return nil, errors.New("retrieving network interfaces" + err.Error())
    61  	}
    62  	macAddress := ""
    63  	for _, iface := range ifaces {
    64  		log.Printf("found an interface: %v\n", iface)
    65  		if len(iface.HardwareAddr) > 0 {
    66  			macAddress = iface.HardwareAddr.String()
    67  			break
    68  		}
    69  	}
    70  	if macAddress == "" {
    71  		return nil, errors.New("could not find mac address")
    72  	}
    73  
    74  	resp, err := http.Post("http://"+listenerIp+":3000/register?mac_address="+macAddress, "", bytes.NewBuffer([]byte{}))
    75  	if err != nil {
    76  		return nil, err
    77  	}
    78  	data, err := ioutil.ReadAll(resp.Body)
    79  	if err != nil {
    80  		return nil, err
    81  	}
    82  	var env map[string]string
    83  	if err := json.Unmarshal(data, &env); err != nil {
    84  		return nil, err
    85  	}
    86  	return env, nil
    87  }