server.py 6.78 KB
Newer Older
Ismail Moumni's avatar
Ismail Moumni committed
1
# authors: Julien DAVID & Ismail MOUMNI
Ismail-Moumni's avatar
Ismail-Moumni committed
2
import socket
Ismail Moumni's avatar
Ismail Moumni committed
3
import json
4
import datetime
Ismail Moumni's avatar
Ismail Moumni committed
5
import os
Ismail Moumni's avatar
Ismail Moumni committed
6
import sys
Ismail Moumni's avatar
Ismail Moumni committed
7
sys.path.append(os.path.realpath('../softwares/'))
Ismail Moumni's avatar
Ismail Moumni committed
8
import database as db  # noqa E402
Ismail Moumni's avatar
Ismail Moumni committed
9

10
__RDOS_Dict__ = {"parameters": "request"}
Ismail Moumni's avatar
Ismail Moumni committed
11
12

# tools List
13
# __RDOS_Tool__ = db.list_generators()
Ismail Moumni's avatar
Ismail Moumni committed
14

Ismail Moumni's avatar
Ismail Moumni committed
15

Ismail Moumni's avatar
Ismail Moumni committed
16
17
18
19
20
class RdosServer:

    # Function server_conn creates a socket and listens on port 9393
    # Function input address : SERVER IP ADRESS & Port server Port
    # Function output query send from client to server
Ismail Moumni's avatar
Ismail Moumni committed
21
22
23
24
25
    def server_conn(address, PORT):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
            serv.bind((address, PORT))
            # Listening to 5 CLients
            serv.listen(5)
26
27
28
29
30
31
32
33
34
            while 1:
                # accepting the connection from client and getting client IP
                conn, addr = serv.accept()
                if conn:
                    print('Connexion acceptee depuis l IP : ', addr)
                    # Receiving Data from Client
                    data = conn.recv(4096)
                    query = (json.loads(data.decode('utf-8')))
                    print("Requete reçu : ", query)
35
                    if (query is not None):
36
37
38
39
40
41
42
43
44
45
                        # Sending GENERATORS
                        print(query)
                        if (match_query_dict(query, __RDOS_Dict__)):
                            response = db.get_generators()
                            conn.send(bytes(json.dumps(response), "utf-8"))
                            print("database generators ", response)
                            conn.close()
                        # Inserting client query in DATABASE
                        else:
                            print("check", check_and_complete_parameters(query))
46
47
48
49
50
51
                            res = db_server_insert(conn, query_client(addr, check_and_complete_parameters(query)))
                            # print("query : " , query)
                            if (res == 1):
                                conn.send(bytes(res, "utf-8"))
                            else:
                                conn.send(bytes("query not inserted !!", "utf-8"))
52
53
54
55
                            conn.close()


def query_client(addr, data):
Ismail Moumni's avatar
Ismail Moumni committed
56
    __RDOS_Tool__ = db.li_gen()
