22 #include <sys/socket.h>
23 #include <netinet/in.h>
25 #include <arpa/inet.h>
30 #define MAX_FILE_SIZE (long)(1 * (1 << 29))
32 #define JUMP_SIZE (1 << 14)
44 int n_chunks = file_size / INT_MAX + 1;
46 file->
chunk_size = malloc(
sizeof(
int) * n_chunks);
47 long amount_allocated = 0;
48 int chunk_size = INT_MAX;
49 file->
data = malloc(
sizeof(
char*) * n_chunks);
50 for (
int i=0; amount_allocated < file_size; i++) {
51 if (amount_allocated + chunk_size > file_size) {
52 long chunk_tmp = (file_size - amount_allocated);
53 if (chunk_tmp > (
long)(INT_MAX)) {
54 printf(
"Warning: Chunk size too big!\n");
56 chunk_size = (int)chunk_tmp;
59 file->
data[i] = malloc(chunk_size);
60 amount_allocated += chunk_size;
61 memset(file->
data[i], 0, chunk_size);
63 return amount_allocated;
68 for (
int chunk = 0; accessed < total_size; chunk++) {
70 char *data = file->
data[chunk];
71 for (
int i = 0; i < chunk_size; i +=
JUMP_SIZE) {
74 accessed += (long)chunk_size;
79 void init_db(
char *ip,
int port,
int n_files) {
83 inet_pton(AF_INET, ip, &(
db_addr.sin_addr));
88 struct mock_file *file = malloc(
sizeof(*file));
95 for (
int i=0; i <file->
n_chunks; i++) {
105 int db_fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
111 if (setsockopt(db_fd, SOL_SOCKET, SO_REUSEPORT, &optval,
sizeof(optval)) < 0) {
114 if (setsockopt(db_fd, SOL_SOCKET, SO_REUSEADDR, &optval,
sizeof(optval)) < 0) {
122 if (state->
db_fd <= 0) {
124 if (state->
db_fd == -1) {
130 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINPROGRESS) {
131 log(LOG_DB_OPS,
"Connection in progress..");
140 sprintf(state->
db_req,
"%d", db_param);
146 if (errno == EAGAIN || errno == EWOULDBLOCK) {
156 #define MAX_DB_RCV_LEN 64
160 socklen_t addrlen =
sizeof(
db_addr);
162 (
struct sockaddr*)&
db_addr, &addrlen);
165 if (errno == EAGAIN || errno == EWOULDBLOCK) {
184 log_error(
"Database is not initialized");
197 }
else if (rtn == 1) {
200 }
else if (rtn == 0) {
213 }
else if (rtn == 1) {
215 }
else if (rtn == 0) {
228 }
else if (rtn == 1) {
230 }
else if (rtn == 0) {
int connect_to_db(struct db_state *state)
int recv_from_db(struct db_state *state)
long allocate_file(struct mock_file *file, long file_size)
struct sockaddr_in db_addr
void * allocate_db_memory()
long access_file(struct mock_file *file, long total_size)
#define WS_INCOMPLETE_READ
#define log_perror(fmt,...)
Logging of status messages to the terminal.
int send_to_db(struct db_state *state)
#define WS_INCOMPLETE_WRITE
void free_db_memory(void *memory)
#define log_error(fmt,...)
int query_db(struct db_state *state)
void init_db(char *ip, int port, int n_files)
#define log(level, fmt,...)
Log at a custom level.