Esempio n. 1
0
File: buffer.c Progetto: jjkrol/elka
/*
* initialisation - takse shared memory key and queue_size
* returns 1 if everythings correct
*
*/
int buf_initialise(int shm_key, int queue_size){
/* allocate semaphores */
if((sem_mutex = sem_alloc(MUTEX, 0666 | IPC_CREAT))<0) return -1;
if((sem_full = sem_alloc(FULL, 0666 | IPC_CREAT))<0) return -1;  
if((sem_empty = sem_alloc(EMPTY, 0666 | IPC_CREAT))<0) return -1;
/* initialise semaphores */
int wynik;
if (sem_init(sem_mutex, 1)) return -1;
if (sem_init(sem_full, queue_size-1)) return -1;
if (sem_init(sem_empty, 0)) return -1;
printf("Tworze kolejke za pomoca klucz %d o dlugosci %di\n", shm_key, queue_size);
queue = queue_init(shm_key, queue_size);
initialised = 1;
printf("Initialised\n");
}
Esempio n. 2
0
void semaphore_test2() {
	int pid, pid2;
	int sem;

	sem = sem_alloc();
	sem_init(sem, 0);

	pid = fork();
	if(pid) {
		// father
		sem_wait(sem);
		printf(stdout, "parent woken\n");
    sem_post(sem);
		wait();
	} else {
		// child
		pid2 = fork();
		if(pid2) {
			sem_wait(sem);
			printf(stdout, "child 1 woken\n");
      sem_post(sem);
			wait();
      exit();
		} else {
			sem_post(sem);
			printf(stdout, "posted\n");
      exit();
		}
	}
  printf(stdout, "passed sem_test2!\n");
  sem_destroy(sem);
}
Esempio n. 3
0
void
semaphore_test1(void) {
  int pid;
  int sem;

  sem = sem_alloc();
  sem_init(sem, 0);
  
  printf(stdout, "A\n");
  pid = fork();
  if (pid) {
//	  sleep(5);
   sem_wait(sem);
   printf(stdout, "C\n");
   wait();
   return;
   sem_destroy(sem);
  }
  else {
    sleep(5);
    printf (stdout,  "B\n");
    sem_post(sem);
    printf (stdout, "D\n");
    exit();
  }
  sem_destroy(sem);
}
Esempio n. 4
0
/* Creates and returns a new semaphore. The "count" argument specifies
 * the initial state of the semaphore. */
sys_sem_t sys_sem_new(uint8_t count)
{
    struct semaphore *sem = mm_malloc(sizeof(struct semaphore),0);

    sem_alloc(sem,count );
    return sem;
 }
