Ejemplo n.º 1
0
func do_local_findvalue(argv []string) {
	id, err := kademlia.FromString(argv[1])
	if err != nil {
		log.Fatal("Get Local Value: ", err)
	}
	kademlia.Get_local_value(id)
}
Ejemplo n.º 2
0
func do_iterative_findnode(argv []string) {
	id, err := kademlia.FromString(argv[1])
	if err != nil {
		log.Fatal("Find Node: ", err)
	}
	kademlia.IterativeFindNode(id)
}
Ejemplo n.º 3
0
func do_get_contact(argv []string) {
	id, err := kademlia.FromString(argv[1])
	if err != nil {
		log.Fatal("Find Node: ", err)
	}
	kademlia.Find_node(id)
}
Ejemplo n.º 4
0
func notify_release_lock(argv []string) {
	id, err := kademlia.FromString(argv[1])
	if err != nil {
		log.Fatal("Find Node: ", err)
	}
	kademlia.ThisNode.Notify_Release_Lock(id)
}
Ejemplo n.º 5
0
func request_lock(argv []string) {
	id, err := kademlia.FromString(argv[1])
	if err != nil {
		log.Fatal("Find Node: ", err)
	}
	kademlia.ThisNode.Request_Lock(id)
}
Ejemplo n.º 6
0
func do_iterative_store(argv []string) {
	k, err := kademlia.FromString(argv[1])
	if err != nil {
		log.Fatal("Iterative Store: ", err)
	}
	b := []byte(argv[2])
	kademlia.IterativeStore(k, b)
}
Ejemplo n.º 7
0
func doPing(kadem *kademlia.Kademlia, con kademlia.Contact, addressOrId string) {
	var pingAddress string
	if len(strings.Split(addressOrId, string(":"))) == 2 {
		pingAddress = addressOrId
	} else {
		id, err := kademlia.FromString(addressOrId)
		if err != nil {
			fmt.Printf("ERR could not interpret nodeid as ID")
			return
		}
		con, err := kadem.ContactFromID(id)
		if err != nil {
			fmt.Println("ERR : unknown node")
			return
		}
		pingAddress = contactToAddrString(con)
	}
	client, err := rpc.DialHTTP("tcp", pingAddress)
	if err != nil {
		log.Fatal("DialHTTP: ", err)
	}
	ping := kademlia.Ping{Sender: con}
	ping.MsgID = kademlia.NewRandomID()
	var pong kademlia.Pong
	err = client.Call("Kademlia.Ping", ping, &pong)
	if err != nil {
		log.Fatal("Call: ", err)
	}

	if ping.MsgID.Equals(pong.MsgID) {
		fmt.Print("OK\n")
	} else {
		fmt.Print("ERR : response message id does not match\n")
	}
	_ = client.Close()
}
Ejemplo n.º 8
0
func NewKademliaInstruction(s string) (kInst *KademliaInstruction) {
	var err error
	var strTokens []string

	kInst = new(KademliaInstruction)

	//remove the newline character
	s = strings.TrimRight(s, "\n")

	//split string, separator is the white-space
	strTokens = strings.Split(s, " ")

	//log.Printf("Parsing command: %s\n", strTokens)

	kInst.flags = 255 //255 means skip cause nothing could be matched, check with IsSkip()
	kInst.Data = s    //store the whole string somewhere so we can print for debugging

	switch strings.ToLower(strTokens[0]) {
	case "exit":
		kInst.flags = 1
	case "ping":
		//kademlia.Assert(len(strTokens) == 2, "Ping requires 1 argument")//ping nodeID, ping host:port
		if len(strTokens) != 2 {
			return kInst
		}
		kInst.flags = 2
		if strings.Contains(strTokens[1], ":") {
			kInst.Addr = strTokens[1]
		} else {
			kInst.Addr = ""
			kInst.NodeID, err = kademlia.FromString(strTokens[1])
		}
	case "store":
		//kademlia.Assert(len(strTokens) == 4, "Store requires 3 argument")//store nodeID key value
		if len(strTokens) != 4 {
			return kInst
		}
		kInst.flags = 3
		kInst.NodeID, err = kademlia.FromString(strTokens[1])
		kInst.Key, err = kademlia.FromString(strTokens[2])
		kInst.Data = strTokens[3]
	case "find_node":
		//kademlia.Assert(len(strTokens) == 3, "FindNode requires 2 argument")//find_node nodeID key
		if len(strTokens) != 3 {
			return kInst
		}
		kInst.flags = 4
		kInst.NodeID, err = kademlia.FromString(strTokens[1])
		kInst.Key, err = kademlia.FromString(strTokens[2])
	case "find_value":
		//kademlia.Assert(len(strTokens) == 3, "FindValue requires 2 argument")//find_value nodeID key
		if len(strTokens) != 3 {
			return kInst
		}
		kInst.flags = 5
		kInst.NodeID, err = kademlia.FromString(strTokens[1])
		kInst.Key, err = kademlia.FromString(strTokens[2])
	case "whoami":
		//kademlia.Assert(len(strTokens) == 1, "GetNodeId requires 0 argument")//whoami
		if len(strTokens) != 1 {
			return kInst
		}
		kInst.flags = 6
	case "local_find_value":
		//kademlia.Assert(len(strTokens) == 2, "LocalFindValue requires 1 argument")//local_find_value key
		if len(strTokens) != 2 {
			return kInst
		}
		kInst.flags = 7
		kInst.Key, err = kademlia.FromString(strTokens[1])
	case "get_contact":
		//kademlia.Assert(len(strTokens) == 2, "GetContact requires 1 argument")//get_contact nodeID
		if len(strTokens) != 2 {
			return kInst
		}
		kInst.flags = 8
		kInst.NodeID, err = kademlia.FromString(strTokens[1])
	case "iterativestore":
		//kademlia.Assert(len(strTokens) == 3, "IterativeStore requires 2 argument")//iterativeStore key value
		if len(strTokens) != 3 {
			return kInst
		}
		kInst.flags = 9
		kInst.Key, err = kademlia.FromString(strTokens[1])
		kInst.Data = strTokens[2]
	case "iterativefindnode":
		//kademlia.Assert(len(strTokens) == 2, "IterativeFindNode requires 1 argument")//iterativeFindNode nodeID
		if len(strTokens) != 2 {
			return kInst
		}
		kInst.flags = 10
		kInst.NodeID, err = kademlia.FromString(strTokens[1])
	case "iterativefindvalue":
		//kademlia.Assert(len(strTokens) == 2, "IterativeFindValue requires 1 argument")//iterativeFindValue key
		if len(strTokens) != 2 {
			return kInst
		}
		kInst.flags = 11
		kInst.Key, err = kademlia.FromString(strTokens[1])
	case "runtests":
		//kademlia.Assert(len(strTokens) == 2, "runtests requires 1 arguments")//runtests number of kademlia instances to start
		if len(strTokens) != 2 {
			return kInst
		}
		kInst.flags = 12
		kInst.Data = strTokens[1]
	case "plb":
		//kademlia.Assert(len(strTokens) == 1, "printLocalBuckets requires 0 arguments")//plb
		if len(strTokens) != 1 {
			return kInst
		}
		kInst.flags = 13
	case "pld":
		//kademlia.Assert(len(strTokens) == 1, "printLocalData requires 0 arguments")//pld
		if len(strTokens) != 1 {
			return kInst
		}
		kInst.flags = 14
	}
	//log.Printf("Flag: %d\n", kInst.flags);

	if err != nil {

	}

	return kInst
}
Ejemplo n.º 9
0
func do_iterative_findvalue(argv []string) {
	k, _ := kademlia.FromString(argv[1])
	kademlia.IterativeFindValue(k)
}
Ejemplo n.º 10
0
func main() {

	// By default, Go seeds its RNG with 1. This would cause every program to

	// generate the same sequence of IDs.

	rand.Seed(time.Now().UnixNano())

	// Get the bind and connect connection strings from command-line arguments.

	flag.Parse()

	args := flag.Args()

	if len(args) != 2 {

		log.Fatal("Must be invoked with exactly two arguments!\n")

	}

	listenStr := args[0]

	firstPeerStr := args[1]

	fmt.Printf("kademlia starting up!\n")

	kadem := kademlia.NewKademlia()

	tcpAddr, err := net.ResolveTCPAddr("tcp4", args[0])

	kadem.MyContact.Host = tcpAddr.IP

	kadem.MyContact.Port = uint16(tcpAddr.Port)

	rpc.Register(kadem)

	rpc.HandleHTTP()

	l, err := net.Listen("tcp", listenStr)

	if err != nil {

		log.Fatal("Listen: ", err)

	}

	// Serve forever.

	go http.Serve(l, nil)

	// Confirm our server is up with a PING request and then exit.

	// Your code should loop forever, reading instructions from stdin and

	// printing their results to stdout. See README.txt for more details.

	client, err := rpc.DialHTTP("tcp", firstPeerStr)

	if err != nil {

		log.Fatal("DialHTTP: ", err)

	}

	ping := new(kademlia.Ping)

	ping.MsgID = kademlia.NewRandomID()

	var pong kademlia.Pong

	err = client.Call("Kademlia.Ping", ping, &pong)

	if err != nil {

		log.Fatal("Call: ", err)

	}

	//log.Printf("ping msgID: %s\n", ping.MsgID.AsString())

	// log.Printf("pong msgID: %s\n", pong.MsgID.AsString())

	tcpAdd, err := net.ResolveTCPAddr("tcp4", args[1])

	host := tcpAdd.IP

	port := uint16(tcpAdd.Port)

	//fmt.Println(pong.Sender)

	nodeID := pong.Sender.NodeID

	cont := kademlia.Contact{nodeID, host, port}

	kademlia.Join(kadem, cont)

	for true {

		var command, arg1, arg2, arg3 string

		fmt.Scanf("%s", &command, "\n")

		//fmt.Print("command:", command)

		switch command {

		case "whoami":

			//Print your node ID

			kademlia.WhoAmI(kadem)

		case "local_find_value":

			//If your node has data for the given key, print it.

			//If your node does not have data for the given key, you should print "ERR".

			fmt.Scanf("%s", &arg1)

			key := arg1

			kademlia.LocalFindValue(kadem, key)

		case "get_contact":

			//If your buckets contain a node with the given ID, printf("%v %v\n",theNode.addr,theNode.port)

			//If your buckers do not contain any such node, print "ERR".

			fmt.Scanf("%s", &arg1)

			ID := arg1

			//fmt.Println(ID)

			kademlia.GetContact(kadem, ID)

		case "iterativeStore":

			//Perform the iterativeStore operation and then print the ID of the node that received the final STORE operation.

			fmt.Scanf("%s %s", &arg1, &arg2)

			key := arg1

			keyId, err := kademlia.FromString(key)

			if err != nil {

			}

			value := arg2

			//fmt.Println(key,value)

			storereq := kademlia.StoreRequest{}

			var kclosenodes *list.List

			storereq.Sender = kadem.MyContact

			storereq.MsgID = kademlia.NewRandomID()

			storereq.Key = keyId

			storereq.Value = []byte(value)

			kadem.IterativeStore(storereq, kclosenodes)

		case "iterativeFindNode":

			//Print a list of ≤ k closest nodes and print their IDs. You should collect the IDs in a slice and print that.

			fmt.Scanf("%s", &arg1)

			ID := arg1

			//fmt.Println(ID)

			ID2, err := kademlia.FromString(ID)

			if err != nil {

			}

		//kadem.IterativeFindNode(ID2, false)

		case "iterativeFindValue":

			//printf("%v %v\n"  ID, value), where ID refers to the node that finally returned the value. If you do not find a value, print "ERR".

			fmt.Scanf("%s", &arg1)

			key := arg1

			//fmt.Println(key)

			keyId, err := kademlia.FromString(key)

			if err != nil {

			}

			findvalueresult := kademlia.FindValueResult{}

			kadem.IterativeFindValue(keyId, &findvalueresult)

		case "ping":

			fmt.Scanf("%s", &arg1)

			nodeID := arg1

			//fmt.Println(nodeID)

			if strings.ContainsAny(nodeID, ":") {

				client, err := rpc.DialHTTP("tcp", arg1)

				if err != nil {

					log.Fatal("DialHTTP: ", err)

				}

				ping := new(kademlia.Ping)

				ping.MsgID = kademlia.NewRandomID()

				var pong kademlia.Pong

				err = client.Call("Kademlia.Ping", ping, &pong)

				if err != nil {

					log.Fatal("Call: ", err)

					fmt.Println("Err")

					continue

				}

				tcpAdd, err := net.ResolveTCPAddr("tcp4", arg1)

				host := tcpAdd.IP

				port := uint16(tcpAdd.Port)

				//fmt.Println(pong.Sender)

				nodeID := pong.Sender.NodeID

				cont := kademlia.Contact{nodeID, host, port}

				kademlia.Update(kadem, &cont)

				fmt.Println("Ping success")

				continue

			}

			isPing := kademlia.CallPings(kadem, nodeID)

			if isPing != true {

				fmt.Println("Error in Ping")

			}

		case "store":

			//Perform a store and print a blank line.

			fmt.Scanf("%s %s", &arg1, &arg2)

			nodeID := arg1

			key := arg2

			r := bufio.NewReader(os.Stdin)

			arg3, err = r.ReadString(10)

			//fmt.Fscanln(r, &arg3)

			//arg3 = bufio.ReadString('\n')

			value := arg3

			//fmt.Println("ID: ", nodeID, "key: ", key, "value", value)

			isStored := kademlia.CallStore(kadem, nodeID, key, value)

			if isStored != true {

				fmt.Println("Error in Store")

			}

		case "find_node":

			//Perform a find_node and print its results as for iterativeFindNode.

			fmt.Scanf("%s %s", &arg1, &arg2)

			nodeID := arg1

			key := arg2

			//fmt.Println(nodeID, key)

			isFound := kademlia.CallFindNode(kadem, nodeID, key)

			if isFound != true {

				fmt.Println("Error in finding")

			}

		case "find_value":

			//Perform a find_value. If it returns nodes, print them as for find_node. If it returns a value, print the value as in iterativeFindValue.

			fmt.Scanf("%s %s", &arg1, &arg2)

			nodeID := arg1

			key := arg2

			//fmt.Println(nodeID, key)

			isFound := kademlia.CallFindValue(kadem, nodeID, key)

			if isFound != true {

				fmt.Println("UnSuccessful ")

			}
			break

		case "exit":
			break

		}

		if command == "exit" {
			break
		}

	}

}
Ejemplo n.º 11
0
func main() {
	// By default, Go seeds its RNG with 1. This would cause every program to
	// generate the same sequence of IDs.
	//	rand.seed()
	rand.Seed(time.Now().UnixNano())

	// Get the bind and connect connection strings from command-line arguments.
	flag.Parse()
	args := flag.Args()
	if len(args) != 2 {
		log.Fatal("Must be invoked with exactly two arguments!\n")
	}
	listenStr := args[0]
	firstPeerStr := args[1]
	fmt.Printf("kademlia starting up!\n")
	kadem := kademlia.NewKademlia()
	//------------------------------------
	//	fmt.Println(kadem.NodeID)
	//	myNodeID := kadem.WhoAmI()
	//	fmt.Println(myNodeID)
	//------------------------------------

	//-----initializing MyContact---------
	addr, err := net.ResolveTCPAddr("tcp4", listenStr)
	if err != nil {
		log.Fatal("Call: ", err)
	}
	host1 := addr.IP
	port1 := uint16(addr.Port)
	kadem.MyContact.NodeID = kademlia.WhoAmI(kadem)
	kadem.MyContact.Host = host1
	kadem.MyContact.Port = port1
	//puttin Mycontact in the bucket
	kadem.KademBuckets.Update_Contact(kadem.MyContact, kadem.MyContact)
	//-----registering kadem object and it's functionalities----------
	rpc.Register(kadem)
	rpc.HandleHTTP()
	l, err := net.Listen("tcp", listenStr) //telling the server is ON
	if err != nil {
		log.Fatal("Listen: ", err)
	}
	//---------------------------------------------------------------
	// Serve forever.
	go http.Serve(l, nil)
	//---------------------------------------------------------------
	// Confirm our server is up with a PING request and then exit.
	// Your code should loop forever, reading instructions from stdin and
	// printing their results to stdout. See README.txt for more details.
	client, err := rpc.DialHTTP("tcp", firstPeerStr)
	if err != nil {
		log.Fatal("DialHTTP: ", err)
	}
	addr1, err := net.ResolveTCPAddr("tcp4", firstPeerStr)
	if err != nil {
		log.Fatal("Call: ", err)
	}
	host2 := addr1.IP

	ping := new(kademlia.Ping) //creating a ping object of the ping structure in the kademlia package

	//	net.LookupHost(127.0.0.1)
	//    a, err := net.LookupIP("www.google.com")
	ping.MsgID = kademlia.NewRandomID()
	ping.Sender = kadem.MyContact
	//--------------------------------------------------------------------
	var pong kademlia.Pong //declaring a pong object of the pong structure in the kademlia package, but not initializing it
	//    calling Kademlia.Ping method passing ping as request object and pong as response object
	err = client.Call("Kademlia.Ping", ping, &pong)
	if err != nil {
		log.Fatal("Call: ", err)
	}
	//------------------------------------------------------------------------
	//	log.Printf("ping msgID: %s\n", ping.MsgID.AsString())
	//	log.Printf("pong msgID: %s\n", pong.MsgID.AsString())
	fmt.Println("connecting server NodeID:", pong.Sender.NodeID.AsString())
	//	fmt.Println("connecting server host:",pong.Sender.Host)
	//	fmt.Println("connecting server Port:",pong.Sender.Port)
	pong.Sender.Host = host2
	kadem.KademBuckets.Update_Contact(pong.Sender, kadem.MyContact)

	//--------------------------------------------------------------
	/*	//---taking a string and getting the key for that string---
		a := "my name is rishabh"
		fmt.Println(a)
		h := sha1.New()
		io.WriteString(h,a)

		b:=h.Sum(nil)
		fmt.Println(b)
		c := hex.EncodeToString(b)
		f, err := kademlia.FromString(c)
		if err != nil {
			log.Fatal("Call: ", err)
		}
		fmt.Println(f)
	*/
	//--------------------------------------------------------------
	/*
	   	a := "my name is rishabh"
	   	f :=kademlia.StringToKey(a)
	   //	fmt.Println(f)

	   //--------------------------------------------------------------
	   	sreq := new(kademlia.StoreRequest)
	   	sreq.MsgID = kademlia.NewRandomID()
	   	sreq.Sender = kadem.MyContact
	   	sreq.Key = f
	   	sreq.Value = []byte(a)
	   	var sres kademlia.StoreResult
	   	fmt.Println(".....ii'm here......1")
	   	err = client.Call("Kademlia.Store", sreq, &sres)
	   	if err != nil {
	   		log.Fatal("Call: ", err)
	   	}
	   	fmt.Println(".....ii'm here......2")

	   	//------------------------------------------------------------------------
	   	log.Printf("ping msgID: %s\n", sreq.MsgID.AsString())
	   	log.Printf("pong msgID: %s\n", sres.MsgID.AsString())

	   	fmt.Println(".....ii'm here......3")
	   	err = client.Call("Kademlia.Store", sreq, &sres)
	   	if err != nil {
	   		log.Fatal("Call: ", err)
	   	}
	   	fmt.Println(".....ii'm here......4")

	   	//------------------------------------------------------------------------
	   	log.Printf("ping msgID: %s\n", sreq.MsgID.AsString())
	   	log.Printf("pong msgID: %s\n", sres.MsgID.AsString())

	*/
	/*
	       a1 := new(kademlia.StoreRequest)  //creating a ping object of the
	       b1 := new(kademlia.StoreResult)  //creating a ping object of the
	   	//---------------------------------------------------
	       a2 := new(kademlia.StoreRequest)  //creating a ping object of the
	       b2 := new(kademlia.StoreResult)  //creating a ping object of the
	   	//----------------------------------------------------
	       err = client.Call("Kademlia.Ping", ping, &pong)
	       if err != nil {
	           log.Fatal("Call: ", err)
	       }
	*/

	//---------find value-------------------------

	/*

		fvreq := new(kademlia.FindValueRequest)
		fvreq.MsgID = kademlia.NewRandomID()
		fvreq.Sender = kadem.MyContact
		fvreq.Key = f
		var fvres kademlia.FindValueResult
		fmt.Println(".....ii'm here......1")
		err = client.Call("Kademlia.FindValue", fvreq, &fvres)
		if err != nil {
			log.Fatal("Call: ", err)
		}
		fmt.Println(".....ii'm here......2")


		fmt.Println(string(fvres.Value))

	*/
	//--------------------------------------------------------------------
	//--------------------------------------------------------------------

	r := bufio.NewReader(os.Stdin)
	//	println("enter string:")
	line, err := r.ReadString(delim)
	if err != nil {
		//		fmt.Println(err)
		//		os.Exit(1)
	}
	//	fmt.Println(line)
	token := strings.Fields(line)
	for token[0] != "exit" || token[0] == "" {
		switch token[0] {
		case "whoami":
			//		fmt.Println("this is 1")
			a := kademlia.Whoami(kadem)
			fmt.Println(a)

		case "local_find_value":
			//		fmt.Println("this is 2")
			key, err := kademlia.FromString(token[1])
			//		fmt.Println(id)
			if err == nil {
				kademlia.Local_find_value(kadem, key)
			}
		case "get_contact":
			//		fmt.Println("this is 3")
			id, err := kademlia.FromString(token[1])
			fmt.Println(id)
			var c kademlia.Contact
			if err == nil {
				c = kademlia.Get_contact(kadem, id)
				fmt.Println("Node id: ", c.NodeID)
				fmt.Println("IP Addr: ", c.Host)
				fmt.Println("Port   : ", c.Port)
			}

		case "iterativeStore":
			//		fmt.Println("this is 4")
		case "iterativeFindNode":
			//		fmt.Println("this is 5")
		case "iterativeFindValue":
			//		fmt.Println("this is 6")
		case "ping":
			//		fmt.Println("this is 7")
			id, err := kademlia.FromString(token[1])
			if err == nil {
				ping, pong, s := kademlia.Pingnode(kadem, id)
				client, err := rpc.DialHTTP("tcp", s) //REFPEER
				//			s = s + ":"
				if err != nil {
					log.Fatal("DialHTTP: ", err)
				}
				err = client.Call("Kademlia.Ping", ping, &pong)
				if err != nil {
					log.Fatal("Call: ", err)
				}
				log.Printf("ping msgID: %s\n", ping.MsgID.AsString())
				log.Printf("pong msgID: %s\n", pong.MsgID.AsString())
			}

		case "store":
			//		fmt.Println("this is 8")

			id, err := kademlia.FromString(token[1])
			if err != nil {
			}
			key, err := kademlia.FromString(token[2])
			if err != nil {
			}

			//		val:=token[3]
			val := ""
			for t := 3; t < len(token); t++ {
				val = val + string(token[t]) + " "
			}

			sreq, sres, s := kademlia.Storenode(kadem, id, key, val)
			//			s = s + ":"
			client, err := rpc.DialHTTP("tcp", s) //REFPEER) //s
			if err != nil {
				log.Fatal("DialHTTP: ", err)
			}
			err = client.Call("Kademlia.Store", sreq, &sres)
			if err != nil {
				log.Fatal("Call: ", err)
			}

			//		log.Printf("sreq msgID: %s\n", sreq.MsgID.AsString())
			//		log.Printf("sres msgID: %s\n", sres.MsgID.AsString())

		case "find_node":
			//		fmt.Println("this is 9")
			id, err := kademlia.FromString(token[1])
			if err != nil {
			}
			key, err := kademlia.FromString(token[2])
			if err != nil {
			}
			fnreq, fnres, s := kademlia.Findnode(kadem, id, key)
			//			s = s + ":"
			client, err := rpc.DialHTTP("tcp", s) //REFPEER) //s
			if err != nil {
				log.Fatal("DialHTTP: ", err)
			}
			err = client.Call("Kademlia.FindNode", fnreq, &fnres)
			if err != nil {
				log.Fatal("Call: ", err)
			}
			log.Printf("fnreq msgID: %s\n", fnreq.MsgID.AsString())
			log.Printf("fnres msgID: %s\n", fnres.MsgID.AsString())
			var temp_contact kademlia.Contact
			l := len(fnres.Nodes)
			for j := 0; j < l; j++ {
				if fnres.Nodes[j].NodeID.AsString() != "0" {
					fmt.Println("NodeID : ", fnres.Nodes[j].IPAddr)
					fmt.Println("Port   : ", fnres.Nodes[j].Port)
					fmt.Println("Host   : ", fnres.Nodes[j].NodeID.AsString())

					peer3 := fmt.Sprintf("%s:%d", fnres.Nodes[j].IPAddr, fnres.Nodes[j].Port)
					addr3, err := net.ResolveTCPAddr("tcp4", peer3)
					if err != nil {
						log.Fatal("Call: ", err)
					}

					temp_contact.NodeID = fnres.Nodes[j].NodeID
					temp_contact.Host = addr3.IP //net.IP(fnres.Nodes[j].IPAddr)
					temp_contact.Port = fnres.Nodes[j].Port
					kadem.KademBuckets.Update_Contact(temp_contact, kadem.MyContact)
				}
			} //for

		case "find_value":
			//		fmt.Println("this is 10")
			id, err := kademlia.FromString(token[1])
			if err != nil {
			}
			key, err := kademlia.FromString(token[2])
			if err != nil {
			}
			fvreq, fvres, s := kademlia.Findvalue(kadem, id, key)
			//			s = s + ":"
			client, err := rpc.DialHTTP("tcp", s) //REFPEER) //s
			if err != nil {
				log.Fatal("DialHTTP: ", err)
			}
			err = client.Call("Kademlia.FindValue", fvreq, &fvres)
			if err != nil {
				log.Fatal("Call: ", err)
			}
			//		log.Printf("fvreq msgID: %s\n", fvreq.MsgID.AsString())
			//		log.Printf("fvres msgID: %s\n", fvres.MsgID.AsString())

			fmt.Println(string(fvres.Value))
		case "exit":
			break
		default:
			fmt.Println("enter the correct input")
		} //switch
		line, err := r.ReadString(delim)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		token = strings.Fields(line)
	} //for

} //main
Ejemplo n.º 12
0
func main() {
	// By default, Go seeds its RNG with 1. This would cause every program to
	// generate the same sequence of IDs.
	rand.Seed(time.Now().UnixNano())

	// Get the bind and connect connection strings from command-line arguments.
	flag.Parse()
	args := flag.Args()
	if len(args) != 2 {
		log.Fatal("Must be invoked with exactly two arguments!\n")
	}
	listenStr := args[0]
	firstPeerStr := args[1]

	fmt.Printf("kademlia starting up!\n")
	kadem := kademlia.NewKademlia()
	myIpPort := strings.Split(listenStr, ":")
	if len(myIpPort) != 2 {
		log.Fatal("Invalid format of arg one, expected IP:PORT\n")
	}
	if strings.Contains(myIpPort[0], "localhost") {
		myIpPort[0] = "127.0.0.1"
	}

	ipAndPort := strings.Split(firstPeerStr, ":")
	if len(ipAndPort) != 2 {
		log.Fatal("Invalid format of arg two, expected IP:PORT\n")
	}
	port, err := strconv.Atoi(myIpPort[1])
	if err != nil {
		log.Fatal("Could not parse local port\n")
	}

	rpc.Register(kadem)
	rpc.HandleHTTP()
	l, err := net.Listen("tcp", listenStr)
	if err != nil {
		log.Fatal("Listen: ", err)
	}

	// Serve forever.
	go http.Serve(l, nil)

	me := kademlia.Contact{NodeID: kademlia.CopyID(kadem.NodeID), Host: net.ParseIP(myIpPort[0]), Port: uint16(port)}
	if false == strings.Contains(listenStr, firstPeerStr) {
		err = kadem.Join(me, ipAndPort[0], ipAndPort[1])
		if err != nil {
			log.Fatal("Error joinging network", err)
		}
	}

	fmt.Println("Finished starting up")

	// Confirm our server is up with a PING request and then exit.
	// Your code should loop forever, reading instructions from stdin and
	// printing their results to stdout. See README.txt for more details.
	input := bufio.NewReader(os.Stdin)
	for {
		commandStr, err := input.ReadString('\n')
		commandStr = strings.TrimRight(strings.TrimRight(commandStr, string('\n')), string(' '))
		if err != nil {
			log.Fatal("Reading line:", err)
		}
		command_parts := strings.Split(commandStr, string(' '))
		if len(commandStr) == 0 || len(command_parts) == 0 {
			continue
		}
		command := []byte(strings.ToLower(command_parts[0]))
		switch {
		case bytes.Equal(command, []byte("ping")):
			if len(command_parts) != 2 {
				fmt.Println("Invalid format ping\n\tping nodeID\n\tping host:port")
				continue
			}
			doPing(kadem, me, command_parts[1])
		case bytes.Equal(command, []byte("store")):
			if len(command_parts) != 4 {
				fmt.Println("Invalid format store\n\tstore nodeid key data")
				continue
			}

			id, err := kademlia.FromString(command_parts[1])
			if err != nil {
				fmt.Printf("ERR could not interpret nodeid as ID")
				return
			}
			con, err := kadem.ContactFromID(id)
			if err != nil {
				fmt.Println("ERR : unknown node")
				continue
			}
			remoteAddr := contactToAddrString(con)
			client, err := rpc.DialHTTP("tcp", remoteAddr)
			if err != nil {
				log.Fatal("DialHTTP: ", err)
			}
			req := kademlia.StoreRequest{MsgID: kademlia.NewRandomID(), Sender: me}
			req.Key, err = kademlia.FromString(command_parts[2])
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}

			req.Value = []byte(command_parts[3])
			res := new(kademlia.StoreResult)
			err = client.Call("Kademlia.Store", req, res)
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}
			_ = client.Close()

			fmt.Println("OK")
		case bytes.Equal(command, []byte("find_node")):
			if len(command_parts) != 3 {
				fmt.Println("Invalid format find_node\n\tfind_node nodeid key")
				continue
			}
			id, err := kademlia.FromString(command_parts[1])
			if err != nil {
				fmt.Printf("ERR could not interpret nodeid as ID")
				continue
			}
			con, err := kadem.ContactFromID(id)
			if err != nil {
				fmt.Println("ERR : unknown node")
				continue
			}
			remoteAddr := contactToAddrString(con)

			client, err := rpc.DialHTTP("tcp", remoteAddr)
			if err != nil {
				log.Fatal("DialHTTP: ", err)
			}
			req := kademlia.FindNodeRequest{MsgID: kademlia.NewRandomID()}
			req.NodeID, err = kademlia.FromString(command_parts[2])
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}
			res := new(kademlia.FindNodeResult)
			err = client.Call("Kademlia.FindNode", req, res)
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}

			_ = client.Close()

			fmt.Printf("OK\n")
			for _, node := range res.Nodes {
				fmt.Printf("%s\n", node.NodeID.AsString())
			}

		case bytes.Equal(command, []byte("find_value")):
			if len(command_parts) != 3 {
				fmt.Println("Invalid format find_value\n\tfind_value key")
				continue
			}

			id, err := kademlia.FromString(command_parts[1])
			if err != nil {
				fmt.Printf("ERR could not interpret nodeid as ID")
				return
			}

			con, err := kadem.ContactFromID(id)
			if err != nil {
				fmt.Println("ERR : unknown node")
				continue
			}
			remoteAddr := contactToAddrString(con)

			client, err := rpc.DialHTTP("tcp", remoteAddr)
			if err != nil {
				log.Fatal("ERR: DialHTTP -> ", err)
			}
			req := kademlia.FindValueRequest{MsgID: kademlia.NewRandomID()}
			req.Key, err = kademlia.FromString(command_parts[2])
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}
			res := new(kademlia.FindValueResult)
			err = client.Call("Kademlia.FindValue", req, res)
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}

			_ = client.Close()

			if res.Value != nil {
				fmt.Printf("%s\n", string(res.Value))
			} else {
				for _, node := range res.Nodes {
					fmt.Printf("%s\n", node.NodeID.AsString())
				}
			}

		case bytes.Equal(command, []byte("whoami")):
			if len(command_parts) != 1 {
				fmt.Println("Invalid format get_node_id\n\twhoami")
				continue
			}
			fmt.Printf("%s\n", kadem.NodeID.AsString())
		case bytes.Equal(command, []byte("local_find_value")):
			if len(command_parts) != 2 {
				fmt.Println("Invalid format get_local_value\n\tlocal_find_value key")
				continue
			}
			key, err := kademlia.FromString(command_parts[1])
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}
			var val kademlia.TimeValue
			val, ok := kadem.StoredData[key]
			if ok {
				fmt.Printf("OK: %s\n", string(val.Data))
			} else {
				fmt.Printf("ERR no data for key\n")
			}
		case bytes.Equal(command, []byte("get_contact")):
			if len(command_parts) != 2 {
				fmt.Println("Invalid format get_contact\n\tget_contact nodeid")
				continue
			}
			key, err := kademlia.FromString(command_parts[1])

			con, err := kadem.ContactFromID(key)
			if err != nil {
				fmt.Println("ERR")
			} else {
				fmt.Printf("%s %d\n", con.Host.String(), con.Port)
			}
		case bytes.Equal(command, []byte("iterativeStore")):
			if len(command_parts) != 3 {
				fmt.Println("Invalid format iterativeStore")
				continue
			}
			req := kademlia.StoreRequest{MsgID: kademlia.NewRandomID(), Sender: me}
			req.Key, err = kademlia.FromString(command_parts[1])
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}

			req.Value = []byte(command_parts[2])
			res := new(kademlia.StoreResult)
			lastNode := kadem.IterStore(req, res)
			if len(lastNode.NodeID) != 0 {
				fmt.Printf("%s", lastNode.NodeID.AsString())
			} else {
				fmt.Println("Could not find a neighbor")
			}
		case bytes.Equal(command, []byte("iterativefindnode")):
			if len(command_parts) != 2 {
				fmt.Println("Invalid format iterativeFindNode")
				continue
			}
			req := kademlia.FindNodeRequest{MsgID: kademlia.NewRandomID(), Sender: me}
			req.NodeID, err = kademlia.FromString(command_parts[1])
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}
			res := new(kademlia.FindNodeResult)
			err := kadem.IterFindNode(req, res)
			if err != nil {
				fmt.Printf("ERR: %v", err)
			} else {
				for _, node := range res.Nodes {
					fmt.Printf("%s", node.NodeID.AsString())
				}
			}
		case bytes.Equal(command, []byte("iterativefindvalue")):
			if len(command_parts) != 2 {
				fmt.Println("Invalid format iterativeFindValue")
				continue
			}
			req := kademlia.FindValueRequest{MsgID: kademlia.NewRandomID(), Sender: me}
			req.Key, err = kademlia.FromString(command_parts[1])
			if err != nil {
				fmt.Printf("ERR: %v\n", err)
				continue
			}
			res := new(kademlia.FindValueResult)
			err := kadem.IterFindValue(req, res)
			if err != nil {
				fmt.Printf("ERR: %v", err)
			} else {
				if res.Value != nil {
					fmt.Printf("%s %s\n", res.Nodes[0].NodeID.AsString(), string(res.Value))
				} else {
					fmt.Println("ERR")
				}
			}
		default:
			fmt.Printf("Unknown command: %s\n", command_parts[0])
		}
	}
}
Ejemplo n.º 13
0
func NewDryMartiniInstruction(s string) (dmInst *DryMartiniInstruction) {
	var err error
	var strTokens []string

	dmInst = new(DryMartiniInstruction)

	//remove the newline character
	s = strings.TrimRight(s, "\n")

	//split string, separator is the white-space
	strTokens = strings.Split(s, " ")

	//log.Printf("Parsing command: %s\n", strTokens)

	dmInst.flags = 255 //255 means skip cause nothing could be matched, check with IsSkip()
	dmInst.CmdStr = s  //store the whole string somewhere so we can print for debugging

	switch strings.ToLower(strTokens[0]) {
	case drymartini.EXIT_CMD_STR:
		dmInst.flags = 1
	case drymartini.PING_CMD_STR:
		//kademlia.Assert(len(strTokens) == 2, "Ping requires 1 argument")//ping host:port
		if (len(strTokens) != 2) || !(strings.Contains(strTokens[1], ":")) {
			return dmInst
		}

		dmInst.flags = 2
		dmInst.Addr = strTokens[1]
	case drymartini.JOIN_CMD_STR:
		if (len(strTokens) != 2) || !(strings.Contains(strTokens[1], ":")) {
			return dmInst
		}
		dmInst.flags = 3
		dmInst.Addr = strTokens[1]
	case drymartini.WHOAMI_CMD_STR:
		//kademlia.Assert(len(strTokens) == 1, "GetNodeId requires 0 argument")//whoami
		if len(strTokens) != 1 {
			return dmInst
		}
		dmInst.flags = 4
	case drymartini.PLB_CMD_STR:
		//kademlia.Assert(len(strTokens) == 1, "printLocalBuckets requires 0 arguments")//plb
		if len(strTokens) != 1 {
			return dmInst
		}
		dmInst.flags = 5
	case drymartini.PLD_CMD_STR: //kademlia.Assert(len(strTokens) == 1, "printLocalData requires 0 arguments")//pld
		if len(strTokens) != 1 {
			return dmInst
		}
		dmInst.flags = 6
	case drymartini.GENPATH_CMD_STR:
		if len(strTokens) != 3 {
			return dmInst
		}
		dmInst.flags = 7
		dmInst.minNodes, err = strconv.Atoi(strTokens[1])
		dmInst.maxNodes, err = strconv.Atoi(strTokens[2])
		if err != nil {
			log.Printf("error parsing strings to int: %s\n", err)
		}
	case drymartini.BC_CMD_STR:
		if len(strTokens) != 4 {
			return dmInst
		}
		dmInst.flags = 8
		dmInst.request = strTokens[1]
		dmInst.minNodes, err = strconv.Atoi(strTokens[2])
		dmInst.maxNodes, err = strconv.Atoi(strTokens[3])
		if err != nil {
			log.Printf("error parsing strings to int: %s\n", err)
		}
	case drymartini.FV_CMD_STR:
		if len(strTokens) != 2 {
			return dmInst
		}
		dmInst.flags = 9
		dmInst.Key, err = kademlia.FromString(strTokens[1])
	case drymartini.PLF_CMD_STR:
		//kademlia.Assert(len(strTokens) == 1, "printLocalData requires 0 arguments")//pld
		if len(strTokens) != 1 {
			return dmInst
		}
		dmInst.flags = 10
	case drymartini.SEND_CMD_STR:
		//kademlia.Assert(len(strTokens) == 3, "send requires 2 arguments")//pld
		if len(strTokens) != 3 {
			return dmInst
		}
		dmInst.flags = 11
		dmInst.FlowIndex, err = strconv.Atoi(strTokens[1])
		dmInst.request = strTokens[2]
	case drymartini.MAKEWARMSWARM_CMD_STR:
		if len(strTokens) != 3 {
			return dmInst
		}
		dmInst.minNodes, err = strconv.Atoi(strTokens[1])
		dmInst.maxNodes, err = strconv.Atoi(strTokens[2])
		if err != nil {
			log.Printf("error parsing num nodes:%s\n", err)
			return dmInst
		}
		dmInst.flags = 12
	case drymartini.RUNTESTS_CMD_STR:
		if len(strTokens) == 2 { //args: runtests [num nodes in swarm] [portrange start] [optional: seed for random generation]
		}
		if len(strTokens) != 3 {
			return dmInst
		}
		dmInst.minNodes, err = strconv.Atoi(strTokens[1]) //store number of test nodes here
		dmInst.maxNodes, err = strconv.Atoi(strTokens[2]) //store start of portrange nodes will listen on
		dmInst.flags = 13
	case drymartini.SLEEP_CMD_STR:
		if len(strTokens) != 2 { //args: 1 arg, number of seconds to sleep
			return dmInst
		}
		dmInst.minNodes, err = strconv.Atoi(strTokens[1])
		if err != nil {
			log.Printf("error parsing sleep time:%s\n", err)
			return dmInst
		}
		dmInst.flags = 14
	case drymartini.BLOCK_CMD_STR:
		if len(strTokens) != 1 {
			return dmInst
		}
		dmInst.flags = 15
	case drymartini.OPEN_CMD_STR:
		if len(strTokens) != 1 {
			return dmInst
		}
		dmInst.flags = 16
	case drymartini.GETPATH_AND_SEND_CMD_STR:
		if len(strTokens) != 3 {
			return dmInst
		}
		dmInst.minNodes, err = strconv.Atoi(strTokens[2])
		if err != nil {
			log.Printf("Error: main. failure parsing pathlength string for %s\n", Verbose, drymartini.GETPATH_AND_SEND_CMD_STR)
		}
		dmInst.maxNodes = dmInst.minNodes
		dmInst.request = strTokens[1]
		dmInst.flags = 17
	}

	if err != nil {
		//?
	}

	return dmInst
}