Esempio n. 1
0
func main() {
	var port uint
	var etcdAddr, logLevel string

	flag.UintVarP(&port, "port", "p", 19000, "listen port")
	flag.StringVarP(&etcdAddr, "etcd", "e", defaultEtcdAddr, "address of etcd machine")
	flag.StringVarP(&logLevel, "log-level", "l", "warn", "log level")
	flag.Parse()

	if err := logx.DefaultSetup(logLevel); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"level": logLevel,
		}).Fatal("failed to set up logging")
	}

	etcdClient := etcd.NewClient([]string{etcdAddr})

	if !etcdClient.SyncCluster() {
		log.WithFields(log.Fields{
			"addr": etcdAddr,
		}).Fatal("unable to sync etcd cluster")
	}

	ctx := lochness.NewContext(etcdClient)

	_ = Run(port, ctx)
}
Esempio n. 2
0
// NewFetcher creates a new fetcher
func NewFetcher(etcdAddress string) *Fetcher {
	e := etcd.NewClient([]string{etcdAddress})
	c := lochness.NewContext(e)
	return &Fetcher{
		context:    c,
		etcdClient: e,
	}
}
Esempio n. 3
0
func main() {
	interval := flag.IntP("interval", "i", 60, "update interval in seconds")
	ttl := flag.IntP("ttl", "t", 0, "heartbeat ttl in seconds")
	eaddr := flag.StringP("etcd", "e", "http://localhost:4001", "address of etcd machine")
	id := flag.StringP("id", "d", "", "hypervisor id")
	logLevel := flag.StringP("log-level", "l", "info", "log level")
	flag.Parse()

	if err := logx.DefaultSetup(*logLevel); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "logx.DefaultSetup",
			"level": logLevel,
		}).Fatal("failed to set up logging")
	}

	if *ttl == 0 {
		*ttl = 2 * (*interval)
	}

	e := etcd.NewClient([]string{*eaddr})
	c := lochness.NewContext(e)

	hn, err := lochness.SetHypervisorID(*id)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "lochness.SetHypervisorID",
			"id":    id,
		}).Fatal("failed to set hypervisor id")
	}

	hv, err := c.Hypervisor(hn)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "context.Hypervisor",
			"id":    hn,
		}).Fatal("failed to instantiate hypervisor")
	}

	for {
		if err = hv.UpdateResources(); err != nil {
			log.WithFields(log.Fields{
				"error": err,
				"func":  "hv.UpdateResources",
			}).Fatal("failed to update hypervisor resources")
		}
		if err = hv.Heartbeat(time.Duration(*ttl)); err != nil {
			log.WithFields(log.Fields{
				"error": err,
				"func":  "hv.Heartbeat",
				"ttl":   *ttl,
			}).Fatal("failed to beat heart")
		}
		time.Sleep(time.Duration(*interval) * time.Second)
	}
}
Esempio n. 4
0
func newContext(t *testing.T) *lochness.Context {
	e := etcd.NewClient([]string{"http://127.0.0.1:4001"})
	if !e.SyncCluster() {
		t.Fatal("cannot sync cluster. make sure etcd is running at http://127.0.0.1:4001")
	}

	c := lochness.NewContext(e)

	return c
}
Esempio n. 5
0
func main() {
	var port uint
	var etcdAddr, bstalk, logLevel string

	// Command line flags
	flag.StringVarP(&bstalk, "beanstalk", "b", "127.0.0.1:11300", "address of beanstalkd server")
	flag.StringVarP(&logLevel, "log-level", "l", "warn", "log level")
	flag.StringVarP(&etcdAddr, "etcd", "e", "http://127.0.0.1:4001", "address of etcd server")
	flag.UintVarP(&port, "http", "p", 7544, "http port to publish metrics. set to 0 to disable")
	flag.Parse()

	// Set up logger
	if err := logx.DefaultSetup(logLevel); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"level": logLevel,
		}).Fatal("unable to to set up logrus")
	}

	etcdClient := etcd.NewClient([]string{etcdAddr})

	if !etcdClient.SyncCluster() {
		log.WithFields(log.Fields{
			"addr": etcdAddr,
		}).Fatal("unable to sync etcd cluster")
	}

	ctx := lochness.NewContext(etcdClient)

	log.WithField("address", bstalk).Info("connection to beanstalk")
	jobQueue, err := jobqueue.NewClient(bstalk, etcdClient)
	if err != nil {
		log.WithFields(log.Fields{
			"error":   err,
			"address": bstalk,
		}).Fatal("failed to create jobQueue client")
	}

	// Set up metrics
	m := setupMetrics(port)
	if m != nil {
	}

	agent := ctx.NewMistifyAgent()

	// Start consuming
	consume(jobQueue, agent, m)
}
Esempio n. 6
0
func main() {

	// Command line options
	var logLevel string
	flag.StringVarP(&logLevel, "log-level", "l", "info", "log level: debug/info/warning/error/critical/fatal")
	flag.Parse()

	// Logging
	if err := logx.DefaultSetup(logLevel); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "logx.DefaultSetup",
		}).Fatal("Could not set up logrus")
	}

	// Write logs to this directory
	testDir = "cdhcpd-integration-test-" + uuid.New()
	if err := os.Mkdir(testDir, 0755); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "os.Mkdir",
			"path":  testDir,
		}).Fatal("Could not create directory for test logs")
	}
	hconfPath = testDir + "/hypervisors.conf"
	gconfPath = testDir + "/guests.conf"

	// From now on, write the logs from this script to a file in the test directory as well
	var err error
	selfLog, err = os.Create(testDir + "/integrationtest.log")
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "os.Open",
		}).Fatal("Could not open self-log file for writing")
	}
	defer func() {
		if err := selfLog.Sync(); err != nil {
			fmt.Println("Could not sync self-log file")
		}
		if err := selfLog.Close(); err != nil {
			fmt.Println("Could not close self-log file")
			os.Exit(1)
		}
	}()
	log.SetOutput(selfLog)

	// Set up report and global ok
	r := &bytes.Buffer{}
	_, _ = r.WriteString("cdhcpd Integration Test Results\n")
	_, _ = r.WriteString("==================================\n")
	testOk = true

	// Start up processes
	log.Info("Starting etcd")
	ep := newTestProcess("etcd", exec.Command("etcd", "--data-dir", testDir+"/data.etcd",
		"--listen-client-urls", etcdClientAddress,
		"--listen-peer-urls", etcdPeerAddress,
		"--initial-advertise-peer-urls", etcdPeerAddress,
		"--initial-cluster", "default="+etcdPeerAddress,
		"--advertise-client-urls", etcdClientAddress,
	))
	if err := ep.captureOutput(true); err != nil {
		cleanupAfterError(err, "testProcess.captureOutput", r, nil, ep, nil)
	}
	if err := ep.start(); err != nil {
		cleanupAfterError(err, "testProcess.start", r, nil, ep, nil)
	}
	log.Info("Starting cdhcpd")
	dp := newTestProcess("cdhcpd", exec.Command("cdhcpd", "-e", etcdClientAddress,
		"-d", "example.com",
		"-l", logLevel,
		"-c", testDir,
	))
	if err := dp.captureOutput(true); err != nil {
		if err := ep.finish(); err != nil {
			log.Error("Could not close out etcd")
		}
		cleanupAfterError(err, "testProcess.captureOutput", r, nil, ep, dp)
	}
	if err := dp.start(); err != nil {
		if err := ep.finish(); err != nil {
			log.Error("Could not close out etcd")
		}
		cleanupAfterError(err, "testProcess.start", r, nil, ep, dp)
	}

	// Begin test
	log.Info("Running test")
	time.Sleep(time.Second)
	if ok := reportConfStatus(r, "on start", "not present", "not present"); !ok {
		log.Warning("Failure testing conf status on start")
		testOk = false
	}

	// Set up context
	e := etcd.NewClient([]string{etcdClientAddress})
	c := lochness.NewContext(e)

	// Roughly follow the steps of the demo's guest-setup.sh
	hs := make(map[string]*lochness.Hypervisor)
	gs := make(map[string]*lochness.Guest)

	// Basic setup
	f, err := testhelper.NewFlavor(c, 1, 512, 1024)
	if err != nil {
		cleanupAfterError(err, "testhelper.NewFlavor", r, e, ep, dp)
	}
	n, err := testhelper.NewNetwork(c)
	if err != nil {
		cleanupAfterError(err, "testhelper.NewNetwork", r, e, ep, dp)
	}
	fw, err := testhelper.NewFirewallGroup(c)
	if err != nil {
		cleanupAfterError(err, "testhelper.NewFirewallGroup", r, e, ep, dp)
	}
	time.Sleep(time.Second)
	if ok := reportConfStatus(r, "after setup", "created", "created"); !ok {
		log.Warning("Failure testing conf status after setup")
		testOk = false
	}

	// Add a subnet
	s, err := testhelper.NewSubnet(c, "192.168.100.0/24", net.IPv4(192, 168, 100, 1), net.IPv4(192, 168, 100, 10), net.IPv4(192, 168, 100, 200), n)
	if err != nil {
		cleanupAfterError(err, "testhelper.NewSubnet", r, e, ep, dp)
	}
	time.Sleep(time.Second)
	if ok := reportConfStatus(r, "after subnet creation", "not touched", "not touched"); !ok {
		log.Warning("Failure testing conf status after subnet creation")
		testOk = false
	}

	// Add a hypervisor
	h, err := testhelper.NewHypervisor(c, "fe:dc:ba:98:76:54", net.IPv4(192, 168, 100, 200), net.IPv4(192, 168, 100, 1), net.IPv4(255, 255, 255, 0), "br0", s)
	if err != nil {
		cleanupAfterError(err, "testhelper.NewHypervisor", r, e, ep, dp)
	}
	hs[h.ID] = h
	time.Sleep(time.Second)
	if ok := reportConfStatus(r, "after hypervisor creation", "changed", "not touched"); !ok {
		log.Warning("Failure testing conf status after hypervisor creation")
		testOk = false
	}
	if ok := reportHasHosts(r, "after hypervisor creation", hs, gs); !ok {
		log.Warning("Failure testing for hosts in confs after hypervisor creation")
		testOk = false
	}

	// Create a guest, without setting the subnet or hypervisor (will NOT appear in the conf)
	g, err := testhelper.NewGuest(c, "A4:75:C1:6B:E3:49", n, nil, f, fw, nil)
	if err != nil {
		cleanupAfterError(err, "testhelper.NewGuest", r, e, ep, dp)
	}
	time.Sleep(time.Second)
	if ok := reportConfStatus(r, "after guest creation", "not touched", "not touched"); !ok {
		log.Warning("Failure testing conf status after guest creation")
		testOk = false
	}
	if ok := reportHasHosts(r, "after guest creation", hs, gs); !ok {
		log.Warning("Failure testing for hosts in confs after guest creation")
		testOk = false
	}

	// Add the guest to the hypervisor (would normally be performed by cplacerd, having pulled it from the queue)
	if err := h.AddGuest(g); err != nil {
		cleanupAfterError(err, "hypervisor.AddGuest", r, e, ep, dp)
	}
	gs[g.ID] = g
	time.Sleep(time.Second)
	if ok := reportConfStatus(r, "after adding guest to hypervisor", "not touched", "changed"); !ok {
		log.Warning("Failure testing conf status after adding guest to hypervisor")
		testOk = false
	}
	if ok := reportHasHosts(r, "after adding guest to hypervisor", hs, gs); !ok {
		log.Warning("Failure testing for hosts in confs after adding guest to hypervisor")
		testOk = false
	}

	// Sleep for a few seconds to make sure everything finished, then clean up
	time.Sleep(2 * time.Second)
	log.WithField("path", testDir).Info("Creating test output directory")
	showTestStatus(true)
	cleanup(r, e, ep, dp)
}
Esempio n. 7
0
func main() {
	rand.Seed(time.Now().UTC().UnixNano())
	e := etcd.NewClient([]string{"http://127.0.0.1:4001"})
	c := lochness.NewContext(e)

	f1 := c.NewFlavor()
	f1.CPU = 4
	f1.Memory = 4096
	f1.Disk = 8192
	if err := f1.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    f1.ID,
			"item":  "flavor",
		}).Fatal("failed to save flavor")
	}
	print(f1)

	f2 := c.NewFlavor()
	f2.CPU = 6
	f2.Memory = 8192
	f2.Disk = 1024
	if err := f2.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    f2.ID,
			"item":  "flavor",
		}).Fatal("failed to save flavor")
	}
	print(f2)

	n := c.NewNetwork()
	if err := n.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    n.ID,
			"item":  "network",
		}).Fatal("failed to save network")
	}
	print(n)

	fw := c.NewFWGroup()
	fw.Rules = append(fw.Rules, &lochness.FWRule{})

	if err := fw.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    fw.ID,
			"item":  "fwgroup",
		}).Fatal("failed to save fwgroup")
	}
	print(fw)

	s := c.NewSubnet()
	var err error
	cidr := "10.10.10.0/24"
	_, s.CIDR, err = net.ParseCIDR(cidr)
	if err != nil {
		log.WithFields(log.Fields{
			"func":  "net.ParseCIDR",
			"error": err,
			"id":    s.ID,
			"cidr":  cidr,
		}).Fatal("failed to parse subnet CIDR")
	}
	s.Gateway = net.IPv4(10, 10, 10, 1)
	s.StartRange = net.IPv4(10, 10, 10, 10)
	s.EndRange = net.IPv4(10, 10, 10, 250)
	if err := s.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    s.ID,
			"item":  "subnet",
		}).Fatal("failed to save subnet")
	}
	print(s)

	addresses := s.Addresses()
	print(addresses)

	print(s.AvailibleAddresses())

	if err := n.AddSubnet(s); err != nil {
		log.WithFields(log.Fields{
			"func":  "AddSubnet",
			"error": err,
			"id":    n.ID,
			"item":  "network",
		}).Fatal("failed to add subnet to network")
	}

	networkSubnets := n.Subnets()
	if len(networkSubnets) == 0 {
		log.Fatal("no subnets available on network")
	}
	for _, k := range networkSubnets {
		_, err := c.Subnet(k)
		if err != nil {
			log.Fatal(err)
		}
		print(s)
	}

	print(n)

	var h *lochness.Hypervisor
	if hv := os.Getenv("TEST_HV"); hv != "" {
		var err error
		h, err = c.Hypervisor(hv)
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
				"id":    hv,
				"func":  "context.Hypervsior",
			}).Fatal("failted to instantiate hypervisor")
		}
	} else {
		h = c.NewHypervisor()
		h.IP = net.IPv4(10, 100, 101, 34)
		mac := "01:23:45:67:89:ab"
		h.MAC, err = net.ParseMAC(mac)
		if err != nil {
			log.WithFields(log.Fields{
				"func":  "net.ParseMAC",
				"error": err,
				"id":    h.ID,
				"mac":   mac,
				"item":  "hypervisor",
			}).Fatal("failed to parse hypervisor mac")
		}
		if err := h.Save(); err != nil {
			log.WithFields(log.Fields{
				"func":  "Save",
				"error": err,
				"id":    h.ID,
				"item":  "hypervisor",
			}).Fatal("failed to save hypervisor")
		}
	}
	if err := h.AddSubnet(s, "br0"); err != nil {
		log.WithFields(log.Fields{
			"func":  "AddSubnet",
			"error": err,
			"id":    h.ID,
			"item":  "hypervisor",
		}).Fatal("failed to add subnet")
	}

	print(h)

	subnets := h.Subnets()
	if len(subnets) == 0 {
		log.Fatal("no subnets available on hypervisor")
	}

	for k := range subnets {
		s, err := c.Subnet(k)
		if err != nil {
			log.Fatal(err)
		}
		print(s)
	}

	fw1 := c.NewFWGroup()
	fw2 := c.NewFWGroup()

	fw1.Rules = lochness.FWRules{&lochness.FWRule{
		Group:     fw2.ID,
		PortStart: 80,
		PortEnd:   82,
		Protocol:  "tcp",
	}}
	fw2.Rules = lochness.FWRules{&lochness.FWRule{
		Group:     fw1.ID,
		PortStart: 80,
		PortEnd:   82,
		Protocol:  "tcp",
	}}

	if err := fw1.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    fw1.ID,
			"item":  "fwgroup",
		}).Fatal("failed to save fwgroup")
	}
	if err := fw2.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    fw2.ID,
			"item":  "fwgroup",
		}).Fatal("failed to save fwgroup")
	}

	g1 := c.NewGuest()
	g1.SubnetID = s.ID
	g1.NetworkID = n.ID
	g1.MAC, err = net.ParseMAC("01:23:45:67:89:ab")
	g1.FlavorID = f1.ID
	g1.FWGroupID = fw1.ID
	if err := g1.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    g1.ID,
			"item":  "guest",
		}).Fatal("failed to save guest")
	}
	if err := h.AddGuest(g1); err != nil {
		log.WithFields(log.Fields{
			"func":  "AddGuest",
			"error": err,
			"id":    h.ID,
			"item":  "hypervisor",
			"guest": g1.ID,
		}).Fatal("failed to add guest to hypervisor")
	}
	g1.IP, err = s.ReserveAddress(g1.ID)
	if err != nil {
		log.WithFields(log.Fields{
			"func":  "ReserverAddress",
			"error": err,
			"id":    s.ID,
			"item":  "subnet",
		}).Fatal("failed to reserver address")
	}
	if err := g1.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    g1.ID,
			"item":  "guest",
		}).Fatal("failed to save guest")
	}
	print(g1)

	g2 := c.NewGuest()
	g2.SubnetID = s.ID
	g2.NetworkID = n.ID
	g2.MAC, err = net.ParseMAC("01:23:45:67:89:ac")
	g2.FlavorID = f2.ID
	g2.FWGroupID = fw2.ID
	if err := g2.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    g2.ID,
			"item":  "guest",
		}).Fatal("failed to save guest")
	}
	if err := h.AddGuest(g2); err != nil {
		log.WithFields(log.Fields{
			"func":  "AddGuest",
			"error": err,
			"id":    h.ID,
			"item":  "hypervisor",
			"guest": g2.ID,
		}).Fatal("failed to add guest to hypervisor")
	}
	g2.IP, err = s.ReserveAddress(g2.ID)
	if err != nil {
		log.WithFields(log.Fields{
			"func":  "ReserverAddress",
			"error": err,
			"id":    s.ID,
			"item":  "subnet",
		}).Fatal("failed to reserver address")
	}
	if err := g2.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    g2.ID,
			"item":  "guest",
		}).Fatal("failed to save guest")
	}
	print(g2)
}
Esempio n. 8
0
func main() {
	eaddr := "http://localhost:4001"
	hn := ""
	rules := "/etc/nftables.conf"
	flag.StringVarP(&eaddr, "etcd", "e", eaddr, "etcd cluster address")
	flag.StringVarP(&hn, "id", "i", hn, "hypervisor id")
	flag.StringVarP(&rules, "file", "f", rules, "nft configuration file")
	flag.Parse()

	rules = canonicalizeRules(rules)
	cleanStaleFiles(rules)

	e := etcd.NewClient([]string{eaddr})
	c := ln.NewContext(e)
	hv := getHV(hn, e, c)

	watcher, err := watcher.New(e)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "watcher.New",
		}).Fatal("failed to start watcher")
	}

	if err = watcher.Add("/lochness/guests"); err != nil {
		log.WithFields(log.Fields{
			"error":  err,
			"func":   "watcher.Add",
			"prefix": "/lochness/guests",
		}).Fatal("failed to add prefix to watch list")
	}

	if err := watcher.Add("/lochness/fwgroups"); err != nil {
		log.WithFields(log.Fields{
			"error":  err,
			"func":   "watcher.Add",
			"prefix": "/lochness/fwgroups",
		}).Fatal("failed to add prefix to watch list")
	}

	// load rules at startup
	td, err := genRules(hv, c)
	if err != nil {
		log.WithField("error", err).Fatal("could not load intial rules")
	}
	if err := applyRules(rules, td); err != nil {
		log.WithField("error", err).Fatal("could not apply intial rules")
	}

	for watcher.Next() {
		td, err := genRules(hv, c)
		if err != nil {
			continue
		}
		if err := applyRules(rules, td); err != nil {
			log.WithField("error", err).Fatal("could not apply rules")
		}
	}
	if err := watcher.Err(); err != nil {
		log.Fatal(err)
	}
}
Esempio n. 9
0
func main() {
	rand.Seed(time.Now().UTC().UnixNano())
	e := etcd.NewClient([]string{"http://127.0.0.1:4001"})
	c := lochness.NewContext(e)

	f := c.NewFlavor()
	f.CPU = 1
	f.Memory = 512
	f.Disk = 1024
	if err := f.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    f.ID,
			"item":  "flavor",
		}).Fatal("failed to save flavor")
	}

	n := c.NewNetwork()
	if err := n.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    n.ID,
			"item":  "network",
		}).Fatal("failed to save network")
	}

	fw := c.NewFWGroup()
	fw.Rules = append(fw.Rules, &lochness.FWRule{})

	if err := fw.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    fw.ID,
			"item":  "fwgroup",
		}).Fatal("failed to save fwgroup")
	}

	s := c.NewSubnet()
	var err error
	cidr := "127.0.0.0/24"
	_, s.CIDR, err = net.ParseCIDR(cidr)
	if err != nil {
		log.WithFields(log.Fields{
			"func":  "net.ParseCIDR",
			"error": err,
			"id":    s.ID,
			"cidr":  cidr,
		}).Fatal("failed to parse subnet CIDR")
	}
	s.Gateway = net.IPv4(127, 0, 0, 1)
	s.StartRange = net.IPv4(127, 0, 0, 10)
	s.EndRange = net.IPv4(127, 0, 0, 250)
	if err := s.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    s.ID,
			"item":  "subnet",
		}).Fatal("failed to save subnet")
	}

	if err := n.AddSubnet(s); err != nil {
		log.WithFields(log.Fields{
			"func":  "AddSubnet",
			"error": err,
			"id":    n.ID,
			"item":  "network",
		}).Fatal("failed to add subnet to network")
	}

	h := c.NewHypervisor()
	h.IP = net.IPv4(127, 0, 0, 1)
	mac := "01:23:45:67:89:ab"
	h.MAC, err = net.ParseMAC(mac)
	if err != nil {
		log.WithFields(log.Fields{
			"func":  "net.ParseMAC",
			"error": err,
			"id":    h.ID,
			"mac":   mac,
			"item":  "hypervisor",
		}).Fatal("failed to parse hypervisor mac")
	}
	h.TotalResources = f.Resources
	h.AvailableResources = f.Resources
	if err := h.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    h.ID,
			"item":  "hypervisor",
		}).Fatal("failed to save hypervisor")
	}
	if err := h.AddSubnet(s, "br0"); err != nil {
		log.WithFields(log.Fields{
			"func":  "AddSubnet",
			"error": err,
			"id":    h.ID,
			"item":  "hypervisor",
		}).Fatal("failed to add subnet")
	}

	g := c.NewGuest()
	g.SubnetID = s.ID
	g.NetworkID = n.ID
	g.FlavorID = f.ID
	mac = "01:23:45:67:89:ac"
	g.MAC, err = net.ParseMAC(mac)
	if err != nil {
		log.WithFields(log.Fields{
			"func":  "net.ParseMAC",
			"error": err,
			"id":    g.ID,
			"mac":   mac,
			"item":  "guest",
		}).Fatal("failed to parse guest mac")
	}
	if err := g.Save(); err != nil {
		log.WithFields(log.Fields{
			"func":  "Save",
			"error": err,
			"id":    g.ID,
			"item":  "guest",
		}).Fatal("failed to save guest")
	}
	if err := h.AddGuest(g); err != nil {
		log.WithFields(log.Fields{
			"func":  "AddGuest",
			"error": err,
			"id":    h.ID,
			"item":  "hypervisor",
			"guest": g.ID,
		}).Fatal("failed to add guest to hypervisor")
	}

	g.IP, err = s.ReserveAddress(g.ID)
	if err != nil {
		log.WithFields(log.Fields{
			"func":  "ReserverAddress",
			"error": err,
			"id":    s.ID,
			"item":  "subnet",
		}).Fatal("failed to reserver address")
	}

	agent := c.NewMistifyAgent()
	clientGuest, err := agent.CreateGuest(g.ID)
	if err != nil {
		log.WithFields(log.Fields{
			"func":  "agent.CreateGuest",
			"error": err,
			"id":    g.ID,
			"item":  "agent",
		}).Fatal("failed to create guest")
	}
	print(clientGuest)
}
Esempio n. 10
0
func main() {
	port := flag.UintP("port", "p", 8888, "address to listen")
	eaddr := flag.StringP("etcd", "e", "http://127.0.0.1:4001", "address of etcd machine")
	baseURL := flag.StringP("base", "b", "http://ipxe.mistify.local:8888", "base address of bits request")
	defaultVersion := flag.StringP("version", "v", "0.1.0", "If all else fails, what version to serve")
	imageDir := flag.StringP("images", "i", "/var/lib/images", "directory containing the images")
	addOpts := flag.StringP("options", "o", "", "additional options to add to boot kernel")
	statsd := flag.StringP("statsd", "s", "", "statsd address")

	flag.Parse()

	e := etcd.NewClient([]string{*eaddr})
	c := lochness.NewContext(e)

	router := mux.NewRouter()
	router.StrictSlash(true)

	s := &server{
		ctx:            c,
		t:              template.Must(template.New("ipxe").Parse(ipxeTemplate)),
		c:              template.Must(template.New("config").Parse(configTemplate)),
		r:              regexp.MustCompile(envRegex),
		defaultVersion: *defaultVersion,
		baseURL:        *baseURL,
		addOpts:        *addOpts,
		etcdAddr:       *eaddr,
	}

	chain := alice.New(
		func(h http.Handler) http.Handler {
			return recovery.Handler(os.Stderr, h, true)
		},
		func(h http.Handler) http.Handler {
			return handlers.CombinedLoggingHandler(os.Stdout, h)
		},
		handlers.CompressHandler,
	)

	sink := mapsink.New()
	fanout := metrics.FanoutSink{sink}

	if *statsd != "" {
		ss, _ := metrics.NewStatsdSink(*statsd)
		fanout = append(fanout, ss)
	}

	conf := metrics.DefaultConfig("cbootstrapd")
	conf.EnableHostname = false
	m, _ := metrics.New(conf, fanout)
	mw := mmw.New(m)

	router.PathPrefix("/debug/").Handler(chain.Append(mw.HandlerWrapper("debug")).Then(http.DefaultServeMux))
	router.PathPrefix("/images").Handler(chain.Append(mw.HandlerWrapper("images")).Then(http.StripPrefix("/images/", http.FileServer(http.Dir(*imageDir)))))
	router.Handle("/metrics", chain.Append(mw.HandlerWrapper("metrics")).ThenFunc(
		func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			if err := json.NewEncoder(w).Encode(sink); err != nil {
				log.WithField("error", err).Error(err)
			}
		}))

	chain = chain.Append(func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			context.Set(r, "_server_", s)
			h.ServeHTTP(w, r)
		})
	})
	router.Handle("/ipxe/{ip}", chain.Append(mw.HandlerWrapper("ipxe")).ThenFunc(ipxeHandler))
	router.Handle("/config/{ip}", chain.Append(mw.HandlerWrapper("config")).ThenFunc(configHandler))

	if err := http.ListenAndServe(fmt.Sprintf(":%d", *port), router); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "http.ListenAndServe",
		}).Fatal("ListenAndServe returned an error")
	}
}
Esempio n. 11
0
func main() {
	var port uint
	var etcdAddr, bstalk, logLevel, statsd string

	flag.UintVarP(&port, "port", "p", 18000, "listen port")
	flag.StringVarP(&etcdAddr, "etcd", "e", defaultEtcdAddr, "address of etcd machine")
	flag.StringVarP(&bstalk, "beanstalk", "b", "127.0.0.1:11300", "address of beanstalkd server")
	flag.StringVarP(&logLevel, "log-level", "l", "warn", "log level")
	flag.StringVarP(&statsd, "statsd", "s", "", "statsd address")
	flag.Parse()

	if err := logx.DefaultSetup(logLevel); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "logx.DefaultSetup",
			"level": logLevel,
		}).Fatal("unable to set up logrus")
	}

	etcdClient := etcd.NewClient([]string{etcdAddr})

	if !etcdClient.SyncCluster() {
		log.WithFields(log.Fields{
			"error": nil,
			"func":  "etcd.SyncCluster",
			"addr":  etcdAddr,
		}).Fatal("unable to sync etcd cluster")
	}

	ctx := lochness.NewContext(etcdClient)

	log.WithField("address", bstalk).Info("connection to beanstalk")
	jobQueue, err := jobqueue.NewClient(bstalk, etcdClient)
	if err != nil {
		log.WithFields(log.Fields{
			"error":   err,
			"address": bstalk,
		}).Fatal("failed to create jobQueue client")
	}

	// setup metrics
	sink := mapsink.New()
	fanout := metrics.FanoutSink{sink}

	if statsd != "" {
		ss, _ := metrics.NewStatsdSink(statsd)
		fanout = append(fanout, ss)
	}
	conf := metrics.DefaultConfig("cguestd")
	conf.EnableHostname = false
	m, _ := metrics.New(conf, fanout)

	mctx := &metricsContext{
		sink:    sink,
		metrics: m,
		mmw:     mmw.New(m),
	}

	if err := Run(port, ctx, jobQueue, mctx); err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("failed to run server")
	}
}