-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremote_table.c
More file actions
executable file
·403 lines (337 loc) · 10.2 KB
/
remote_table.c
File metadata and controls
executable file
·403 lines (337 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/*
* File: remote_table.c
*
* Este ficheiro concretiza uma função por cada comando do cliente, além de
* funções para conectar e desconectar a um servidor.
* Cada função vai preencher uma estrutura message_t com o opcode (tipo da
* operação) e os campos usados de acordo com o conteúdo requerido pela mensagem
* e vai passar esta estrutura para o módulo de comunicação, recebendo uma
* resposta deste.
*
* Author: sd001 > Bruno Neves, n.º 31614
* > Vasco Orey, n.º 32550
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "data.h"
#include "entry.h"
#include "message.h"
#include "message-private.h"
#include "remote_table.h"
#include "remote_table-private.h"
#include "network_client.h"
#include "network_client-private.h"
#include "table.h"
/*
* Função para estabelecer uma associação com uma tabela num servidor.
* address_port é uma string no formato <hostname>:<port>.
* Retorna NULL em caso de erro.
*/
struct rtable_t *rtable_open(const char *address_port) {
//verifica se address_port aponta para NULL
if(address_port == NULL) {
ERROR("remote_table: NULL address_port");
return NULL;
}
char *host; //IP ou nome da máquina
char *port; //porto
char *endereco; //uma cópia do endereço
struct rtable_t * remoteTable; //a tabela remota
//copia o endereço para uma variável temporária
if((endereco = strdup(address_port)) == NULL) {
ERROR("remote_table: strdup address_port");
return NULL;
}
//guarda o endereço da máquina
if((host = strdup((char *) strtok(endereco, ":"))) == NULL) {
ERROR("remote_table: strdup host");
free(endereco);
return NULL;
}
//guarda o porto da máquina
char *tempString;
if((tempString = strtok(NULL, ":")) == NULL) {
ERROR("remote_table: strtok port");
return NULL;
}
if((port = strdup(tempString)) == NULL) {
ERROR("remote_table: strdup port");
free(host);
free(endereco);
return NULL;
}
//aloca memória para a tabela remota
if((remoteTable = (struct rtable_t *) malloc(sizeof(struct rtable_t))) == NULL) {
ERROR("remote_table: malloc remoteTable");
free(host);
free(port);
free(endereco);
return NULL;
}
//guarda o ip e o porto
remoteTable->ip = host;
remoteTable->porto = port;
free(endereco);
//em caso de sucesso
return remoteTable;
}
int rtable_connect(struct rtable_t *table) {
return network_connect(table);
}
/*
* Fecha a ligação com o servidor, desaloca toda a memória local.
* Retorna 0 se tudo correr bem e -1 em caso de erro.
*/
int rtable_disconnect(struct rtable_t *table) {
//verifica se table aponta para NULL
if(table == NULL) {
ERROR("remote_table: rtable_disconnect: NULL table");
return -1;
}
//verifica se a ligação é fechada sem erros
if((network_close(table)) == -1) {
ERROR("remote_table: network_close");
return -1;
}
free(table->ip);
free(table->porto);
free(table);
//em caso de sucesso
return 0;
}
/*
* Função para adicionar um elemento na tabela.
* Se key ja existe, vai substituir essa entrada pelos novos dados.
* Devolve 0 (ok) ou -1 (out of memory).
*/
int rtable_put(struct rtable_t *table, struct entry_t *entry) {
//verifica se table, key ou data apontam para NULL
if(table == NULL || entry == NULL) {
ERROR("remote_table: NULL table or key or data");
return -1;
}
//preenche os campos da mensagem
struct message_t msg;
msg.opcode = OP_RT_PUT;
msg.c_type = CT_ENTRY;
msg.content.entry = entry;
//envia a mensagem e recebe a resposta
struct message_t *rsp;
if((rsp = network_send_receive(table, &msg)) == NULL) {
ERROR("remote_table: network_send_receive");
entry_destroy(entry);
return -1;
}
//verifica se a resposta é válida
if(rsp->opcode != (OP_RT_PUT + 1)) {
ERROR("remote_table: invalid message");
entry_destroy(entry);
free_message(rsp);
return -1;
}
//em caso de sucesso
free_message(rsp);
entry_destroy(entry);
return 0;
}
/*
* Função para obter um elemento da tabela.
* Em caso de erro, devolve NULL.
*/
struct data_t *rtable_get(struct rtable_t *table, char *key) {
//verifica se table ou key apontam para NULL
if(table == NULL || key == NULL) {
ERROR("remote_table: NULL table or key");
return NULL;
}
//preenche os campos da mensagem
struct message_t msg;
msg.opcode = OP_RT_GET;
msg.c_type = CT_KEY;
msg.content.key = key;
//envia a mensagem e recebe a resposta
struct message_t *rsp;
if((rsp = network_send_receive(table, &msg)) == NULL) {
ERROR("remote_table: network_send_receive");
return NULL;
}
//verifica se a resposta é válida
if(rsp->opcode != (OP_RT_GET + 1)) {
if(rsp->opcode == OP_RT_ERROR && rsp->content.result != 0) {
ERROR("remote_table: invalid message");
}
free_message(rsp);
return NULL;
}
//duplica a data recebida na resposta
struct data_t *data = NULL;
if(rsp->content.value && (data = data_dup(rsp->content.value)) == NULL) {
ERROR("remote_table: data_dup");
free_message(rsp);
return NULL;
}
//printf("Criei um data de tamanho: %d\n", data->datasize);
//em caso de sucesso
free_message(rsp);
return data;
}
/*
* Função para remover um elemento da tabela. Vai desalocar
* toda a memória alocada na respectiva operação rtable_put()
* Devolve: 0 (ok), -1 (key not found).
*/
int rtable_del(struct rtable_t *table, char *key) {
int retVal = 0;
//verifica se table ou key apontam para NULL
if(table == NULL || key == NULL) {
ERROR("remote_table: NULL table or key");
return -1;
}
//preenche os campos da mensagem
struct message_t msg;
msg.opcode = OP_RT_DEL;
msg.c_type = CT_KEY;
msg.content.key = key;
//envia a mensagem e recebe a resposta
struct message_t *rsp;
if((rsp = network_send_receive(table, &msg)) == NULL) {
ERROR("remote_table: network_send_receive");
return -1;
}
//verifica se a resposta é válida
if(rsp->opcode != (OP_RT_DEL + 1)) {
ERROR("remote_table: invalid message");
free_message(rsp);
return -1;
}
//em caso de sucesso
retVal = rsp->content.result;
free_message(rsp);
return retVal;
}
/*
* Devolve o número de elementos da tabela.
*/
int rtable_size(struct rtable_t *table) {
//verifica se table aponta para NULL
if(table == NULL) {
ERROR("remote_table: NULL table");
return -1;
}
//preenche os campos da mensagem
struct message_t msg;
msg.opcode = OP_RT_SIZE;
msg.c_type = CT_RESULT;
msg.content.result = 0;
//envia a mensagem e recebe a resposta
struct message_t *rsp;
if((rsp = network_send_receive(table, &msg)) == NULL) {
ERROR("remote_table: network_send_receive");
return -1;
}
//verifica se a resposta é válida
if(rsp->opcode != (OP_RT_SIZE + 1)) {
ERROR("remote_table: invalid message");
free_message(rsp);
return -1;
}
//em caso de sucesso
int size = rsp->content.result;
free_message(rsp);
return size;
}
/*
* Devolve um array de char* com a cópia de todas as keys da tabela,
* e um último elemento NULL.
*/
char **rtable_get_keys(struct rtable_t *table) {
//verifica se table aponta para NULL
if(table == NULL) {
ERROR("remote_table: NULL table");
return NULL;
}
//preenche os campos da mensagem
struct message_t msg;
msg.opcode = OP_RT_GETKEYS;
msg.c_type = CT_RESULT;
msg.content.result = 0;
//envia a mensagem e recebe a resposta
struct message_t *rsp;
if((rsp = network_send_receive(table, &msg)) == NULL) {
ERROR("remote_table: network_send_receive");
return NULL;
}
//verifica se a resposta é válida
if(rsp->opcode != (OP_RT_GETKEYS + 1)) {
ERROR("remote_table: invalid message");
free_message(rsp);
return NULL;
}
//determina o tamanho da lista de chaves
int i = 0;
int nKeys = 0;
while (rsp->content.keys[i] != NULL) {
nKeys++;
i++;
}
nKeys ++; //para colocar na última posição NULL
//aloca memória para o novo vector de keys
char **keys;
if((keys = (char **) malloc(sizeof(char *) * nKeys)) == NULL) {
ERROR("remote_table: malloc keys");
free_message(rsp);
return NULL;
}
//duplica todas as chaves da lista original
i = 0;
while (rsp->content.keys[i] != NULL) {
if((keys[i] = strdup(rsp->content.keys[i])) == NULL) {
ERROR("remote_table: strdup keys");
table_free_keys(keys);
free_message(rsp);
return NULL;
}
i++;
}
keys[nKeys - 1] = NULL; //coloca o último elemento da lista a NULL
//em caso de sucesso
free_message(rsp);
return keys;
}
/*
* Função para obter o timestamp do valor associado a essa chave.
* Em caso de erro devolve -1. Em caso de chave não encontrada devolve 0.
*/
long rtable_get_ts(struct rtable_t *table, char *key) {
// Verifica os parâmetros
if(table == NULL || key == NULL) {
ERROR("NULL table or key");
return -1;
}
// Preenche os campos da mensagem
struct message_t msg;
msg.opcode = OP_RT_GETTS;
msg.c_type = CT_KEY;
msg.content.key = key;
// Envia a mensagem e recebe a resposta
struct message_t *rsp;
if((rsp = network_send_receive(table, &msg)) == NULL) {
ERROR("network_send_receive");
return -1;
}
// Verifica se a resposta é válida
if(rsp->opcode != (OP_RT_GETTS + 1)) {
if(rsp->opcode == OP_RT_ERROR) {
ERROR("OP_RT_ERROR");
}
free_message(rsp);
return -1;
}
// Em caso de sucesso
long ts = rsp->content.timestamp;
//printf("Timestamp recebido: %ld\n", ts);
free_message(rsp);
return ts;
}