Esempio n. 5
0
int
_sem_init(sem_t *sem, int pshared, unsigned int value)
{
	(*sem) = sem_alloc(value, pshared);
	if ((*sem) == NULL)
		return (-1);
	return (0);
}
Esempio n. 6
0
int scInitConfig (void)
{
    struct stat mystat;
    char config [BUFSIZE];
    char * s;

    if (scConfigInit) {
      return 0;
    }
    
    if ((sc_sem = sem_alloc (1, "eucalyptus-storage-semaphore")) == NULL) { /* TODO: use this semaphore to fix the race */
        logprintfl (EUCAERROR, "failed to create and initialize a semaphore\n");
        return 1;
    }
    /* read in configuration */
    char * home = getenv (EUCALYPTUS_ENV_VAR_NAME);
    if (!home) {
        home = strdup(""); /* root by default */
    }
    
    snprintf(config, BUFSIZE, EUCALYPTUS_CONF_LOCATION, home);
    if (stat(config, &mystat)==0) {
        logprintfl (EUCAINFO, "SC is looking for configuration in %s\n", config);
        
        if (get_conf_var(config, INSTANCE_PATH, &s)>0){ 
            sc_instance_path = strdup (s); 
            free (s); 
        }

        if (get_conf_var(config, CONFIG_NC_CACHE_SIZE, &s)>0){ 
            cache_size_mb = atoll (s); 
            cache_free_mb = cache_size_mb;
            free (s); 
        }

        if (get_conf_var(config, CONFIG_NC_SWAP_SIZE, &s)>0){ 
            swap_size_mb = atoll (s); 
            free (s); 
        }
    }
    snprintf(add_key_command_path, BUFSIZE, EUCALYPTUS_ADD_KEY, home, home, home);
    
    /* we need to have valid path */
    if (check_directory(sc_instance_path)) {
	    logprintfl (EUCAERROR, "ERROR: INSTANCE_PATH (%s) does not exist!\n", sc_instance_path);
	    return(1);
    }

    if (euca_init_cert ()) {
        logprintfl (EUCAFATAL, "failed to find cryptographic certificates\n");
        return 1;
    }

    snprintf (disk_convert_command_path, BUFSIZE, EUCALYPTUS_DISK_CONVERT, home, home);

    scConfigInit=1;
    return(0);
}
Esempio n. 7
0
//!
//! Initialize ebs data structures and semaphores for EBS
//! Should only be called once!
//!
//! @return
//!
//! @pre
//!
//! @post
//!
//! @note
//!
int init_ebs_utils(int sc_request_timeout_sec)
{
    LOGDEBUG("Initializing EBS utils\n");
    request_timeout_sec = sc_request_timeout_sec;
    if (vol_sem == NULL) {
        vol_sem = sem_alloc(1, IPC_MUTEX_SEMAPHORE);
    }
    LOGDEBUG("Completed EBS util initialization\n");
    return EUCA_OK;
}
Esempio n. 8
0
int init_backing_store (const char * conf_instances_path, unsigned int conf_work_size_mb, unsigned int conf_cache_size_mb)
{
    logprintfl (EUCAINFO, "initializing backing store...\n");

    if (conf_instances_path == NULL) {
        logprintfl (EUCAERROR, "error: INSTANCE_PATH not specified\n");
        return ERROR;
    }
    safe_strncpy (instances_path, conf_instances_path, sizeof (instances_path));
    if (check_directory (instances_path)) {
	    logprintfl (EUCAERROR, "error: INSTANCE_PATH (%s) does not exist!\n", instances_path);
        return ERROR;
    }
    char cache_path [MAX_PATH]; snprintf (cache_path, sizeof (cache_path), "%s/cache", instances_path);
    if (ensure_directories_exist (cache_path, 0, NULL, NULL, BACKING_DIRECTORY_PERM) == -1) return ERROR;
    char work_path [MAX_PATH];  snprintf (work_path,  sizeof (work_path),  "%s/work", instances_path);
    if (ensure_directories_exist (work_path, 0, NULL, NULL, BACKING_DIRECTORY_PERM) == -1) return ERROR;
    unsigned long long cache_limit_blocks = conf_cache_size_mb * 2048; // convert MB to blocks
    unsigned long long work_limit_blocks  = conf_work_size_mb * 2048;
    if (work_limit_blocks==0) { // we take 0 as unlimited
        work_limit_blocks = ULLONG_MAX;
    }

    // by default we let blobstore pick the snapshot policy, which
    // will use device mapper if available, which is faster than copying
    blobstore_snapshot_t snapshot_policy = BLOBSTORE_SNAPSHOT_ANY;
    if (nc_state.disable_snapshots) {
        logprintfl (EUCAINFO, "if allocating storage, will avoid using snapshots\n");
        snapshot_policy = BLOBSTORE_SNAPSHOT_NONE;
    }
    blobstore_set_error_function ( &bs_errors );
    if (cache_limit_blocks) {
        cache_bs = blobstore_open (cache_path, cache_limit_blocks, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_DIRECTORY, BLOBSTORE_REVOCATION_LRU, snapshot_policy);
        if (cache_bs==NULL) {
            logprintfl (EUCAERROR, "ERROR: failed to open/create cache blobstore: %s\n", blobstore_get_error_str(blobstore_get_error()));
            return ERROR;
        }
    }
    work_bs = blobstore_open (work_path, work_limit_blocks, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_FILES, BLOBSTORE_REVOCATION_NONE, snapshot_policy);
    if (work_bs==NULL) {
        logprintfl (EUCAERROR, "ERROR: failed to open/create work blobstore: %s\n", blobstore_get_error_str(blobstore_get_error()));
        logprintfl (EUCAERROR, "ERROR: %s\n", blobstore_get_last_trace());
        blobstore_close (cache_bs);
        return ERROR;
    }

    // set the initial value of the semaphore to the number of 
    // disk-intensive operations that can run in parallel on this node
    if (nc_state.concurrent_disk_ops && (disk_sem = sem_alloc (nc_state.concurrent_disk_ops, "mutex")) == NULL) {
        logprintfl (EUCAERROR, "failed to create and initialize disk semaphore\n");
        return ERROR;
    }

    return OK;
}
Esempio n. 9
0
int diskutil_init (int require_grub) // 0 = not required, 1 = required
{
    int ret = 0;

    if (require_grub > 0) require_grub = 1;
    if (initialized < 1+require_grub) { // if init was called without grub requirement, it will run again if grub is needed now
        bzero (helpers_path, sizeof (helpers_path));
        int missing_handlers = verify_helpers (helpers, helpers_path, LASTHELPER);
        if (helpers_path [GRUB])
            grub_version = 1;
        else
            missing_handlers--;

        if (helpers_path [GRUB_SETUP]) {// don't need it, but grub-setup only exists on v2
            if (grub_version != 1)
                grub_version = 2; // prefer 1 until 2 is implemented
        }
        else 
            missing_handlers--;

        if (require_grub && grub_version == 0) {
            logprintfl (EUCAERROR, "ERROR: cannot find either grub 1 or grub 2\n");
            ret = 1;   
        } else if (grub_version == 1) { 
            // grub 1 commands seem present, check for stage files, which we will be copying
            if (try_stage_dir ("/usr/lib/grub/x86_64-pc") ||
                try_stage_dir ("/usr/lib/grub/i386-pc") ||
                try_stage_dir ("/usr/lib/grub") ||
                try_stage_dir ("/boot/grub")) {
                logprintfl (EUCAINFO, "found grub 1 stage files in %s\n", stage_files_dir);
            } else if (require_grub) {
                logprintfl (EUCAERROR, "ERROR: failed to find grub 1 stage files (in /boot/grub et al)\n");
                ret = 1;
            }
        } else if (grub_version == 2) {
            logprintfl (EUCAINFO, "detected grub 2\n");
        }
        
        // flag missing handlers
        if (missing_handlers) {
            for (int i=0; i<LASTHELPER; i++) {
                if (helpers_path [i] == NULL && i!=GRUB && i!=GRUB_SETUP) {
                    logprintfl (EUCAERROR, "ERROR: missing a required handler: %s\n", helpers[i]);
                    ret = 1;
                }
            }
        }
        
        if (initialized < 1)
            loop_sem = sem_alloc (1, "mutex");
        initialized = 1 + require_grub;
    }
    
    return ret;
}
Esempio n. 10
0
void semaphore_test3(void) {
  int sem1, sem2;
  int i;
  sem1 = sem_alloc();
  sem2 = sem_alloc();
  sem_init(sem1, 0);
  sem_init(sem2, 0);
  sem_post(sem2);
  
  if(fork()) {
    // parent
    for(i = 0; i < 10; i++) {
      sem_wait(sem1); // wait for a child
      printf(stdout, "parent %d\n", i);
      sem_post(sem2); // wake a child
    }
    wait();
  } else {
    // child1
    if(fork()) {
      // child1
      for(i = 0; i < 5; i++) {
        sem_wait(sem2);
        printf(stdout, "child1 %d\n", i);
        sem_post(sem1);
      }
      wait();
      exit();
    } else {
      // child2
      for(i = 0; i < 5; i++) {
        sem_wait(sem2);
        printf(stdout, "child2 %d\n", i);
        sem_post(sem1);
      }
      exit();
    }
  }
  printf(stdout, "sem_test3 passed!\n");
}
Esempio n. 11
0
void init_iscsi (const char * euca_home)
{
    const char * tmp;
    if (euca_home) {
        tmp = euca_home;
    } else {
        tmp = getenv(EUCALYPTUS_ENV_VAR_NAME);
        if (!tmp) {
            tmp = "/opt/eucalyptus";
        }
    } 
    safe_strncpy (home, tmp, sizeof (home));
    snprintf (connect_storage_cmd_path, MAX_PATH, EUCALYPTUS_CONNECT_ISCSI, home, home);
    snprintf (disconnect_storage_cmd_path, MAX_PATH, EUCALYPTUS_DISCONNECT_ISCSI, home, home);
    snprintf (get_storage_cmd_path, MAX_PATH, EUCALYPTUS_GET_ISCSI, home, home);
	iscsi_sem = sem_alloc (1, "mutex");
}
Esempio n. 12
0
int
_sem_init(sem_t *sem, int pshared, unsigned int value)
{
	semid_t semid;

	semid = (semid_t)SEM_USER;
	if ((pshared != 0) && (ksem_init(&semid, value) != 0))
		return (-1);

	(*sem) = sem_alloc(value, semid, pshared);
	if ((*sem) == NULL) {
		if (pshared != 0)
			ksem_destroy(semid);
		return (-1);
	}
	return (0);
}
Esempio n. 13
0
//!
//!
//!
//! @param[in] euca_home
//!
void init_iscsi(const char *euca_home)
{
    const char *tmp = NULL;
    if (euca_home) {
        tmp = euca_home;
    } else {
        if ((tmp = getenv(EUCALYPTUS_ENV_VAR_NAME)) == NULL) {
            tmp = "/opt/eucalyptus";
        }
    }

    euca_strncpy(home, tmp, sizeof(home));
    snprintf(connect_storage_cmd_path, MAX_PATH, EUCALYPTUS_CONNECT_ISCSI, home, home);
    snprintf(disconnect_storage_cmd_path, MAX_PATH, EUCALYPTUS_DISCONNECT_ISCSI, home, home);
    snprintf(get_storage_cmd_path, MAX_PATH, EUCALYPTUS_GET_ISCSI, home, home);
    iscsi_sem = sem_alloc(1, IPC_MUTEX_SEMAPHORE);
}
Esempio n. 14
0
//!
//!
//!
//! @param[in] require_grub FALSE = not required, TRUE = required
//!
//! @return EUCA_OK on success or EUCA_ERROR on failure
//!
int diskutil_init()
{
   int ret = EUCA_OK;
   int missing_handlers = 0;
   if (!initialized) {
        bzero(helpers_path, sizeof(helpers_path));
        missing_handlers = verify_helpers(helpers, helpers_path, LASTHELPER);
        if (missing_handlers) {
            for (int i = 0; i < LASTHELPER; i++) {
                if (helpers_path[i] == NULL) {
                    LOGERROR("ERROR: missing a required handler: %s\n", helpers[i]);
                    ret = EUCA_ERROR;
                }
            }
        }
        if (loop_sem == NULL)
            loop_sem = sem_alloc(1, IPC_MUTEX_SEMAPHORE);
        initialized = 1;
    }
    return (ret);
}
Esempio n. 15
0
//!
//! Initialize the backing store. Called during initialization of node controller.
//!
//! @param[in] conf_instances_path path to where the instances information are stored
//! @param[in] conf_work_size_mb the work blobstore size limit in MB (if 0 then unlimitted)
//! @param[in] conf_cache_size_mb the cache blobstore size limit in MB (if 0 then cache isn't used)
//!
//! @return EUCA_OK on success or the following error codes:
//!         \li EUCA_INVALID_ERROR: if any parameter does not meet the preconditions
//!         \li EUCA_ACCESS_ERROR: if we fail to access our cache and work directories
//!         \li EUCA_PERMISSION_ERROR: if we fail to create the cache or work stores.
//!
//! @pre The conf_instances_path field must not be NULL
//!
//! @post On success, the backing store module is initialized and the following happened:
//!       \li our global instance_path variable is set with the given conf_instance_path
//!       \li the work blobstore is created and our global work_bs variable is set
//!       \li the cache blobstore is created if necessary and the cache_bs variable is set
//!       \li the disk semaphore is created if necessary
//!
int init_backing_store(const char *conf_instances_path, unsigned int conf_work_size_mb, unsigned int conf_cache_size_mb)
{
    char cache_path[EUCA_MAX_PATH] = "";
    char work_path[EUCA_MAX_PATH] = "";
    unsigned long long cache_limit_blocks = 0;
    unsigned long long work_limit_blocks = 0;
    blobstore_snapshot_t snapshot_policy = BLOBSTORE_SNAPSHOT_ANY;

    LOGINFO("initializing backing store...\n");

    // Make sure we have a valid intance path passed to us
    if (conf_instances_path == NULL) {
        LOGERROR("INSTANCE_PATH not specified\n");
        return (EUCA_INVALID_ERROR);
    }
    // Set our global instance_path variable with the content of conf_instance_path
    euca_strncpy(instances_path, conf_instances_path, sizeof(instances_path));
    if (check_directory(instances_path)) {
        LOGERROR("INSTANCE_PATH (%s) does not exist!\n", instances_path);
        return (EUCA_ACCESS_ERROR);
    }
    // Check if our cache path exist. If not it should get crated
    snprintf(cache_path, sizeof(cache_path), "%s/cache", instances_path);
    if (ensure_directories_exist(cache_path, 0, NULL, NULL, BACKING_DIRECTORY_PERM) == -1)
        return (EUCA_ACCESS_ERROR);

    // Check if our work path exist. If not it should get crated
    snprintf(work_path, sizeof(work_path), "%s/work", instances_path);
    if (ensure_directories_exist(work_path, 0, NULL, NULL, BACKING_DIRECTORY_PERM) == -1)
        return (EUCA_ACCESS_ERROR);

    // convert MB to blocks
    cache_limit_blocks = (unsigned long long)conf_cache_size_mb *2048;
    work_limit_blocks = (unsigned long long)conf_work_size_mb *2048;

    // we take 0 as unlimited
    if (work_limit_blocks == 0) {
        work_limit_blocks = ULLONG_MAX;
    }
    // by default we let blobstore pick the snapshot policy, which
    // will use device mapper if available, which is faster than copying
    snapshot_policy = BLOBSTORE_SNAPSHOT_ANY;
    if (nc_state.disable_snapshots) {
        LOGINFO("if allocating storage, will avoid using snapshots\n");
        snapshot_policy = BLOBSTORE_SNAPSHOT_NONE;
    }
    // Set the backing store error callback function
    blobstore_set_error_function(&bs_errors);

    // Do we need to create a cache blobstore
    if (cache_limit_blocks) {
        cache_bs = blobstore_open(cache_path, cache_limit_blocks, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_DIRECTORY, BLOBSTORE_REVOCATION_LRU, snapshot_policy);
        if (cache_bs == NULL) {
            LOGERROR("failed to open/create cache blobstore: %s\n", blobstore_get_error_str(blobstore_get_error()));
            return (EUCA_PERMISSION_ERROR);
        }
    }
    // Lets open the work blobstore
    work_bs = blobstore_open(work_path, work_limit_blocks, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_FILES, BLOBSTORE_REVOCATION_NONE, snapshot_policy);
    if (work_bs == NULL) {
        LOGERROR("failed to open/create work blobstore: %s\n", blobstore_get_error_str(blobstore_get_error()));
        LOGERROR("%s\n", blobstore_get_last_trace());
        BLOBSTORE_CLOSE(cache_bs);
        return (EUCA_PERMISSION_ERROR);
    }
    // set the initial value of the semaphore to the number of
    // disk-intensive operations that can run in parallel on this node
    if (nc_state.concurrent_disk_ops && ((disk_sem = sem_alloc(nc_state.concurrent_disk_ops, IPC_MUTEX_SEMAPHORE)) == NULL)) {
        LOGERROR("failed to create and initialize disk semaphore\n");
        return (EUCA_PERMISSION_ERROR);
    }

    return (EUCA_OK);
}
Esempio n. 16
0
void initMutexes(int nb, unsigned short val) {
	sem_alloc(nb);
	sem_init(nb, val);
}
Esempio n. 17
0
static int init (void)
{
	static int initialized = 0;
	int do_warn = 0, i;
	char configFiles[2][MAX_PATH],
		log[MAX_PATH],
		*bridge,
		*hypervisor,
		*s,
	       	*tmp;
	struct stat mystat;
	struct statfs fs;
	struct handlers ** h; 
	long long fs_free_blocks = 0;
	long long fs_block_size  = 0;
	long long instances_bytes = 0;
	pthread_t tcb;

	if (initialized>0) /* 0 => hasn't run, -1 => failed, 1 => ok */
		return 0;
	else if (initialized<0)
		return 1;

	bzero (&nc_state, sizeof(struct nc_state_t)); // ensure that MAXes are zeroed out

	/* from now on we have unrecoverable failure, so no point in
	 * retrying to re-init */
	initialized = -1;

	/* read in configuration - this should be first! */
	tmp = getenv(EUCALYPTUS_ENV_VAR_NAME);
	if (!tmp) {
		nc_state.home[0] = '\0';
		do_warn = 1;
	} else 
		strncpy(nc_state.home, tmp, MAX_PATH);

	/* set the minimum log for now */
	snprintf(log, MAX_PATH, "%s/var/log/eucalyptus/nc.log", nc_state.home);
	logfile(log, EUCADEBUG);

	if (do_warn) 
		logprintfl (EUCAWARN, "env variable %s not set, using /\n", EUCALYPTUS_ENV_VAR_NAME);

	/* search for the config file */
	snprintf(configFiles[1], MAX_PATH, EUCALYPTUS_CONF_LOCATION, nc_state.home);
	if (stat(configFiles[1], &mystat)) {
		logprintfl (EUCAFATAL, "could not open configuration file %s\n", configFiles[1]);
		return 1;
	}
	snprintf(configFiles[0], MAX_PATH, EUCALYPTUS_CONF_OVERRIDE_LOCATION, nc_state.home);

	logprintfl (EUCAINFO, "NC is looking for configuration in %s,%s\n", configFiles[1], configFiles[0]);

	/* reset the log to the right value */
	tmp = getConfString(configFiles, 2, "LOGLEVEL");
	i = EUCADEBUG;
	if (tmp) {
		if (!strcmp(tmp,"INFO")) {i=EUCAINFO;}
		else if (!strcmp(tmp,"WARN")) {i=EUCAWARN;}
		else if (!strcmp(tmp,"ERROR")) {i=EUCAERROR;}
		else if (!strcmp(tmp,"FATAL")) {i=EUCAFATAL;}
		free(tmp);
	}
	logfile(log, i);

#define GET_VAR_INT(var,name) \
        s = getConfString(configFiles, 2, name); \
	if (s){					\
		var = atoi(s);\
		free (s);\
	}

	GET_VAR_INT(nc_state.config_max_mem,      CONFIG_MAX_MEM);
	GET_VAR_INT(nc_state.config_max_disk,     CONFIG_MAX_DISK);
	GET_VAR_INT(nc_state.config_max_cores,    CONFIG_MAX_CORES);
	GET_VAR_INT(nc_state.save_instance_files, CONFIG_SAVE_INSTANCES);

	nc_state.config_network_port = NC_NET_PORT_DEFAULT;
	strcpy(nc_state.admin_user_id, EUCALYPTUS_ADMIN);

	hyp_sem = sem_alloc (1, "mutex");
	inst_sem = sem_alloc (1, "mutex");
	addkey_sem = sem_alloc (1, "mutex");
	if (!hyp_sem || !inst_sem) {
		logprintfl (EUCAFATAL, "failed to create and initialize a semaphore\n");
		return ERROR_FATAL;
	}

	/* set default in the paths. the driver will override */
	nc_state.config_network_path[0] = '\0';
	nc_state.gen_libvirt_cmd_path[0] = '\0';
	nc_state.xm_cmd_path[0] = '\0';
	nc_state.virsh_cmd_path[0] = '\0';
	nc_state.get_info_cmd_path[0] = '\0';
	snprintf (nc_state.rootwrap_cmd_path, MAX_PATH, EUCALYPTUS_ROOTWRAP, nc_state.home);

	/* prompt the SC to read the configuration too */
	if (scInitConfig()) {
		logprintfl (EUCAFATAL, "ERROR: scInitConfig() failed\n");
		return ERROR_FATAL;
	}

	/* determine the hypervisor to use */
	
	//if (get_conf_var(config, CONFIG_HYPERVISOR, &hypervisor)<1) {
	hypervisor = getConfString(configFiles, 2, CONFIG_HYPERVISOR);
	if (!hypervisor) {
		logprintfl (EUCAFATAL, "value %s is not set in the config file\n", CONFIG_HYPERVISOR);
		return ERROR_FATAL;
	}

	/* let's look for the right hypervisor driver */
	for (h = available_handlers; *h; h++ ) {
		if (!strncmp ((*h)->name, "default", CHAR_BUFFER_SIZE))
			nc_state.D = *h; 
		if (!strncmp ((*h)->name, hypervisor, CHAR_BUFFER_SIZE))
			nc_state.H = *h; 
	}
	if (nc_state.H == NULL) {
		logprintfl (EUCAFATAL, "requested hypervisor type (%s) is not available\n", hypervisor);
		free (hypervisor);
		return ERROR_FATAL;
	}
	
	/* only load virtio config for kvm */
	if (!strncmp("kvm", hypervisor, CHAR_BUFFER_SIZE) ||
		!strncmp("KVM", hypervisor, CHAR_BUFFER_SIZE)) {
		GET_VAR_INT(nc_state.config_use_virtio_net, CONFIG_USE_VIRTIO_NET);
		GET_VAR_INT(nc_state.config_use_virtio_disk, CONFIG_USE_VIRTIO_DISK);
		GET_VAR_INT(nc_state.config_use_virtio_root, CONFIG_USE_VIRTIO_ROOT);
	}

	free (hypervisor);

	/* NOTE: this is the only call which needs to be called on both
	 * the default and the specific handler! All the others will be
	 * either or */
	i = nc_state.D->doInitialize(&nc_state);
	if (nc_state.H->doInitialize)
		i += nc_state.H->doInitialize(&nc_state);
	if (i) {
		logprintfl(EUCAFATAL, "ERROR: failed to initialized hypervisor driver!\n");
		return ERROR_FATAL;
	}

	/* adopt running instances */
	adopt_instances();

	/* setup the network */
	nc_state.vnetconfig = malloc(sizeof(vnetConfig));
	if (!nc_state.vnetconfig) {
		logprintfl (EUCAFATAL, "Cannot allocate vnetconfig!\n");
		return 1;
	}
	snprintf (nc_state.config_network_path, MAX_PATH, NC_NET_PATH_DEFAULT, nc_state.home);
	hypervisor = getConfString(configFiles, 2, "VNET_PUBINTERFACE");
	if (!hypervisor) 
		hypervisor = getConfString(configFiles, 2, "VNET_INTERFACE");
	bridge = getConfString(configFiles, 2, "VNET_BRIDGE");
	tmp = getConfString(configFiles, 2, "VNET_MODE");
	
	vnetInit(nc_state.vnetconfig, tmp, nc_state.home, nc_state.config_network_path, NC, hypervisor, hypervisor, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, bridge, NULL, NULL);
	if (hypervisor) free(hypervisor);
	if (bridge) free(bridge);
	if (tmp) free(tmp);

	/* cleanup from previous runs and verify integrity of
	 * instances directory */
	sem_p (inst_sem);
	instances_bytes = scFSCK (&global_instances);
	sem_v (inst_sem);
	if (instances_bytes < 0) {
		logprintfl (EUCAFATAL, "instances store failed integrity check (error=%lld)\n", instances_bytes);
		return ERROR_FATAL;
	}
	
	/* get disk max */
	strncpy(log, scGetInstancePath(), MAX_PATH);

	if (statfs(log, &fs) == -1) {
		logprintfl(EUCAWARN, "Failed to stat %s\n", log);
	}  else {
		nc_state.disk_max = (long long)fs.f_bsize * (long long)fs.f_bavail + instances_bytes; /* max for Euca, not total */
		nc_state.disk_max /= BYTES_PER_DISK_UNIT;
		if (nc_state.config_max_disk && nc_state.config_max_disk < nc_state.disk_max)
			nc_state.disk_max = nc_state.config_max_disk;

		logprintfl (EUCAINFO, "Maximum disk available: %lld (under %s)\n", nc_state.disk_max, log);
	}

	/* start the monitoring thread */
	if (pthread_create(&tcb, NULL, monitoring_thread, &nc_state)) {
		logprintfl (EUCAFATAL, "failed to spawn a monitoring thread\n");
		return ERROR_FATAL;
	}
        if (pthread_detach(tcb)) {
          logprintfl(EUCAFATAL, "failed to detach the monitoring thread\n");
          return ERROR_FATAL;
        }


	initialized = 1;

	return OK;
}
Esempio n. 18
0
static void
tftpd_server(cyg_addrword_t p)
{
    struct tftp_server *server = (struct tftp_server *)p;
    int max_s = 0;
    int data_len, recv_len;
    socklen_t from_len;
    struct sockaddr from_addr;
    char data[SEGSIZE+sizeof(struct tftphdr)];
    struct tftphdr *hdr = (struct tftphdr *)data;
    struct addrinfo hints;
    struct addrinfo *ai;
    fd_set readfds;
    char name[64];
    int error;
    int i;
#ifdef CYGOPT_NET_TFTP_SERVER_INSTRUMENT
    struct info o = tftp_server_instrument;
#endif
    
#ifndef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS
    // Otherwise routine printfs fail the test - interrupts disabled too long.
    diag_printf("TFTPD [%x]: port %d\n", p, server->port);
#endif

    memset(&hints,0,sizeof(hints));
    hints.ai_family = PF_UNSPEC;
    hints.ai_flags = AI_PASSIVE;

    error = getaddrinfo(NULL,"tftp",&hints, &server->res);
    if (0 != error) {
      diag_printf("TFTPD [%d] : can't get a local server address to bind to: %s\n",
		  p, gai_strerror(error));
      return;
    }
 
    // If the port is 0, we need to use the default TFTP port. Extrace
    // the port number from one of the addresses returned by
    // getaddrinfo.
    if (server->port == 0) {
      switch (server->res->ai_family) {
      case AF_INET: 
	{
	  struct sockaddr_in *addr = (struct sockaddr_in *)server->res->ai_addr;
	  server->port = ntohs(addr->sin_port);
	  break;
	}
#ifdef CYGPKG_NET_INET6
      case AF_INET6:
	{
	  struct sockaddr_in6 *addr = (struct sockaddr_in6 *)server->res->ai_addr;
	  server->port = ntohs(addr->sin6_port);
	  break;
	}
#endif
      default:
	break;
      }
    }

#ifdef CYGSEM_NET_TFTPD_MULTITHREADED   
    sem_alloc(server->port);
    while (true) {
#endif
      // Iterate over the addresses and create a local port to listen for requests 
      ai = server->res;
      memset(server->s,0,sizeof(server->s));
      server->num_s = 0;
#ifdef CYGSEM_NET_TFTPD_MULTITHREADED   
      sem_wait(server->port);
#endif
      while (ai && (server->num_s < CYGNUM_NET_MAX_INET_PROTOS)) {
	server->s[server->num_s] = socket(ai->ai_family, 
					  ai->ai_socktype, 
					  ai->ai_protocol);
	if (server->s[server->num_s] < 0 ) {
	  diag_printf("TFTPD [%x]: can't open socket\n", p);
	  freeaddrinfo(server->res);
	  server->res = NULL;
	  return;
	}
	
	set_port(ai->ai_addr, server->port);
	
	if (bind(server->s[server->num_s],ai->ai_addr, ai->ai_addrlen) < 0) {
	  // Problem setting up my end
	  diag_printf("TFTPD [%x]: can't bind to server port\n",p);
	  close(server->s[server->num_s]);
	  server->s[server->num_s] = 0;
	  ai = ai->ai_next;
	  continue;
	}
	// We need to know the highest socket number for select.
	if (server->s[server->num_s] > max_s)
	  max_s = server->s[server->num_s];
	server->num_s++;
	ai = ai->ai_next;
      }
      
#ifndef CYGSEM_NET_TFTPD_MULTITHREADED   
      while (true) {
#endif
	FD_ZERO(&readfds);
	for (i=0; i < CYGNUM_NET_MAX_INET_PROTOS; i++) {
	  if (server->s[i]) {
	    FD_SET(server->s[i],&readfds);
	  }
	}
	error = select(max_s+1,&readfds,NULL,NULL,NULL);
	if ( -1 == error) {
	  diag_printf("TFTPD [%x]: error in select\n",p);
	}
	for (i=0; i < CYGNUM_NET_MAX_INET_PROTOS; i++) {
	  if (server->s[i] && FD_ISSET(server->s[i],&readfds)) {
	    recv_len = sizeof(data);
	    from_len = sizeof(from_addr);
	    data_len = recvfrom(server->s[i], hdr, recv_len, 0,
				&from_addr, &from_len);
	    if ( data_len < 0) {
	      diag_printf("TFTPD [%x]: can't read request\n", p);
	    } else {
#ifdef CYGSEM_NET_TFTPD_MULTITHREADED   
	      // Close the socket and post on the semaphore some
	      // another thread can start listening for requests. This
	      // is not quite right. select could of returned with more than
	      // one socket with data to read. Here we only deal with one of them 
	      for (i=0; i < CYGNUM_NET_MAX_INET_PROTOS; i++) {
		if (server->s[i]) {
		  close (server->s[i]);
		  server->s[i] = 0;
		}
	      }
	      sem_post(server->port);
#endif
#ifndef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS
	      getnameinfo(&from_addr,sizeof(from_addr), name, sizeof(name),0,0,0);
	      diag_printf("TFTPD [%x]: received %x from %s\n", p,
			  ntohs(hdr->th_opcode), name);
#endif
	      switch (ntohs(hdr->th_opcode)) {
	      case WRQ:
		tftpd_write_file(server, hdr, &from_addr, from_len);
		break;
	      case RRQ:
		tftpd_read_file(server, hdr, &from_addr, from_len);
		break;
	      case ACK:
	      case DATA:
	      case ERROR:
		// Ignore
		break;
	      default:
		getnameinfo(&from_addr,sizeof(from_addr), name, sizeof(name),0,0,0);
		diag_printf("TFTPD [%x]: bogus request %x from %s\n", p,
			    ntohs(hdr->th_opcode),
			    name);
		tftpd_send_error(server->s[i],hdr,TFTP_EBADOP,&from_addr,from_len);
	      }
	      
#ifdef CYGOPT_NET_TFTP_SERVER_INSTRUMENT
	      tftp_server_instrument.total_transactions++;
	      
	      o.data.rx        -= tftp_server_instrument.data.rx       ;
	      o.data.rx_repeat -= tftp_server_instrument.data.rx_repeat;
	      o.data.rx_skip   -= tftp_server_instrument.data.rx_skip  ;
	      o.data.send      -= tftp_server_instrument.data.send     ;
	      o.data.resend    -= tftp_server_instrument.data.resend   ;
	      
	      o.ack.rx         -= tftp_server_instrument.ack.rx        ;
	      o.ack.rx_repeat  -= tftp_server_instrument.ack.rx_repeat ;
	      o.ack.rx_skip    -= tftp_server_instrument.ack.rx_skip   ;
	      o.ack.send       -= tftp_server_instrument.ack.send      ;
	      o.ack.resend     -= tftp_server_instrument.ack.resend    ;
	      
	      o.err_send       -= tftp_server_instrument.err_send      ;
	      
#ifndef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS
	      if ( o.data.rx        ) diag_printf( "data rx       %4d\n", -o.data.rx        );
	      if ( o.data.rx_repeat ) diag_printf( "data rx_repeat%4d\n", -o.data.rx_repeat );
	      if ( o.data.rx_skip   ) diag_printf( "data rx_skip  %4d\n", -o.data.rx_skip   );
	      if ( o.data.send      ) diag_printf( "data send     %4d\n", -o.data.send      );
	      if ( o.data.resend    ) diag_printf( "data resend   %4d\n", -o.data.resend    );
	      
	      if ( o.ack.rx         ) diag_printf( " ack rx       %4d\n", -o.ack.rx         );
	      if ( o.ack.rx_repeat )  diag_printf( " ack rx_repeat%4d\n", -o.ack.rx_repeat  );
	      if ( o.ack.rx_skip   )  diag_printf( " ack rx_skip  %4d\n", -o.ack.rx_skip    );
	      if ( o.ack.send      )  diag_printf( " ack send     %4d\n", -o.ack.send       );
	      if ( o.ack.resend    )  diag_printf( " ack resend   %4d\n", -o.ack.resend     );
	      
	      if ( o.err_send      )  diag_printf( "*error sends  %4d\n", -o.err_send      );
#endif // CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS
#endif // CYGOPT_NET_TFTP_SERVER_INSTRUMENT
#ifdef CYGSEM_NET_TFTPD_MULTITHREADED
	      break;
#endif
	    }
	  }
	}
	// The following looks a little strange, but it keeps emacs's
	// auto indention happy.
#ifndef CYGSEM_NET_TFTPD_MULTITHREADED   
      }
#endif
#ifdef CYGSEM_NET_TFTPD_MULTITHREADED   
    }
#endif
}
Esempio n. 19
0
void *mutexCreate() { // TODO implementing TODO
    struct semaphore *sem = mm_malloc(sizeof(struct semaphore),0);

    sem_alloc(sem, 1);
    return sem;
}