Question

C Programming - Please Help us! Implementing Load Balancing, the 3 Base Code files are at the bot...

C Programming - Please Help us! Implementing Load Balancing, the 3 Base Code files are at the bottom: Implementing Load Balancing Summary: In this homework, you will be implementing the main muti-threaded logic for doing batch based server load balancing using mutexes Background In this assignment you will write a batch-based load balancer. Consider a server which handles data proces- sing based on user requests. In general, a server has only a fixed set of hardware resources that it can use to satisfy user requests. This is problematic since servers can be become overloaded. One common scaling feature that is implemented is load batching (a form of load balancing). On modern platforms, it is possible to spin up a virtual instance server using a cloud environment (e.g., AWS, Microsoft Azure, Google Cloud) to handle specific needs. The idea of cloud computing has gained traction as a way to deal with scalability and maintance issues. Examples include internet-based storage, computing, or services, which are accessed by client-based devices or by web browsers. As more requests are made, more servers instance are spawned This gives the ability to seamlessly scale up to peaks in user requests. Although this provides a good way to scale resources, the cost of spinning up a new server is non-trivial. Thus, gateway servers tend to col lect a batch of requests before starting a server instance. Your goal in this assignment is to implement the multi-threaded load balancer server logic that l mimic the process of creating server instances to process es of requ Note that while thi rk s come Tn be modelin ren cross three files At a high level, the load balancer server waits for a specific number of requests to be made before spawning an instance server in a cloud-like environment, and initializing the instance with the appropriate work. We call the number of requests that should be serviced the batch size, and assume that the server instances are designed so they can handle exactly batch size number of requests at a time. The load balancer starts to form a batch as soon as it receives as least one request and continues to add requests to the batch until the batch is full (i.e., the batch size is reached). At that point, the load balancer will spawn a new server instance using the instance host to begin processing the batch. The load balancer makes sure that server instances are only initialized when enough requests have been made. Internally, the load balancer will add requests to a list which is then forwarded to a instance server once it reaches the appropriate size. As the requests are handled by the individual server instances, each instance will store the result into output location given by the creator of the request This document is separated into five sections: Background, System Architecture, Requirements, Include i have almost finished r eptual view of the system as the interactions between users, a load balance ig Вас gro rn nd an instance host. In Requirements, we will discuss what is expected of you in this homework. In Include re, we di Files, we discuss the the various libraries and function calls you may find useful in the assigr Submission discusses how your source code should be submitted on BlackBoard ent. Lastl //BASECODE // //User.c file -------------------------------------------------------------------------------------------------// #include #include #include #include #include "LoadBalancer.h" //forward declarations for internal (private) functions. void* simulate_user_request(void* user_id); /** * Entry point to simulation. * * @return Zero. */ int main() { int number_of_requests = 10; int batch_size = 5; printf("Please input number of requests (users): "); //scanf("%d", &number_of_requests); printf("Please input batch size: "); //scanf("%d", &batch_size); pthread_t threads[number_of_requests]; balancer_init(batch_size); //create number_of_requests number of users that want to square a number. for (int i = 0; i < number_of_requests; i++) { printf("creating: %d\n", i); pthread_create(&threads[i], NULL, &simulate_user_request, (void*)i); } balancer_shutdown(); //wait for all users to finish before program exit. for (int i = 0; i < number_of_requests; i++) pthread_join(threads[i], NULL); return 0; } /** * Simulates a user requesting work to be done a server. Expected to be run in a * thread. * * @param user_id * @return */ void* simulate_user_request(void* user_id) { int data = rand() % 100; int* result = (int*)malloc(sizeof(int)); *result = -1; //make the thread wait to simulate differences in when user requests occur. int ms = (rand() % 100) * 1000; usleep(ms); printf("User #%d: Wants to process data=%d and store it at %p.\n", (int)user_id, data, result); //make request to balance to complete job and wait for it's completion. balancer_add_job((int)user_id, data, result); while(*result == -1); //busy waiting, bad but simple printf("User #%d: Received result from data=%d as result=%d.\n", (int)user_id, data, *result); free(result); pthread_exit(NULL); } // // // // // //LoadBalancer.h file ------------------------------------------------------------------------------------------------------// #ifndef LOADBALANCER_H #define LOADBALANCER_H #include "InstanceHost.h" //structure to track jobs as they are created. serves as list node. struct job_node { int user_id; //unique id of user int data; //input data provided by user. int* data_result; //pointer to place in global memory to store result. //negative one (-1) means result not computed. struct job_node* next;//pointer to the next job in a list of jobs. }; //forward declarations for (public) functions /** * Initializes the load balancer. Takes batch size as parameter. */ void balancer_init(int batch_size); /** * Shuts down the load balancer. Ensures any outstanding batches have * completed. */ void balancer_shutdown(); /** * Adds a job to the load balancer. If enough jobs have been added to fill a * batch, will request a new instance from InstanceHost. When job is complete, * *data_return will be updated with the result. * * @param user_id the id of the user making the request. * @param data the data the user wants to process. * @param data_return a pointer to a location to store the result of processing. */ void balancer_add_job(int user_id, int data, int* data_return); /** * Sets the size of the batch. That is, how many jobs much be collected before a * server instance requested. * * @param size the new batch size. */ void balancer_set_batch_size(int size); #endif /* LOADBALANCER_H */ // // // // // //InstanceHost.h file ------------------------------------------------------------------------------------------------------// #ifndef INSTANCEHOST_H #define INSTANCEHOST_H #include "LoadBalancer.h" struct job_node; //defined in LoadBalancer //forward declarations for (public) functions /** * Initializes the host environment. */ void host_init(); /** * Shuts down the host environment. Ensures any outstanding batches have * completed. */ void host_shutdown(); /** * Creates a new server instance (i.e., thread) to handle processing the items * contained in a batch (i.e., a listed list of job_node). InstanceHost will * maintain a list of active instances, and if the host is requested to * shutdown, ensures that all jobs are completed. * * @param job_batch_list A list containing the jobs in a batch to process. */ void host_request_instance(struct job_node* batch); #endif

0 0
Add a comment Improve this question Transcribed image text
✔ Recommended Answer
Answer #1

InstanceHost.c


#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include "InstanceHost.h"

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Pre Declarations //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

struct host{
    int num_instances;
    pthread_t *t;
} ;

pthread_t* create_instance(host* h);
void add_instance(host* h);
void remove_instance(host* h);

void *runner(void* args) {
    pthread_exit(NULL);
}
/**
* Initializes the host environment.
*/
host *host_create() {
    host* host = (struct host*)malloc(sizeof(host));
    host->num_instances = 0;
    host->t = create_instance(host);
    return host;
}

/**
* Shuts down the host environment. Ensures any outstanding batches have
* completed.
*/
void host_destroy(host **h) {
    free(*h);

    *h = NULL;
}

/**
* Creates a new server instance (i.e., thread) to handle processing the items
* contained in a batch (i.e., a listed list of job_node). InstanceHost will
* maintain a list of active instances, and if the host is requested to
* shutdown, ensures that all jobs are completed.
*
* @param job_batch_list A list containing the jobs in a batch to process.
*/
void host_request_instance(host *h, struct job_node *batch) {
    pthread_create(&h->t[h->num_instances], NULL, runner, (void*) batch);

}

pthread_t* create_instance(host *h) {
    return (pthread_t*)malloc(sizeof(pthread_t));
}

void add_instance(host *h) {
    h->num_instances++;
    pthread_t* temp = h->t;

    h->t = (pthread_t*)realloc(sizeof(pthread_t)*h->num_instances);
    free(temp);
}

void remove_instance(host *h) {

}

InstanceHost.h

#ifndef INSTANCEHOST_H
#define INSTANCEHOST_H

#include "LoadBalancer.h"

//struct for representing the host
typedef struct host host;

struct job_node; //defined in LoadBalancer

//forward declarations for (public) functions

/**
* Initializes the host environment.
*/
host* host_create();

/**
* Shuts down the host environment. Ensures any outstanding batches have
* completed.
*/
void host_destroy(host** h);

/**
* Creates a new server instance (i.e., thread) to handle processing the items
* contained in a batch (i.e., a listed list of job_node). InstanceHost will
* maintain a list of active instances, and if the host is requested to
* shutdown, ensures that all jobs are completed.
*
* @param job_batch_list A list containing the jobs in a batch to process.
*/
void host_request_instance(host* h, struct job_node* batch);

#endif

LoadBalancer.c

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include "LoadBalancer.h"
#include "InstanceHost.h"

struct balancer {
    struct host *host;
    struct job_node *head;
    pthread_mutex_t *lock;
    int number_of_requests;
    int batch_size ;
};

void balancer_destroy(balancer **lb) {

    free(*lb);
    *lb = NULL;

}

