/
museum.c
675 lines (622 loc) · 18.8 KB
/
museum.c
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
// Wojciech Kordalski (wk359805)
// nie wchodzić na stderr, bo KDevelop się wiesza wtedy :D
#include "common.h"
#include "debug.h"
#include "double_queue.h"
#include "util.h"
#include "bank_utils.h"
#include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static int Dlugosc;
static int Glebokosc;
static int OplataStala;
static int OgraniczenieArtefaktow;
static int LiczbaFirm;
static int UruchomioneFirmy;
static pid_t bank_pid;
static pthread_mutex_t ochrona;
static int do_exit = 0;
static int *Teren;
static int *Szacunek;
static int *Rezerwacje;
static int *Wydobyte;
static int *Uswiadomione;
static int *Kolekcje;
static char **Raporty;
static int *DlugosciRaportow;
static int *OczekiwnaDlugoscRaportu;
static double_queue_t mqueue;
static double_queue_t bqueue;
static double_queue_t *mQ = &mqueue;
static double_queue_t *bQ = &bqueue;
void * delegate(void *arg);
int terrain(int d, int g) {
return Teren[d * Glebokosc + g];
}
typedef struct {
// data pf delegate
int zajety;
long ip;
int g;
int l;
pthread_t thread;
int do_exit;
int k;
} delegate_t;
static delegate_t *Delegaci;
void cleanup() {
bold("Running cleanup...");
log("Closing message queues.");
double_queue_close(mQ);
double_queue_close(bQ);
log("Freeing memory.");
if(Teren) free(Teren);
if(Szacunek) free(Szacunek);
if(Rezerwacje) free(Rezerwacje);
if(Wydobyte) free(Wydobyte);
if(Uswiadomione) free(Uswiadomione);
if(Kolekcje) free(Kolekcje);
if(Raporty) {
for(int i = 0; i < LiczbaFirm; i++) {
if(Raporty[i] != NULL) free(Raporty[i]);
}
free(Raporty);
}
if(DlugosciRaportow) free(DlugosciRaportow);
if(OczekiwnaDlugoscRaportu) free(OczekiwnaDlugoscRaportu);
if(Delegaci) free(Delegaci);
}
static void panic() {
error("Panic inside museum!");
log("Sending panic to bank and shutting down - no reports will be printed.");
if(bank_pid > 0) {
log("Waiting for bank's reaction for panic.");
kill(bank_pid, SIGINT);
while(1) pause(); // waits for termination by external SIGTERM
} else {
log("Bank is unknown - simply exitting.");
cleanup();
exit(1); // we do not know bank
}
}
int report_server(
void *query, size_t query_length,
void **response, size_t *response_length,
int source, void *arg) {
char cmd = ((char*)query)[0];
log("Report server!");
if(cmd == ACT_MUSEUM_REPORT_INIT) {
int id, len;
if(match(query, query_length, "@c %i %i", ACT_MUSEUM_REPORT_INIT, &id, &len) == 0) {
id--;
if(Raporty[id] == NULL) {
Raporty[id] = malloc(len+1);
if(Raporty[id] == NULL) return -1;
DlugosciRaportow[id] = 0;
OczekiwnaDlugoscRaportu[id] = len;
combine(response, response_length, "%c", ACT_OK);
return 0;
} else goto wrong_message;
} else goto wrong_message;
} else if(cmd == ACT_MUSEUM_SEND_REPORT_PART) {
int id;
size_t len = 1000;
void *data = malloc(1010);
if(data == NULL) return -1;
if(match(query, query_length, "@c %i %bv", ACT_MUSEUM_SEND_REPORT_PART, &id, data, &len) == 0) {
id--;
if(len <= OczekiwnaDlugoscRaportu[id] - DlugosciRaportow[id]) {
memcpy(Raporty[id] + DlugosciRaportow[id], data, len);
DlugosciRaportow[id] += len;
free(data);
combine(response, response_length, "%c", ACT_OK);
return 0;
} else {
free(data);
goto wrong_message;
}
} else {
free(data);
goto wrong_message;
}
} else if(cmd == ACT_MUSEUM_COMPANY_EXIT) {
if(match(query, query_length, "@c", ACT_MUSEUM_COMPANY_EXIT) == 0) {
UruchomioneFirmy--;
if(UruchomioneFirmy <= 0) {
do_exit = 1;
}
combine(response, response_length, "%c", ACT_OK);
return 0;
} else {
goto wrong_message;
}
} else return -1;
wrong_message:
warning("Got wrong message.");
combine(response, response_length, "%c %c", ACT_ERROR, ERR_WRONG_MESSAGE);
return 0;
}
int server(
void *query, size_t query_length,
void **response, size_t *response_length,
int source, void *arg) {
if(query_length <= 0) {
error("Empty message - something went wrong.");
return -1;
}
char cmd = ((char*)query)[0];
if(cmd == ACT_MUSEUM_GET_ESTIMATIONS) {
int pL, pP, pT, pB;
if(match(query, query_length, "@c %i %i %i %i", ACT_MUSEUM_GET_ESTIMATIONS, &pL, &pP, &pT, &pB) == 0) {
if(!(1 <= pL && pL <= pP && pP <= Dlugosc && 1 <= pT && pT <= pB && pB <= Glebokosc)) {
combine(response, response_length, "%c %c", ACT_ERROR, ERR_INVALID_ARGUMENT);
return 0;
} else if((pP - pL + 1) * (pB - pT + 1) * sizeof(int) > 999) {
combine(response, response_length, "%c %c", ACT_ERROR, ERR_INVALID_ARGUMENT);
return 0;
} else {
pP--; pL--; pB--; pT--;
int *res = malloc((pP - pL + 1) * (pB - pT + 1) * sizeof(int));
int w = pP - pL + 1;
for(int i = pL, ii = 0; i <= pP; i++, ii++) {
for(int j = pT, jj = 0; j <= pB; j++, jj++) {
res[ii * w + jj] = ((Wydobyte[i] < j)?Szacunek[i*Glebokosc + j]:0);
}
}
combine(response, response_length, "%c %b", ACT_OK, res, (pP - pL + 1) * (pB - pT + 1) * sizeof(int));
free(res);
return 0;
}
} else {
combine(response, response_length, "%c %c", ACT_ERROR, ERR_WRONG_MESSAGE);
return 0;
}
} else if(cmd == ACT_MUSEUM_BUY_TERRAIN) {
/*
* idx (int), id (int), k (int), z (int) -> l (int), d (int), dip(long)
*/
int k, z, idx, id;
if(match(query, query_length, "@c %i %i %i %i", ACT_MUSEUM_BUY_TERRAIN, &idx, &id, &k, &z) == 0) {
// Try to allocate and return result
if(z < OplataStala) {
combine(response, response_length, "%c", ACT_REJECT);
return 0;
}
int ret = change_money_of_company(bQ, idx, id, -OplataStala, museum_ip);
if(ret == 1 || z < OplataStala || Delegaci[idx].zajety != 0) {
combine(response, response_length, "%c", ACT_REJECT);
return 0;
} else if(ret == -1) {
combine(response, response_length, "%c", ACT_ERROR);
return 0;
}
z -= OplataStala;
pthread_mutex_lock(&ochrona);
// find first such block of terrain
int l = -1;
int g = 0;
for(int i = 0; i < Dlugosc - k; i++) {
l = i;
for(int j = 0; j < k; j++) {
if(Rezerwacje[i+j] > 0) {
l = -1;
i = i + j;
break;
}
}
if(l + k == Dlugosc) {
combine(response, response_length, "%c", ACT_REJECT);
pthread_mutex_unlock(&ochrona);
return 0;
}
if(l != -1) {
int sumcost = 0;
int ndw = 0;
for(int ii = 0; ii < Dlugosc; ii++) {
if(Wydobyte[l+ii] < Glebokosc) {
ndw = 1;
break;
}
}
if(ndw == 0) {
continue;
}
for(int i = 0; i < Glebokosc; i++) {
int line_cost = 0;
for(int j = 0; j < k; j++) {
if(Wydobyte[j+l] > i) continue;
line_cost += Szacunek[(j+l)*Glebokosc+i];
if(line_cost > z) {
line_cost = z + 1;
break;
}
}
if(line_cost == z + 1) break;
else if(line_cost + sumcost > z) break;
sumcost += line_cost;
g = i + 1;
}
if(g == 0 || sumcost > z) {
continue;
}
}
}
int ret2 = change_money_of_company(bQ, idx, id, -z, museum_ip);
if(ret2 == 1) {
combine(response, response_length, "%c", ACT_REJECT);
pthread_mutex_unlock(&ochrona);
return 0;
} else if(ret2 == -1) {
combine(response, response_length, "%c", ACT_ERROR);
pthread_mutex_unlock(&ochrona);
return 0;
}
for(int i = 0; i < k; i++) {
Rezerwacje[i+l] = g;
Uswiadomione[i+l] = 0;
}
pthread_mutex_unlock(&ochrona);
// OK - create delegate
Delegaci[idx].zajety = 1;
Delegaci[idx].ip = delegate_base_ip + idx;
Delegaci[idx].l = l;
Delegaci[idx].g = g;
Delegaci[idx].do_exit = 0;
Delegaci[idx].k = k;
pthread_attr_t attrs;
pthread_attr_init(&attrs);
pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
int ret3 = pthread_create(&(Delegaci[idx].thread), &attrs, delegate, Delegaci+idx);
if(ret3 != 0) {
error("Failed with creating thread.");
pthread_attr_destroy(&attrs);
return -1;
}
pthread_attr_destroy(&attrs);
combine(response, response_length, "%c %i %i %l", ACT_OK, l, g, delegate_base_ip + idx);
return 0;
} else {
combine(response, response_length, "%c", ACT_ERROR);
return 0;
}
} else if(cmd == ACT_MUSEUM_REPORT_INIT || cmd == ACT_MUSEUM_SEND_REPORT_PART
|| cmd == ACT_MUSEUM_COMPANY_EXIT) {
if(report_server(query, query_length, response, response_length, source, arg) == 0)
return 0;
else
return -1;
} else {
warning("Unsupported command 0x%x.", cmd);
combine(response, response_length, "%c", ACT_ERROR);
return 0;
}
assert(0);
return -1;
}
int reduced_server(
void *query, size_t query_length,
void **response, size_t *response_length,
int source, void *arg) {
if(query_length <= 0) {
error("Empty message - something went wrong.");
return -1;
}
char cmd = ((char*)query)[0];
if(cmd == ACT_MUSEUM_GET_ESTIMATIONS) {
goto reject;
} else if(cmd == ACT_MUSEUM_BUY_TERRAIN) {
goto reject;
} else if(cmd == ACT_MUSEUM_REPORT_INIT || cmd == ACT_MUSEUM_SEND_REPORT_PART
|| cmd == ACT_MUSEUM_COMPANY_EXIT) {
if(report_server(query, query_length, response, response_length, source, arg) == 0)
return 0;
else
return -1;
} else {
warning("Unsupported command 0x%x.", cmd);
combine(response, response_length, "%c %c", ACT_ERROR, ERR_WRONG_MESSAGE);
return 0;
}
assert(0);
return -1;
reject:
combine(response, response_length, "%c", ACT_REJECT);
return 0;
}
void on_sigint(int type) {
if(bank_pid <= 0) {
cleanup();
exit(1);
}
else
{
do_exit = 1;
}
}
void on_sigterm(int type) {
// simply exit after cleanup
log("Got SIGTERM - exitting.");
cleanup();
exit(1);
}
int main(int argc, const char *argv[]) {
bold("Starting museum process.");
signal(SIGTERM, on_sigterm);
signal(SIGINT, on_sigint);
if(argc != 5) {
error("Wrong command-line input - four parameters needed.");
panic();
}
if(sscanf(argv[1], "%d", &Dlugosc) != 1) {
error("First parameter should be a number.");
panic();
}
if(sscanf(argv[2], "%d", &Glebokosc) != 1) {
error("Second parameter should be a number.");
panic();
}
if(sscanf(argv[3], "%d", &OplataStala) != 1) {
error("Third parameter should be a number.");
panic();
}
if(sscanf(argv[4], "%d", &OgraniczenieArtefaktow) != 1) {
error("Fourth parameter should be a number.");
panic();
} else {
OgraniczenieArtefaktow++; // bo chcemy większe (>=), a nie ściśle większe (>)
}
//
// Create message queues
//
log("Creating museum message queue.");
if(double_queue_init(mQ, 1, museum_key1, museum_key2, 0700|IPC_CREAT, 0700|IPC_CREAT) == -1) {
error("Failed creating message queue.");
panic();
}
log("Creating bank message queue.");
if(double_queue_init(bQ, 0, bank_key1, bank_key2, 0700|IPC_CREAT, 0700|IPC_CREAT) == -1) {
error("Failed creating message queue.");
panic();
}
//
// Read data
//
log("Reading data from stdin");
{
if((Teren = malloc(Dlugosc*Glebokosc*sizeof(int))) == NULL) {
error("Allocation failed.");
panic();
}
if((Szacunek = malloc(Dlugosc*Glebokosc*sizeof(int))) == NULL) {
error("Allocation failed.");
panic();
}
if((Kolekcje = malloc(OgraniczenieArtefaktow*sizeof(int))) == NULL) {
error("Allocation failed.");
panic();
} else {
for(int i = 0; i < OgraniczenieArtefaktow; i++) {
Kolekcje[i] = 0;
}
}
if((Rezerwacje = malloc(Dlugosc*sizeof(int))) == NULL) {
error("Allocation failed.");
panic();
} else {
for(int i = 0; i < Dlugosc; i++) {
Rezerwacje[i] = 0;
}
}
if((Wydobyte = malloc(Dlugosc*sizeof(int))) == NULL) {
error("Allocation failed.");
panic();
} else {
for(int i = 0; i < Dlugosc; i++) {
Wydobyte[i] = 0;
}
}
for(int i = 0; i < Dlugosc; i++) {
for(int j = 0; j < Glebokosc; j++) {
scanf("%d", Teren+i*Glebokosc+j);
}
}
for(int i = 0; i < Dlugosc; i++) {
for(int j = 0; j < Glebokosc; j++) {
scanf("%d", Szacunek+i*Glebokosc+j);
}
}
}
bold("Connecting to bank...");
{
void *query, *response;
size_t qlen, response_size;
pid_t pid = getpid();
int exit_on_signal = 0;
combine(&query, &qlen, "%c %b", ACT_MUSEUM_WITH_BANK_CONNECT_REQUEST, &pid, sizeof(pid_t));
if(double_queue_query(bQ, query, qlen, (void**)(&response), &response_size, &exit_on_signal, museum_ip, bank_ip) != 0) {
error("Error connecting to bank.");
free(query);
panic();
}
free(query);
if(match(response, response_size, "@c %i %b", ACT_OK, &LiczbaFirm, &bank_pid, sizeof(pid_t)) != 0) {
error("Expected OK message - something went wrong.");
free(response);
panic();
}
UruchomioneFirmy = LiczbaFirm;
free(response);
}
bold("Creating company information buffers...");
{
Raporty = malloc(LiczbaFirm * sizeof(char*));
DlugosciRaportow = malloc(LiczbaFirm * sizeof(int));
OczekiwnaDlugoscRaportu = malloc(LiczbaFirm * sizeof(int));
if(Raporty == NULL || DlugosciRaportow == NULL || OczekiwnaDlugoscRaportu == NULL) {
error("Allocation failed");
panic();
}
for(int i = 0; i < LiczbaFirm; i++) {
Raporty[i] = NULL;
}
}
bold("Started listening...");
while(!do_exit) {
int exit_on_signal = 1;
int ret = 0;
if((ret = double_queue_listen(mQ, server, NULL, &exit_on_signal, museum_ip)) == -1) {
error("Error during listening for queries.");
panic();
}
if(ret == DOUBLE_QUEUE_INTERRUPTED) break;
}
bold("Calling bank to exit all companies.");
{
void *query, *response;
size_t qlen, resplen;
combine(&query, &qlen, "%c", ACT_BANK_EXIT_ALL_COMPANIES);
int exit_after_signal = 0;
if(double_queue_query(bQ, query, qlen, &response, &resplen, &exit_after_signal, museum_ip, bank_ip) == -1) {
error("Failed sending company termination query to bank.");
}
free(query);
if(match(response, resplen, "@c", ACT_OK) != 0) {
error("Wrong response - maby some error.");
}
free(response);
}
// handle companies reports
while(UruchomioneFirmy > 0) {
int exit_on_signal = 0;
int ret = 0;
if((ret = double_queue_listen(mQ, reduced_server, NULL, &exit_on_signal, museum_ip)) == -1) {
error("Error during listening for queries.");
panic();
}
}
// print reports
for(int i = 0; i < Dlugosc; i++) {
for(int j = 0; j < Glebokosc; j++) {
if(Wydobyte[i] > j) printf("0");
else if(Rezerwacje[i] > j) printf("1");
else printf("2");
}
printf("\n");
}
for(int i = 0; i < LiczbaFirm; i++) {
if(Raporty[i] != NULL) {
Raporty[i][DlugosciRaportow[i]] = 0;
printf("\n%s", Raporty[i]);
} else {
printf("\nFirma %d nie przesłała raportu.", i+1);
}
}
log("Terminating bank");
{
void *query, *response;
size_t qlen, resplen;
combine(&query, &qlen, "%c", ACT_BANK_EXIT);
int exit_after_signal = 0;
if(double_queue_query(bQ, query, qlen, &response, &resplen, &exit_after_signal, museum_ip, bank_ip) == -1) {
error("Failed sending bank termination query.");
}
free(query);
if(match(response, resplen, "@c", ACT_OK) != 0) {
error("Wrong response - maby some error.");
}
free(response);
}
cleanup();
return 0;
}
int delegate_server(
void *query, size_t query_length,
void **response, size_t *response_length,
int source, void *arg) {
if(query_length <= 0) {
error("Empty message - something went wrong.");
return -1;
}
delegate_t *data = (delegate_t*)arg;
char cmd = ((char*)query)[0];
if(cmd == ACT_DELEGATE_GIVE_WORK) {
int wrkno;
if(match(query, query_length, "@c %i", ACT_DELEGATE_GIVE_WORK, &wrkno) == 0) {
if(Wydobyte[wrkno + data->l] == Rezerwacje[wrkno + data->l]) {
combine(response, response_length, "%c", ACT_REJECT);
Uswiadomione[wrkno+data->l] = 1;
return 0;
} else {
combine(response, response_length, "%c %i", ACT_OK, terrain(wrkno+data->l, Wydobyte[wrkno+data->l]));
return 0;
}
} else {
combine(response, response_length, "%c", ACT_ERROR);
return 0;
}
} else if(cmd == ACT_DELEGATE_CHECK_WORK) {
int wrkno;
int sym;
int results[32];
if(match(query, query_length, "@c %i %i %b", ACT_DELEGATE_CHECK_WORK, &wrkno, &sym, results, 32 * sizeof(int)) == 0) {
long long int mul = results[0], ter = terrain(wrkno+data->l, Wydobyte[wrkno+data->l]);
for(int i = 1; i < 32; i++) mul *= results[i];
if(mul > ter || sym != ter || ter % mul != 0) {
combine(response, response_length, "%c", ACT_ERROR);
return 0;
} else {
pthread_mutex_lock(&ochrona);
Wydobyte[wrkno+data->l]++;
if(Wydobyte[wrkno+data->l] == data->g) {
int flag = 1;
for(int i = 0; i < data->k; i++) {
if(Wydobyte[data->l + i] < data->g || Uswiadomione[data->l + i] == 0) {
flag = 0; break;
}
}
if(flag) {
data->do_exit = 1;
for(int i = 0; i < data->k; i++) {
Rezerwacje[data->l + i] = 0;
}
}
}
pthread_mutex_unlock(&ochrona);
combine(response, response_length, "%c", ACT_OK);
return 0;
}
} else {
combine(response, response_length, "%c", ACT_ERROR);
return 0;
}
} else if(cmd == ACT_DELEGATE_FIRE) {
pthread_mutex_lock(&ochrona);
data->do_exit = 1;
for(int i = 0; i < data->k; i++) {
Rezerwacje[data->l + i] = 0;
}
pthread_mutex_unlock(&ochrona);
} else {
warning("Unsupported command 0x%x.", cmd);
combine(response, response_length, "%c", ACT_ERROR);
return 0;
}
return -1;
}
void * delegate(void *arg) {
bold("Started delegate");
delegate_t *data = (delegate_t*)arg;
while(!data->do_exit) {
int exit_on_signal = 0;
int ret = 0;
if((ret = double_queue_listen(mQ, delegate_server, data, &exit_on_signal, museum_ip)) == -1) {
error("Error during listening for queries in delegate.");
panic();
}
}
data->zajety = 0;
return NULL;
}