/*******************************************************************
 * Function to cleanup provider specific resource, this function is
 * called at various places in Xen_ProviderGeneric.c
 *
 * @param resources - handle to the provider_resource_list to be
 *    be cleaned up. Clean up the provider specific part of the
 *    resource.
 * @return CMPIrc error codes
 *******************************************************************/
static CMPIrc xen_resource_list_cleanup(
    provider_resource_list *resources
    )
{
    if (resources && resources->ctx)
        xen_host_set_free((xen_host_set *)resources->ctx);
    return CMPI_RC_OK;
}
Beispiel #2
0
// automatically generated. Do not modify
static void testHosts(xen_session *session) {
	printf("\nGet all the  Host Records\n");

	xen_host_set *host_set;
	bool d = xen_host_get_all(session, &host_set);
	if (d) {
		size_t i = 0;
		for (; i < host_set->size; ++i) {
			xen_host_record *host_record;
			xen_host_get_record(session, &host_record, host_set->contents[i]);
			char *handle = (char*) host_record->handle;
			char *opaque = (char*) host_set->contents[i];
			if (strcmp(handle, opaque) == 0)
				printf("identical: %s\n", opaque);
			else
				printf("record->handle[%s] v.s. set->contents[%d][%s]\n",
						opaque, i, handle);
			xen_host_record_free(host_record);
		}
	} else {
		print_error(session);
	}

#if 0
	printf("== Get All ============================\n\n");

	xen_host_xen_host_record_map *result;
	bool ok = xen_host_get_all_records(session, &result);
	if(!ok) {
		print_error(session);
	}
	size_t i=0;
	for(;i<result->size;++i) {
		xen_host key = result->contents[i].key;
		struct xen_host_record *val = result->contents[i].val;
		if(strcmp((char*)key, (char*)val->handle)==0) {

		} else {
			printf("%s v.s. %s", (char*)key, (char*)val->handle);
		}
		xen_host_record_free(val);
		xen_host_free(key);
	}
	free(result);
#endif
	xen_host_set_free(host_set);

	printf("\n==============================================\n\n");
}
static int get_host_names(xen_session *session, 
        xen_host_set **hosts_address, char* source_url )
{
    int rc = -1; // failed but nothing to free
    if (xen_host_get_by_name_label(session, hosts_address, source_url))
    {
      if (((*hosts_address)->size) > 1)
      {
          rc = 1;  // greater than 1; an error but will free
          xen_host_set_free(*hosts_address);
      }
      else rc = 0; // size must be = 1
    }
    return rc;
}
/******************************************************************************
* checks for migratability or actually does the migration
******************************************************************************/
int MigrateVirtualSystem(
    const CMPIBroker *broker,   /* in - CMPI Broker that does most of the work */
    const CMPIContext *context, /* in - CMPI context for the caller */
    const CMPIArgs *argsin,     /* in - All the arguments for the method */
    const CMPIArgs *argsout,    /* out - All the output arguments for the method */
    xen_utils_session *session, /* in - Session for making xen calls */
    bool host_ip,               /* in - The host parameter is an IP address */
    bool migrate_check_only,    /* in -Check if migration is possible only, dont actually migrate */
    CMPIStatus *status)         /* out - Report CMPI status of method */
{
    char *hostid = NULL, *vm_uuid = NULL;
    CMPIData argdata;
    xen_vm vm = NULL;
    xen_host_set *host_set = NULL;
    CMPIInstance *msd = NULL;
    xen_host host = NULL;
    int rc = Xen_VirtualSystemMigrationService_MigrateVirtualSystemToSystem_Invalid_Parameter;
    CMPIrc statusrc = CMPI_RC_ERR_INVALID_PARAMETER;
    char *error_msg = "ERROR: Unknown error";
    xen_string_string_map *other_config=NULL;

    /* For now only Live migrations are supported */
    if(_GetArgument(broker, argsin, "MigrationSettingData", CMPI_chars, &argdata, status)) {
        /* Argument passed in as a MOF string, parse it */
        msd = xen_utils_parse_embedded_instance(broker, CMGetCharPtr(argdata.value.string));
        if (msd == NULL) { // parser returns zero for success, non-zero for error
            error_msg = "ERROR: Couldnt parse the 'MigrationSettingData' parameter";
            goto Exit;
        }
    }
    else
        /* Argument could have been passed in as an intance */
        if(_GetArgument(broker, argsin, "MigrationSettingData", CMPI_instance, &argdata, status))
            msd = argdata.value.inst;

    if(msd != NULL) {
        CMPIData data = CMGetProperty(msd, "MigrationType", status);
        if(data.value.uint16 != Xen_VirtualSystemMigrationSettingData_MigrationType_Live) {
            error_msg = "ERROR: 'MigrationSettingData' contains an invalid MigrationType (Live expected)";
            goto Exit;
        }
    }

    /* Host to migrate to */
    if(!host_ip) {
        /* required parameters */
        if(!_GetArgument(broker, argsin, "DestinationSystem", CMPI_ref, &argdata, status)){
            error_msg = "ERROR: 'DestionationSystem' parameter is missing";
            goto Exit;
        }
        else {
            /* This is the CIM reference to an existing Host object */
            CMPIData key;
            key = CMGetKey(argdata.value.ref, "Name", status);
            if(status->rc != CMPI_RC_OK || CMIsNullValue(key)) {
                error_msg = "ERROR: 'DestinationSystem' is missing the required 'Name' key";
                goto Exit;
            }
            hostid = CMGetCharPtr(key.value.string);
            if(!xen_host_get_by_uuid(session->xen, &host, hostid)) 
                goto Exit;
        }
    }
    else {
        if(!_GetArgument(broker, argsin, "DestinationHost", CMPI_string, &argdata, status)) {
            error_msg = "ERROR: 'DestinationHost' parameter is missing";
            goto Exit;
        }
        else {
            /* Determing Xen host based on IP address,. Cannot use inet_pton() and so on since DNS may not have been configured properly */
            hostid = CMGetCharPtr(argdata.value.string);
            _SBLIM_TRACE(_SBLIM_TRACE_LEVEL_INFO, ("Trying to migrate to DestinationHost : %s", hostid));
            if(!xen_host_get_all(session->xen, &host_set))
                goto Exit;
            int i=0;
            for (i=0; i<host_set->size; i++) {
                xen_host_record *host_rec = NULL;
                if(!xen_host_get_record(session->xen, &host_rec, host_set->contents[i]))
                    goto Exit;
                /* DestinationHost could be an IP address or the hostname */
                if((host_rec->address &&  (strcmp(hostid, host_rec->address) == 0)) || 
                   (host_rec->hostname && (strcmp(hostid, host_rec->hostname) == 0)) ||
                   (host_rec->name_label && (strcmp(hostid, host_rec->name_label) == 0))) { 
                    xen_host_record_free(host_rec);
                    host = host_set->contents[i];
                    host_set->contents[i] = NULL; /* dont free this one */
                    break;
                }
                xen_host_record_free(host_rec);
            }
        }
    }

    /* VM to migrate - required parameter */
    if(!_GetArgument(broker, argsin, "ComputerSystem", CMPI_ref, &argdata, status)) {
        if(!_GetArgument(broker, argsin, "ComputerSystem", CMPI_string, &argdata, status)) {
            error_msg = "ERROR: Missing the required 'ComputerSystem' parameter";
            goto Exit;
        }
        else
            vm_uuid = CMGetCharPtr(argdata.value.string);
    } else {
        argdata = CMGetKey(argdata.value.ref, "Name", status);
        if(status->rc != CMPI_RC_OK || CMIsNullValue(argdata)) {
            error_msg = "ERROR: ComputerSystem is missing the required 'Name' key";
            goto Exit;
        }
        vm_uuid = CMGetCharPtr(argdata.value.string);
    }
    status->rc = CMPI_RC_ERR_FAILED;
    rc = Xen_VirtualSystemMigrationService_MigrateVirtualSystemToSystem_Failed;
    if(xen_vm_get_by_uuid(session->xen, &vm, vm_uuid)) {
        _SBLIM_TRACE(_SBLIM_TRACE_LEVEL_ERROR, ("Migrating %s to %s", vm_uuid, hostid));
        if(migrate_check_only) {
            /* Check to see if migration is possible */
            statusrc = CMPI_RC_OK;
            rc = Xen_VirtualSystemMigrationService_MigrateVirtualSystemToSystem_Completed_with_No_Error;
            bool migratable = xen_vm_assert_can_boot_here(session->xen, vm, host);
            if(migratable == false || !session->xen->ok) {
                migratable = false;

                // Workaround for kvp migration
                if(session->xen->error_description_count==1) {
                    if(xen_vm_get_other_config(session->xen, &other_config, vm)) {
                         if(xen_utils_get_from_string_string_map(other_config, "kvp_enabled")) {
                            _SBLIM_TRACE(_SBLIM_TRACE_LEVEL_INFO, ("Overwriting migratable to mark kvp vm as migratable, although its network"));
                            migratable=true;
                            RESET_XEN_ERROR(session->xen);
                         }
                         free(other_config);
                    } else {
                       _SBLIM_TRACE(_SBLIM_TRACE_LEVEL_ERROR, ("Could not get other config."));
                    }
                }

                if(migratable == false && session->xen->error_description) {
                    /* This is not part of the MOF (and is not documented), but nice to have */
                    char *xen_error = xen_utils_get_xen_error(session->xen);
                    CMAddArg(argsout, "Reason", (CMPIValue *)xen_error, CMPI_chars);
                    free(xen_error);
                }
            }
            CMAddArg(argsout, "IsMigratable", (CMPIValue *)&migratable, CMPI_boolean);
        }
        else {
            /* Do the actual migration, this could take a few minutes */
            CMPIObjectPath* job_instance_op = NULL;
            migrate_job_context *job_context = calloc(1, sizeof(migrate_job_context));
            if(!job_context) {
                error_msg = "ERROR: Couldn't allocate memory for the migrate job.";
                goto Exit;
            }
            job_context->vm = vm;
            job_context->host = host;
            if(!job_create(broker, context, session, MIGRATE_VM_TASK_NAME, vm_uuid, 
                           migrate_task, job_context, &job_instance_op, status)) {
                error_msg = "ERROR: Couldn't prepare the Migrate job. Job wasnt started.";
                goto Exit;
            }
            statusrc = CMPI_RC_OK;
            rc = Xen_VirtualSystemMigrationService_MigrateVirtualSystemToHost_Method_Parameters_Checked___Job_Started;
            CMAddArg(argsout, "Job", (CMPIValue *)&job_instance_op, CMPI_ref);
            vm = NULL;      /* freed by async thread */
            host = NULL;    /* freed by async thread */
        }
    }

Exit:
    if(host)
        xen_host_free(host);
    if(vm)
        xen_vm_free(vm);
    if(host_set)
        xen_host_set_free(host_set);

    xen_utils_set_status(broker, status, statusrc, error_msg, session->xen);
    return rc;
}
int main(int argc, char **argv)
{

    if (argc != 6)
    {
        usage();
    }

    url = argv[1];
    char *username = argv[2];
    char *password = argv[3];
    
    source_url = argv[4];
    target_url = argv[5];

    xmlInitParser();
    xmlKeepBlanksDefault(0);
    xen_init();
    curl_global_init(CURL_GLOBAL_ALL);

#define CLEANUP                                 \
    do {                                        \
        xen_session_logout(session);            \
        curl_global_cleanup();                  \
        xen_fini();                             \
        xmlCleanupParser();                     \
    } while(0)                                  \

    
    xen_session *session =
        xen_session_login_with_password(call_func, NULL, username, password,
                                        xen_api_latest_version);

    printf("\n\nQuerying host...\n");
    xen_host host;
    if (!xen_session_get_this_host(session, &host, session))
    {
        print_error(session);
        CLEANUP;
        return 1;
    }
    
    /* Read in the source host and target host using their name labels
     */
    xen_host_set *source_hosts;
    
    int rc = 0;
 
    rc = get_host_names(session, &source_hosts, source_url );
    if (rc !=0 )
    {
        fprintf(stderr, "source host lookup failed.\n");
	print_error(session);
        return 1;
    }
    
    
    xen_host_set *target_hosts;
    rc = 0;
    rc = get_host_names(session, &target_hosts, target_url );
    if (rc !=0 )
    {
        fprintf(stderr, "target host lookup failed.\n");
	print_error(session);
        return 1;
    }
    
            
    struct xen_vm_set *all_vms_in_pool;
    xen_vm_get_all(session, &all_vms_in_pool);
    
    
    bool *vm_to_be_migrated = calloc(all_vms_in_pool->size, sizeof(bool));
    int num_vms_to_migrate = 0;
    enum xen_task_status_type task_status;
   
    xen_vm_record* result;
    
    for (size_t i = 0; i < all_vms_in_pool->size; i++ )
    {
        xen_vm a_vm = all_vms_in_pool->contents[i];
        xen_vm_get_record(session, &result, a_vm);
        
        /*
         * we can only migrate VMs that are
         * -not templates 
         * -not control domains
         * -and are running 
         * 
         * resident_on is used to identify the eligible VMs on the user
         * requested source_host 
         */
        
        if ( !result->is_a_template 
              && !result->is_control_domain
              && (result->power_state ==  XEN_VM_POWER_STATE_RUNNING)
              && (strcmp(result->resident_on->u.handle, 
                         (char*)source_hosts->contents[0]) == 0) )
        {
            // flag this VM as one suitable to migrate
            vm_to_be_migrated[i] = true;
            num_vms_to_migrate++; 
        }
        else 
        {
            vm_to_be_migrated[i] = false;
        }
    }
   
    
    if (!session->ok)
    {
        /* Error has been logged, just clean up. */
        xen_host_set_free(source_hosts);
        xen_host_set_free(target_hosts);
        xen_vm_set_free(all_vms_in_pool);       
        xen_vm_record_free(result);
        free(vm_to_be_migrated);
        CLEANUP;
        return 1;
    }

    xen_task* task_list = calloc(num_vms_to_migrate, sizeof(xen_task));
    xen_string_string_map* options = xen_string_string_map_alloc(0);    
    xen_string_set *error_msgs = NULL;
    
    int idx = 0;
    for (size_t i = 0; i < all_vms_in_pool->size; i++ )
    {
     
        if (vm_to_be_migrated[i] == true)
        {
            xen_vm_pool_migrate_async(session, &task_list[idx], all_vms_in_pool->contents[i], 
                                        target_hosts->contents[0], options );
            
            idx++;
            printf(" Migrating VM %zd \n", i);
        }
    
    }
    
    // time out after certain number of iterations
    int max_iter = 50; 
    int iter = 0;
    int pause_interval_secs = 4;
    int tasks_running = 0;
    int tasks_completed = 0;
    xen_task a_task;
    bool tasks_still_pending = true;

    /* Poll how many of the migration tasks have completed. 
     * 
     * The task querying below isn't is intended to provide a sample of useful 
     * syntax. In practice a user would probably consider using functions such 
     * as xen_task_cancel or indeed the asynchronous equivalent 
     * xen_task_cancel_async.
     * These functions and other task handling ones are defined in xen_task.c
     */
    
    while ( iter < max_iter && tasks_still_pending )
    {
        tasks_running = 0;
        tasks_completed = 0;
        for (int j = 0; j < num_vms_to_migrate; j++)
        {
            a_task = task_list[j];
           
            xen_task_get_status(session, &task_status, a_task);
            
            if (task_status == XEN_TASK_STATUS_TYPE_PENDING)
            {
                tasks_running++;
            }
            else
            {
                /* See the xen_task_status_type enum definitions
                 * defined in xen_task_status_type.h a task can have
                 * failed, or be cancelled or in the process of being cancelled
                 * amongst others.
                 * The definition of tasks_completed in this context is tasks
                 * not pending.
                 */
                           
                if (task_status == XEN_TASK_STATUS_TYPE_FAILURE)
                {
                    if (xen_task_get_error_info(session, &error_msgs, task_list[j] ))
                    {
                        /* VMs may need to meet certain criteria for migration to be 
                         * possible between hosts; such as shared storage between
                         * hosts. It is advisable to check the criteria needed for 
                         * migration on the particular version of XenServer. 
                         * The error messages output below should give information
                         * that allows the identification of an unsupported
                         * operation
                         */
                        printf("-------------------------------------\n");
                        printf("Failed while trying to migrate VM: \n");
                        for(size_t k=0; k<error_msgs->size; k++)
                        {
                            printf("error_msg %zu : %s \n",  k, error_msgs->contents[k]); 
                        }
                    }
                }
                
                tasks_completed++;
            }

        }

        if (tasks_running == 0) 
        {
            tasks_still_pending = false; // stop the iteration early
            printf("All tasks completed \n");
        }
        printf("*********************************************\n");
        printf("VM migration progress, poll number %d \n", iter);
        printf("----------------------------------------\n");
        printf(" Tasks pending : %d \n", tasks_running);
        printf("       ended   : %d \n", tasks_completed);
        printf("*********************************************\n");    
        
        iter++;
        sleep(pause_interval_secs); 
        
    }
    

    xen_string_set_free(error_msgs);
    xen_string_string_map_free(options);
    xen_host_set_free(source_hosts);
    xen_host_set_free(target_hosts);
    free(task_list);
    free(vm_to_be_migrated);
    xen_vm_set_free(all_vms_in_pool);
    
    CLEANUP;
}