void balancer_add_job(balancer *lb, int user_id, int data, int *data_return) {
    pthread_mutex_lock(lb->lock);
    printf("LoadBalancer : Received new job from us e r #%d to process data=%d and storeit at %p. \n",
            user_id,
            data,
            data_return);

    lb->number_of_requests++;

    struct job_node *job = (struct job_node*) malloc(sizeof(struct job_node));
    job->data = data;
    job->data_result = data_return;


    job->next = lb->head;
    lb->head = job;


    if(lb->number_of_requests == lb->batch_size) {
         host_request_instance(lb->host, lb->head);
    }

    pthread_mutex_unlock(lb->lock);

    int i;
    for(i = 0; i < lb->host)
}

balancer *balancer_create(int batch_size) {
    balancer *bal = (balancer*)malloc(sizeof(balancer));
    bal->head = (struct job_node*)malloc(sizeof(struct job_node)*batch_size);
    pthread_mutex_init(bal->lock, NULL);
    bal->number_of_requests = batch_size;
    bal->number_of_requests = 0;
    bal->host = host_create();
    return bal;
}

LoadBalancer.h


#ifndef LOADBALANCER_H
#define LOADBALANCER_H

#include "InstanceHost.h"

//struct for representing the load balancer
typedef struct balancer balancer;

//structure to track jobs as they are created. serves as list node.
struct job_node {
    int user_id;          //unique id of user
    int data;             //input data provided by user.
    int* data_result;     //pointer to place in global memory to store result.
                          //negative one (-1) means result not computed.
    struct job_node* next;//pointer to the next job in a list of jobs.
};

//forward declarations for (public) functions

/**
* Initializes the load balancer. Takes batch size as parameter.
*/
balancer* balancer_create(int batch_size);

/**
* Shuts down the load balancer. Ensures any outstanding batches have
* completed.
*/
void balancer_destroy(balancer** lb);

/**
* Adds a job to the load balancer. If enough jobs have been added to fill a
* batch, will request a new instance from InstanceHost. When job is complete,
* *data_return will be updated with the result.
*
* @param user_id the id of the user making the request.
* @param data the data the user wants to process.
* @param data_return a pointer to a location to store the result of processing.
*/
void balancer_add_job(balancer* lb, int user_id, int data, int* data_return);

#endif /* LOADBALANCER_H */


User.c

#define _POSIX_C_SOURCE 199506L

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "LoadBalancer.h"

//forward declarations for internal (private) functions.
void* simulate_user_request(void* user_id);

//variable to store load balancer object
balancer* lb;

/**
* Entry point to simulation.
*
* @return Zero.
*/
int main() {
   int number_of_requests = 10;
    int batch_size = 5;
   printf("Please input number of requests (users): ");
   //scanf("%d", &number_of_requests);
   printf("Please input batch size: ");
   //scanf("%d", &batch_size);

   pthread_t threads[number_of_requests];

    lb = balancer_create(batch_size);

    //create number_of_requests number of users that want to square a number.
    for (int i = 0; i < number_of_requests; i++) {
        printf("creating: %d\n", i);
        pthread_create(&threads[i], NULL, &simulate_user_request, (void*)i);
    }

    nanosleep((struct timespec[]){{2, 0}}, NULL); //wait two seconds

    balancer_destroy(&lb);

    //wait for all users to finish before program exit.
    for (int i = 0; i < number_of_requests; i++)
        pthread_join(threads[i], NULL);
  
    return 0;
}

/**
* Simulates a user requesting work to be done a server. Expected to be run in a
* thread.
*
* @param user_id
* @return
*/
void* simulate_user_request(void* user_id) {
    int data = rand() % 100;
    int* result = (int*)malloc(sizeof(int));
    *result = -1;
  
    //make the thread wait to simulate differences in when user requests occur.
    int ms = (rand() % 100) * 1000;
    nanosleep((struct timespec[]){{0, ms*1000000}}, NULL);
  
    printf("User #%d: Wants to process data=%d and store it at %p.\n", (int)user_id, data, result);
  
    //make request to balance to complete job and wait for it's completion.
    balancer_add_job(lb, (int)user_id, data, result);
    while(*result == -1); //busy waiting, bad but simple
  
    printf("User #%d: Received result from data=%d as result=%d.\n", (int)user_id, data, *result);
  
    free(result);
  
    pthread_exit(NULL);
}

> This is just a copy of the Chegg answers... it's incomplete and does not compile.

kristen9731 Tue, Nov 9, 2021 6:06 AM

