func applyVerifyRangeTag(t *testing.T, cfgBytes []byte, shouldFail bool) {
	initFakeStateDriver(t)
	defer deinitFakeStateDriver()

	cfg := &intent.Config{}
	err := json.Unmarshal(cfgBytes, cfg)
	if err != nil {
		t.Fatalf("error '%s' parsing config '%s'\n", err, cfgBytes)
	}

	_, err = resources.NewStateResourceManager(fakeDriver)
	if err != nil {
		log.Fatalf("state store initialization failed. Error: %s", err)
	}
	defer func() { resources.ReleaseStateResourceManager() }()

	// setup global state
	gCfg := &gstate.Cfg{}
	gCfg.StateDriver = fakeDriver
	gCfg.Auto.VLANs = "11-1000"
	gCfg.Auto.VXLANs = "1001-2000"

	// setup resources
	err = gCfg.Process()
	if err != nil {
		t.Fatalf("Error updating the config %+v. Error: %s", gCfg, err)
	}

	err = gCfg.Write()
	if err != nil {
		t.Fatalf("error updating global config.Error: %s", err)
	}

	tenant := cfg.Tenants[0]
	err = CreateTenant(fakeDriver, &tenant)
	if err != nil {
		t.Fatalf("error '%s' creating tenant\n", err)
	}

	err = CreateNetworks(fakeDriver, &tenant)
	if shouldFail {

		var expError string
		network := tenant.Networks[0]
		if network.PktTagType == "vlan" {
			expError = "requested vlan not available"
		} else {
			expError = "requested vxlan not available"
		}

		if err == nil {
			t.Fatalf("CreateNetworks did not return error\n")
		} else if !strings.Contains(err.Error(), expError) {
			t.Fatalf("CreateNetworks did not return error for OutOfRange\n")
		}
	} else if err != nil {
		t.Fatalf("error '%s' while creating network\n", err)
	}

}
Beispiel #2
0
// Init initializes the master daemon
func (d *MasterDaemon) Init() {
	// set cluster mode
	err := master.SetClusterMode(d.ClusterMode)
	if err != nil {
		log.Fatalf("Failed to set cluster-mode. Error: %s", err)
	}

	// save dns flag
	err = master.SetDNSEnabled(d.DNSEnabled)
	if err != nil {
		log.Fatalf("Failed to set dns-enable. Error: %s", err)
	}

	// initialize state driver
	d.stateDriver, err = initStateDriver(d.ClusterStore)
	if err != nil {
		log.Fatalf("Failed to init state-store. Error: %s", err)
	}

	// Initialize resource manager
	d.resmgr, err = resources.NewStateResourceManager(d.stateDriver)
	if err != nil {
		log.Fatalf("Failed to init resource manager. Error: %s", err)
	}
}
Beispiel #3
0
// Init initializes the master daemon
func (d *MasterDaemon) Init() {
	// set cluster mode
	err := master.SetClusterMode(d.ClusterMode)
	if err != nil {
		log.Fatalf("Failed to set cluster-mode. Error: %s", err)
	}

	// save dns flag
	err = master.SetDNSEnabled(d.DNSEnabled)
	if err != nil {
		log.Fatalf("Failed to set dns-enable. Error: %s", err)
	}

	// initialize state driver
	d.stateDriver, err = initStateDriver(d.ClusterStore)
	if err != nil {
		log.Fatalf("Failed to init state-store. Error: %s", err)
	}

	// Initialize resource manager
	d.resmgr, err = resources.NewStateResourceManager(d.stateDriver)
	if err != nil {
		log.Fatalf("Failed to init resource manager. Error: %s", err)
	}

	// Create an objdb client
	d.objdbClient, err = objdb.NewClient(d.ClusterStore)
	if err != nil {
		log.Fatalf("Error connecting to state store: %v. Err: %v", d.ClusterStore, err)
	}
}
Beispiel #4
0
func TestGlobalConfigAutoVXLAN(t *testing.T) {
	cfgData := []byte(`
        {
            "Tenant"  : "default",
            "Auto" : {
                "SubnetPool"        : "11.5.0.0",
                "SubnetLen"         : 16,
                "AllocSubnetLen"    : 24,
                "VLANs"             : "1-10",
                "VXLANs"            : "15000-17000"
            },
            "Deploy" : {
                "DefaultNetType"    : "vxlan"
            }
        }`)
	var vxlan, localVLAN uint

	gc, err := Parse(cfgData)
	if err != nil {
		t.Fatalf("error '%s' parsing config '%s' \n", err, cfgData)
	}

	gstateSD.Init(nil)
	defer func() { gstateSD.Deinit() }()
	gc.StateDriver = gstateSD
	_, err = resources.NewStateResourceManager(gstateSD)
	if err != nil {
		t.Fatalf("Failed to instantiate resource manager. Error: %s", err)
	}
	defer func() { resources.ReleaseStateResourceManager() }()

	err = gc.Process("vlan")
	if err != nil {
		t.Fatalf("error '%s' processing config %v \n", err, gc)
	}
	err = gc.Process("vxlan")
	if err != nil {
		t.Fatalf("error '%s' processing config %v \n", err, gc)
	}
	vxlan, localVLAN, err = gc.AllocVXLAN(uint(0))
	if err != nil {
		t.Fatalf("error - allocating vxlan - %s \n", err)
	}
	if vxlan == 0 {
		t.Fatalf("error - invalid vxlan allocated %d \n", vxlan)
	}
	if localVLAN == 0 {
		t.Fatalf("error - invalid vlan allocated %d \n", localVLAN)
	}

	err = gc.FreeVXLAN(vxlan, localVLAN)
	if err != nil {
		t.Fatalf("error freeing allocated vxlan %d localvlan %d - err '%s' \n",
			vxlan, localVLAN, err)
	}
}
Beispiel #5
0
func applyConfig(t *testing.T, cfgBytes []byte) {
	cfg := &intent.Config{}
	err := json.Unmarshal(cfgBytes, cfg)
	if err != nil {
		t.Fatalf("error '%s' parsing config '%s'\n", err, cfgBytes)
	}

	_, err = resources.NewStateResourceManager(fakeDriver)
	if err != nil {
		log.Fatalf("state store initialization failed. Error: %s", err)
	}
	defer func() { resources.ReleaseStateResourceManager() }()

	// setup global state
	gCfg := &gstate.Cfg{}
	gCfg.StateDriver = fakeDriver
	gCfg.Auto.VLANs = "1-4094"
	gCfg.Auto.VXLANs = "1-10000"

	// setup resources
	err = gCfg.Process("vxlan")
	if err != nil {
		t.Fatalf("Error updating the config %+v. Error: %s", gCfg, err)
	}
	err = gCfg.Process("vlan")
	if err != nil {
		t.Fatalf("Error updating the config %+v. Error: %s", gCfg, err)
	}
	err = gCfg.Write()
	if err != nil {
		t.Fatalf("error updating global config.Error: %s", err)
	}

	for _, tenant := range cfg.Tenants {
		err = CreateTenant(fakeDriver, &tenant)
		if err != nil {
			t.Fatalf("error '%s' creating tenant\n", err)
		}

		err = CreateNetworks(fakeDriver, &tenant)
		if err != nil {
			t.Fatalf("error '%s' creating networks\n", err)
		}

		err = CreateEndpoints(fakeDriver, &tenant)
		if err != nil {
			t.Fatalf("error '%s' creating endpoints\n", err)
		}
	}

	fakeDriver.DumpState()
}
Beispiel #6
0
// setup the test netmaster REST server and client
func TestMain(m *testing.M) {
	var err error

	// Setup state store
	stateStore, err = initStateDriver()
	if err != nil {
		log.Fatalf("Error initializing state store. Err: %v", err)
	}
	// little hack to clear all state from etcd
	stateStore.(*state.EtcdStateDriver).Client.Delete("/contiv.io", true)

	// Setup resource manager
	if _, err = resources.NewStateResourceManager(stateStore); err != nil {
		log.Fatalf("Failed to init resource manager. Error: %s", err)
	}

	router := mux.NewRouter()

	// Create a new api controller
	apiController = NewAPIController(router)

	ofnetMaster := ofnet.NewOfnetMaster(ofnet.OFNET_MASTER_PORT)
	if ofnetMaster == nil {
		log.Fatalf("Error creating ofnet master")
	}

	// initialize policy manager
	mastercfg.InitPolicyMgr(stateStore, ofnetMaster)

	// Create HTTP server
	go http.ListenAndServe(netmasterTestListenURL, router)
	time.Sleep(time.Second)

	// create a new contiv client
	contivClient, err = client.NewContivClient(netmasterTestURL)
	if err != nil {
		log.Fatalf("Error creating contiv client. Err: %v", err)
	}

	// Create default tenant
	createDefaultTenant()

	exitCode := m.Run()
	if exitCode == 0 {
		cleanupState()
	}
	os.Exit(exitCode)
}
Beispiel #7
0
func execOpts(opts *cliOpts) core.StateDriver {

	if opts.help {
		fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
		flagSet.PrintDefaults()
		os.Exit(0)
	}

	if opts.version {
		fmt.Printf(version.String())
		os.Exit(0)
	}

	log.SetFormatter(&log.TextFormatter{FullTimestamp: true, TimestampFormat: time.StampNano})

	if opts.debug {
		log.SetLevel(log.DebugLevel)
	}

	if err := master.SetClusterMode(opts.clusterMode); err != nil {
		log.Fatalf("Failed to set cluster-mode. Error: %s", err)
	}

	if err := master.SetDNSEnabled(opts.dnsEnabled); err != nil {
		log.Fatalf("Failed to set dns-enable. Error: %s", err)
	}

	sd, err := initStateDriver(opts)
	if err != nil {
		log.Fatalf("Failed to init state-store. Error: %s", err)
	}

	if _, err = resources.NewStateResourceManager(sd); err != nil {
		log.Fatalf("Failed to init resource manager. Error: %s", err)
	}

	return sd
}
Beispiel #8
0
func (d *daemon) execOpts() {
	if err := d.parseOpts(); err != nil {
		log.Fatalf("Failed to parse cli options. Error: %s", err)
	}

	if d.opts.help {
		fmt.Fprintf(os.Stderr, "Usage: %s [OPTION]...\n", os.Args[0])
		flagSet.PrintDefaults()
		os.Exit(0)
	}

	if d.opts.version {
		fmt.Printf(version.String())
		os.Exit(0)
	}

	log.SetFormatter(&log.TextFormatter{FullTimestamp: true, TimestampFormat: time.StampNano})

	if d.opts.debug {
		log.SetLevel(log.DebugLevel)
	}

	if err := master.SetClusterMode(d.opts.clusterMode); err != nil {
		log.Fatalf("Failed to set cluster-mode. Error: %s", err)
	}

	sd, err := initStateDriver(&d.opts)
	if err != nil {
		log.Fatalf("Failed to init state-store. Error: %s", err)
	}

	if _, err = resources.NewStateResourceManager(sd); err != nil {
		log.Fatalf("Failed to init resource manager. Error: %s", err)
	}

	d.stateDriver = sd
}
Beispiel #9
0
func main() {
	var rsrcName string
	var clusterStore string
	var setVal string
	var stateName string
	var stateID string
	var fieldName string

	// parse all commandline args
	flagSet := flag.NewFlagSet("cfgtool", flag.ExitOnError)
	flagSet.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flagSet.PrintDefaults()
		fmt.Fprintf(os.Stderr, "\nExamples:\n")
		fmt.Fprintf(os.Stderr, "%s -state <state-name> -id <state-id> -field <field-name> -set <new-value>\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "	%s -state GlobConfig -id global -field FwdMode -set routing\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "%s -resource <vlan|vxlan> -set <new-range>\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "	%s -resource vlan -set 1-10\n", os.Args[0])
	}

	flagSet.StringVar(&rsrcName,
		"resource",
		"",
		"Resource to modify [vlan|vxlan]")
	flagSet.StringVar(&setVal,
		"set",
		"",
		"Resource value")
	flagSet.StringVar(&clusterStore,
		"cluster-store",
		"etcd://127.0.0.1:2379",
		"Etcd or Consul cluster store url.")
	flagSet.StringVar(&stateName,
		"state",
		"",
		"State to modify")
	flagSet.StringVar(&stateID,
		"id",
		"",
		"State ID to modify")
	flagSet.StringVar(&fieldName,
		"field",
		"",
		"State Field to modify")
	if err := flagSet.Parse(os.Args[1:]); err != nil {
		log.Errorf("Error parsing commandline args: %v", err)
		return
	}

	// check if we have sufficient args
	if (rsrcName == "" && stateName == "") ||
		(stateName != "" && stateID == "") ||
		(stateName != "" && stateID != "" && setVal != "" && fieldName == "") {
		flagSet.Usage()
		os.Exit(2)
	}

	// initialize state driver
	stateDriver, err := initStateDriver(clusterStore)
	if err != nil {
		log.Fatalf("Failed to init state-store. Error: %s", err)
	}

	// Initialize resource manager
	resmgr, err := resources.NewStateResourceManager(stateDriver)
	if err != nil || resmgr == nil {
		log.Fatalf("Failed to init resource manager. Error: %s", err)
	}

	// process `-resource` command
	if rsrcName != "" {
		err = processResource(stateDriver, rsrcName, setVal)
		if err != nil {
			log.Errorf("Error processing resource %s. Err: %v", rsrcName, err)
		}

		return
	}

	// handle `-state` command
	if stateName != "" && stateID != "" {
		err = processState(stateDriver, stateName, stateID, fieldName, setVal)
		if err != nil {
			log.Errorf("Error processing state %s{ id : %s }. Err: %v", stateName, stateID, err)
		}
	}
}
Beispiel #10
0
// TestNetworkDeleteWithEPs
// This test creates a network and adds endpoints to it.
// It then tries to delete the network, while it has
// active endpoints and expects them to fail
func TestNetworkDeleteWithEPs(t *testing.T) {
	cfgBytes := []byte(`{
    "Tenants" : [{
        "Name"                  : "tenant-one",
        "Networks"  : [{
            "Name"              : "orange",
            "SubnetCIDR"        : "10.1.1.1/24",
            "Gateway"           : "10.1.1.254",
            "Endpoints" : [
            {
                "Container"     : "myContainer1"
            },
            {
                "Container"     : "myContainer3"
            }
            ]
        }]
    }]}`)

	initFakeStateDriver(t)
	defer deinitFakeStateDriver()

	applyConfig(t, cfgBytes)

	epBindings := []intent.ConfigEP{{
		Container: "myContainer1",
		Host:      "host1",
	}, {
		Container: "myContainer2",
		Host:      "host1",
	}, {
		Container: "myContainer3",
		Host:      "host2",
	}, {
		Container: "myContainer4",
		Host:      "host2",
	}}

	err := CreateEpBindings(&epBindings)
	if err != nil {
		t.Fatalf("error '%s' creating tenant\n", err)
	}

	cfg := &intent.Config{}
	err = json.Unmarshal(cfgBytes, cfg)
	if err != nil {
		t.Fatalf("error '%s' parsing config '%s'\n", err, cfgBytes)
	}

	_, err = resources.NewStateResourceManager(fakeDriver)
	if err != nil {
		log.Fatalf("state store initialization failed. Error: %s", err)
	}
	defer func() { resources.ReleaseStateResourceManager() }()

	for _, tenant := range cfg.Tenants {
		err = DeleteNetworks(fakeDriver, &tenant)
		if err == nil || (err != nil && !strings.Contains(err.Error(), "Error: Network has active endpoints")) {
			t.Fatalf("Network delete did not Fail with Active EPs.")
		}
	}
}