57
58
59
60
61
62
63
64
65
66
    sa = __RDOS_Tool__.get(list(data.keys())[0])
    lm = list((data.values()))
    s = {"id": "", "idGenerator": "", "IP": "", "timeSubmitted": "", "timeExecuted": "", "timeFinished": "", "status": "", "parametersJSON": "", "directory": "", "url": "", "message": "", "email": ""}
    s["id"] = str(os.getuid())
    s["idGenerator"] = str(sa)
    s["IP"] = str(addr[0])
    s["timeSubmitted"] = (str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
    s["parametersJSON"] = json.dumps(lm[0])
    print(s)
    return s
Ismail Moumni's avatar
Ismail Moumni committed
67
68


Ismail Moumni's avatar
Ismail Moumni committed
69
# Function query_valwid matches the query send from client side
Ismail Moumni's avatar
Ismail Moumni committed
70
#  with the the parameter dict
Ismail Moumni's avatar
Ismail Moumni committed
71
# Function input dictionary from client
Ismail Moumni's avatar
Ismail Moumni committed
72
73
# Function output boolean true if match else False
def query_valid(data: dict):
74
75
    if data != {}:
        print("heyhey", data)
Ismail Moumni's avatar
Ismail Moumni committed
76
        print(data["parameters"])
77
78
79
80
        if (data["parameters"] == 'response'):
            return True
        else:
            return False
Ismail Moumni's avatar
Ismail Moumni committed
81
82
    else:
        raise Exception("Dictionnaire Vide!!")
Ismail Moumni's avatar
Ismail Moumni committed
83
84
85


# Function json_loads changes a json file into a Dict
Ismail Moumni's avatar
Ismail Moumni committed
86
# Function json_loads returns a dictionary
Ismail Moumni's avatar
Ismail Moumni committed
87
def json_to_dict(js):
Ismail Moumni's avatar
Ismail Moumni committed
88
89
90
91
92
    if js is not None:
        data = json.loads(js)
        return data
    else:
        raise Exception("Dictionnaire Vide!!")
Ismail Moumni's avatar
Ismail Moumni committed
93
94


Ismail Moumni's avatar
Ismail Moumni committed
95
# Function db_req sends a request to get parameters of tools from database
Ismail Moumni's avatar
Ismail Moumni committed
96
# Function takes a dictionary for input
Ismail Moumni's avatar
Ismail Moumni committed
97
98
# Function return a Dict containing tool parameters and default parameters
def db_req(tool: dict):
Ismail Moumni's avatar
Ismail Moumni committed
99
100
101
102
103
    if dict is not None:
        tool_dict = db.getParameters(tool)
        return tool_dict
    else:
        raise Exception("Dictionnaire Vide!!")
Ismail Moumni's avatar
Ismail Moumni committed
104
105


Ismail Moumni's avatar
Ismail Moumni committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# Function match_dict returns non existing fields in a dict
# Function input biblio and dict
# Function returns a list containing missing values
def missing_keys(biblio: dict, gen: dict):
    missing = []
    if(biblio is not None and gen is not None):
        for key in biblio:
            if key not in gen:
                missing.append(key)
        return missing
    else:
        raise Exception("Dictionnaire Vide!!")


Ismail Moumni's avatar
Ismail Moumni committed
120
121
122
# Function match_query_dict matches two dictionaries
# Function input takes 2 dictionaries to match
# Function output return trur if dictionaries matches else raise a value error exception
Ismail Moumni's avatar
Ismail Moumni committed
123
124
125
126
def match_query_dict(biblio: dict, data: dict):
    if biblio is not None and data is not None:
        return biblio.keys() == data.keys()
    else:
Ismail Moumni's avatar
Ismail Moumni committed
127
        raise ValueError("Error Dict Values ")
Ismail Moumni's avatar
Ismail Moumni committed
128
129


Ismail Moumni's avatar
Ismail Moumni committed
130
# Function check_and_complete_parameters verifies json send from client to server by matching it with database query
Ismail Moumni's avatar
Ismail Moumni committed
131
132
# Function input takes a dictionary
# Function output returns query if it matches with database query keys if not it raises an error
133
def check_and_complete_parameters(data):
Ismail Moumni's avatar
Ismail Moumni committed
134
    if data is not None:
135
136
        tool = list(data.keys())[0]
        s = db.getParameters({tool})
Ismail Moumni's avatar
Ismail Moumni committed
137
138
139
140
        parameter = {}
        query = {}
        if s is not None:
            gen = s[0]
141
142
143
144
145
            parameter = s[1]
            q = data.get(tool)
            if match_query_dict(parameter.get(tool), q):
                check_and_replace(data.get(tool), parameter.get(tool))
                return data
Ismail Moumni's avatar
Ismail Moumni committed
146
147
            else:
                raise Exception("Query Doesn't match")
Ismail Moumni's avatar
Ismail Moumni committed
148
        else:
Ismail Moumni's avatar
Ismail Moumni committed
149
            raise Exception("Error Database")
Ismail Moumni's avatar
Ismail Moumni committed
150
    else:
Ismail Moumni's avatar
Ismail Moumni committed
151
        raise Exception("Dictionnaire Vide!!")
Ismail Moumni's avatar
Ismail Moumni committed
152
153


154
155
156
157
158
159
160
161
162
163
164
# Function check_and_replace checks query with that and replaces the empty values
# Function input takes 2 dictionaries
# Function output returns matched query
def check_and_replace(query, data):
    if query is not None and data is not None:
        for a, b in query.items():
            if b == '':
                query[a] = data.get(a)
    return query


Ismail Moumni's avatar
Ismail Moumni committed
165
166
167
168
# Function db_generators returns database generators
# Function takes a dictionary request from client side
# Function returns all database generators or raises an error if request doesn't match
def db_generators(req: dict):
Ismail Moumni's avatar
Ismail Moumni committed
169
170
171
172
173
174
    if req is not None:
        match = {"request": "generators"}
        if(req == match):
            s = db.get_generators()
            return s
        else:
Ismail Moumni's avatar
Ismail Moumni committed
175
            raise Exception("Dictionnaire non Valid")
Ismail Moumni's avatar
Ismail Moumni committed
176
    else:
Ismail Moumni's avatar
Ismail Moumni committed
177
        raise Exception("Dictionnaire Vide!!")
Ismail Moumni's avatar
Ismail Moumni committed
178
179
180
181
182


# Function db_insert send a query to insert in database by socket
# Function db_insert takes a socket and dictionary for input
# Function db_insert returns a string if query send
183
def db_server_insert(s: socket, req: dict):
Ismail Moumni's avatar
Ismail Moumni committed
184
    if(req is not None):
185
        ins = db.db_insert(req)
Ismail Moumni's avatar
Ismail Moumni committed
186
187
188
189
        s.send(bytes(json.dumps(ins), "utf-8"))
        print("Query send")
    else:
        raise Exception("Invalid Query")
Ismail Moumni's avatar
Ismail Moumni committed
190
191
192
193
194


if __name__ == '__main__':
    # TEST FOR Docker
    RdosServer.server_conn('127.0.0.1', '9393')