Add a comment
Know the answer?
Add Answer to:
C Programming - Please Help us! Implementing Load Balancing, the 3 Base Code files are at the bot...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Similar Homework Help Questions
  • Please help in C: with the following code, i am getting a random 127 printed in...

    Please help in C: with the following code, i am getting a random 127 printed in front of my reverse display of the array. The file i am pulling (data.txt) is: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 when the reverse prints, it prints: 127 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 not sure why...please...

  • Can you help with this C programming question. I have provided the skeleton code below along...

    Can you help with this C programming question. I have provided the skeleton code below along with the Stack/Data/Process Class for you to see/reference. Along with the Stack/Data type definition.   **SKELTON CODE** #include #include #include Stack* concat_stack(Stack *s1, Stack *s2) { //your code here return NULL; } **STACK CLASS FOR YOU TO REFERENCE** #include #include #include #include Stack* create_stack(int stack_capacity) { Stack *s = (Stack*) malloc(sizeof(Stack)); if (stack_capacity < 1) { fprintf(stderr, "Error(create_stack): invalid capacity, set to 10\n"); s->capacity =...

  • C programming A linked list is a linear data structure that allows us to add and remove items fro...

    c programming A linked list is a linear data structure that allows us to add and remove items from the list very quickly, by simply changing a few pointers. There are many different variations of linked lists. We have studied the doubly-linked, circular, with a dummy-header-node version of a linked list. In the class notes we studied several functions to manipulate a Linked List. For this assignment you must write the code for the following additional linked list functions: addFirst,...

  • This assignment is comprised of 3 parts: ​All files needed are located at the end of...

    This assignment is comprised of 3 parts: ​All files needed are located at the end of the directions. Part 1: Implementation of Dynamic Array, Stack, and Bag First, complete the Worksheets 14 (Dynamic Array), 15 (Dynamic Array Amortized Execution Time Analysis), 16 (Dynamic Array Stack), and 21 (Dynamic Array Bag). These worksheets will get you started on the implementations, but you will NOT turn them in. ​Do Not Worry about these, they are completed. Next, complete the dynamic array and...

  • PROGRAMING IN C. PLEASE HELP FIX MY CODE TO FIT THE FOLLOWING CRITERIA: 1.)Read your stocks...

    PROGRAMING IN C. PLEASE HELP FIX MY CODE TO FIT THE FOLLOWING CRITERIA: 1.)Read your stocks from your mystocks.txt file. You can use this information for the simulator. 2.)The stock price simulator will return the current price of the stock. The current prices is the prices of the requested ticker + a random number. 3.)We will assume that the stock price remains constant after the price check till your trade gets executed. Therefore, a buy or a sell order placed...

  • In C++: Please help me correct this code .... All parts with (FIX ME) #include <algorithm> #include <climits&gt...

    In C++: Please help me correct this code .... All parts with (FIX ME) #include <algorithm> #include <climits> #include <iostream> #include <string> // atoi #include <time.h> #include "CSVparser.hpp" using namespace std; //============================================================================ // Global definitions visible to all methods and classes //============================================================================ const unsigned int DEFAULT_SIZE = 179; // forward declarations double strToDouble(string str, char ch); // define a structure to hold bid information struct Bid { string bidId; // unique identifier string title; string fund; double amount; Bid() {...

  • I need help on this Systems review please! it's due by midnight monday. Question 1 Not...

    I need help on this Systems review please! it's due by midnight monday. Question 1 Not yet answered Points out of 1.00 Flag question Question text Using these declarations: int * numberPointers[3]; int * pointer; int number; Which of the following statements would generate a warning or error? Select one: a. number = pointer; b. *pointer = number; c. pointer = numberPointers; d. numberPointers[2] = &number; e. a., b., and d. f. a. and c. Question 2 Not yet answered...

  • C code program help. I am trying to find the total parallel resistive load. This is...

    C code program help. I am trying to find the total parallel resistive load. This is what I have so far. It does run, it does ask for numbers. But it doesn't calculate. It just comes out "The parallel is: 0.00". I have tried 3, 4, 5 and 3.2, 4.3, 5.4. Still only shows 0.00. I have tried several combinations of putting different data types in both main.c and the rest of it. Any help or ideas would be helpful....

  • In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer...

    In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer to the standard output. The Producer Accepts multiple consumer requests and processes each request by creating the following four threads. The reader thread will read an input file, one line at a time. It will pass each line of input to the character thread through a queue...

  • PLEASE HELP WITH THE FIX ME'S #include #include #include #include "CSVparser.hpp" using namespace std; //==...

    PLEASE HELP WITH THE FIX ME'S #include #include #include #include "CSVparser.hpp" using namespace std; //============================================================================ // Global definitions visible to all methods and classes //============================================================================ // forward declarations double strToDouble(string str, char ch); // define a structure to hold bid information struct Bid { string bidId; // unique identifier string title; string fund; double amount; Bid() { amount = 0.0; } }; //============================================================================ // Linked-List class definition //============================================================================ /** * Define a class containing data members and methods to *...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT