Skip to content
Snippets Groups Projects
Commit 88a8661e authored by julian.ruhl's avatar julian.ruhl
Browse files

Client peut envoyer messages

parent 4edeb9aa
Branches
No related tags found
No related merge requests found
id: 1
address: "127.0.0.1"
neighbours:
- id: 2
address: "127.0.0.2"
- id: 4
address: "127.0.0.4"
\ No newline at end of file
id: 2
address: "127.0.0.2"
neighbours:
- id: 1
address: "127.0.0.1"
- id: 3
address: "127.0.0.3"
id: 3
address: "127.0.0.3"
neighbours:
- id: 4
address: "127.0.0.4"
- id: 5
address: "127.0.0.5"
- id: 6
address: "127.0.0.6"
id: 4
address: "127.0.0.4"
neighbours:
- id: 1
address: "127.0.0.1"
- id: 5
address: "127.0.0.5"
- id: 6
address: "127.0.0.6"
id: 5
address: "127.0.0.5"
neighbours:
- id: 6
address: "127.0.0.6"
- id: 3
address: "127.0.0.3"
- id: 4
address: "127.0.0.4"
id: 6
address: "127.0.0.6"
neighbours:
- id: 3
address: "127.0.0.3"
- id: 4
address: "127.0.0.4"
- id: 5
address: "127.0.0.5"
package main
import (
"bufio"
"encoding/gob"
"fmt"
"net"
"os"
)
......@@ -20,8 +21,40 @@ func createMessage(id int, key int, _type string) Message {
}
}
func sendMessage(address string, port string, msg Message) {
conn, err := net.Dial("tcp", address+":"+port)
if err != nil {
fmt.Println("Error connecting:", err.Error())
os.Exit(1)
}
encoder := gob.NewEncoder(conn)
encoder.Encode(msg)
rcv := make([]byte, 2048)
n, _ := conn.Read(rcv)
fmt.Println(string(rcv[:n]))
conn.Close()
}
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Quel fichiez recherhez vous ? (ID)")
input, _ := reader.ReadString('\n')
//reader := bufio.NewReader(os.Stdin)
var id = 0
for {
fmt.Println("Quel fichiez recherchez vous ? (ID)")
/* input, _ := reader.ReadString('\n')
key, err := strconv.Atoi(input)
if err != nil {
// handle error
fmt.Println(err)
os.Exit(2)
} */
msg := createMessage(id, 19, "REQUEST")
sendMessage("127.0.0.1", "9000", msg)
fmt.Println(msg)
/* if input == "q" {
os.Exit(0)
} */
}
}
import exoscale
from pexpect import pxssh
from time import sleep
import re
EXOSCALE_API_KEY = 'EXO7945e92f25a038a400b488aa'
EXOSCALE_API_SECRET = 'smRDVh7H0QO3w9068WlSq_JqBuPPdR7uaps6bSkLEWw'
# Initialise exoscale API
exo = exoscale.Exoscale(api_key=EXOSCALE_API_KEY, api_secret=EXOSCALE_API_SECRET)
zone_decix = exo.compute.get_zone("de-fra-1")
security_group_default_ssh = exo.compute.get_security_group(name='default')
###
# Create instances
###
nodes = []
for i in range(6):
new_instance = exo.compute.create_instance(
name="freenet-1"
zone=zone_decix,
type=exo.compute.get_instance_type("tiny"),
template=list(exo.compute.list_instance_templates(
zone_decix,
"Linux Ubuntu 18.04 LTS 64-bit"))[0],
volume_size=10,
security_groups=[security_group_default_ssh],
ssh_key=exo.compute.get_ssh_key("SWARM-cluster-key"),
user_data=
"""#cloud-config
package_upgrade: true
packages:
- golang
- git
runcmd:
- cd /home/ubuntu/
- git clone ssh://git@ssh.hesge.ch:10572/jeremy.martinot/tp2_freenet_go_socket.git
"""
)
nodes.append(new_instance)
print("SWARM master hosted at {}".format(swarm_master.ipv4_address))
print("SWARM http hosted at {}".format(swarm_http_slave.ipv4_address))
print("Swarm slave at {}".format(swarm_slave.ipv4_address))
print("Waiting 60 seconds for cloud-init completion...");
sleep(60)
print("Setting up docker SWARM...")
try:
s = pxssh.pxssh(options={"StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null"})
s.login(swarm_master.ipv4_address, username='ubuntu', ssh_key='swarm_key')
s.sendline('docker swarm init')
s.prompt()
haystack = s.before.decode('utf-8', 'ignore')
join_cmd = re.findall('docker swarm join --token.*$', haystack, re.MULTILINE)[0].strip()
s.logout()
s = pxssh.pxssh(options={"StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null"})
s.login(swarm_slave.ipv4_address, username='ubuntu', ssh_key='swarm_key')
s.sendline(join_cmd)
s.prompt()
s.logout()
s = pxssh.pxssh(options={"StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null"})
s.login(swarm_http_slave.ipv4_address, username='ubuntu', ssh_key='swarm_key')
s.sendline(join_cmd)
s.prompt()
s.logout()
print("Swarm created on all nodes.")
except pxssh.ExceptionPxssh as e:
print("pxssh failed on login.")
print(e)
[tool.poetry]
name = "tp2_freenet_go_socket"
version = "0.1.0"
description = ""
authors = ["Julian Rühl <julian.ruhl@etu.hesge.ch>"]
[tool.poetry.dependencies]
python = "^3.8"
exoscale = "^0.7.1"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
package main
import (
"fmt"
"io/ioutil"
"net"
"os"
"gopkg.in/yaml.v3"
)
type contenu struct {
hash [20]byte //sha1 hash
file string //nom du fichier
node [4]byte //addresse IP
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
func main() {
if len(os.Args) != 3 {
fmt.Fprintf(os.Stderr, "Utilisation: %s port config.yaml\n", os.Args[0])
os.Exit(1)
}
yfile, err := ioutil.ReadFile(os.Args[2])
checkError(err)
data := make(map[interface{}]interface{})
err = yaml.Unmarshal(yfile, &data)
checkError(err)
service := "127.0.0.1"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
conn, err := net.DialTCP("tcp", nil, tcpAddr)
checkError(err)
_, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
checkError(err)
//result, err := readFully(conn)
result, err := ioutil.ReadAll(conn)
checkError(err)
fmt.Println(string(result))
os.Exit(0)
}
# TP2_Freenet_Go_Socket
Our amazing project !
\ No newline at end of file
package main
import (
"bufio"
"encoding/gob"
"fmt"
"io/ioutil"
"math/rand"
"net"
"os"
"time"
"gopkg.in/yaml.v3"
)
......@@ -23,10 +25,41 @@ type Node struct {
}
type Contenu struct {
File string //identifiant du fichier
Key int //key
Origin string //addresse IP
}
var (
thisnode Node
port string
contents []Contenu
requests []Message
)
func createMessage(id int, key int, _type string) Message {
return Message{
Id: id,
Key: key,
Type_: _type,
}
}
func createContenu(key int, origin string) {
return Contenu{
Key: key,
Origin: origin,
}
}
func fillContents() {
rands := [10]int
rand.Seed(time.Now().UnixNano())
for i:=0; i<len(rands); i++ {
rands[i] = rand.Intn(100)
contents = append(contents, createContenu(v[i],node.Address))
}
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
......@@ -50,12 +83,73 @@ func readYaml(filename string) Node {
return nodeFromYaml
}
func handleConn(conn net.Conn) {
func sendMessage(msg Message, dst Node) {
conn, err := net.Dial("tcp", dst.Address+":"+port)
checkError(err)
defer conn.Close()
encoder := gob.NewEncoder(conn)
encoder.Encode(msg)
}
func sendMessageAllExcept(msg Message, unsent Node) {
for _, node := range thisnode.Neighbours {
if node.Address != unsent.Address {
go sendMessage(msg, node)
}
}
}
func handleNewConn(conn net.Conn) {
defer conn.Close()
fmt.Printf("Connexion établi avec %s...\n", conn.RemoteAddr().String())
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Println(message)
dec := gob.NewDecoder(conn)
msg := &Message{}
dec.Decode(msg)
fmt.Printf("Received : %+v", msg)
if msg.Type_ == "REQUEST" {
handleRequest(msg, conn)
} else if msg.Type_ == "POSITIVE" {
handlePositiveMessage(msg, conn)
} else {
handleNegativeMessage(msg, conn)
}
}
func handlePositiveMessage(msg Message, conn net.Conn) {
//transmettre message au noeud qui a démandé SAUF si nous étions le demandeur
}
func handleRequest(msg Message, conn net.Conn) {
requests = append(requests, msg)
if hasKey(msg.Key) {
sendMessage(createMessage(thisnode.Id, msg.Key, "POSITIVE"))
} else {
//demander aux autres noeuds
}
}
func hasKey(key int) bool {
for _, element := range content {
if key == element.Key {
key_found = true
}
}
}
func hasAlreadyRequested(newreq Message) bool {
for _, request := range requests {
if request.Id == newreq.Id && request.Key == newreq.Key {
return true
}
}
return false
}
func main() {
......@@ -64,12 +158,17 @@ func main() {
os.Exit(0)
}
node := readYaml(os.Args[2])
thisnode := readYaml(os.Args[2])
port := os.Args[1]
fillContents()
fmt.Println("Starting server on " + thisnode.Address + ":" + port)
fmt.Println("Starting server on " + node.Address + ":" + port)
if os.Args[3] == "INIT" {
listenSocket, err := net.Listen("tcp", node.Address+":"+port)
}
listenSocket, err := net.Listen("tcp", thisnode.Address+":"+port)
checkError(err)
defer listenSocket.Close()
......@@ -79,7 +178,8 @@ func main() {
connection, err := listenSocket.Accept()
checkError(err)
go handleConn(connection)
handleNewConn(connection)
}
os.Exit(0)
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment