int find_and_terminate_instance(char *instanceId)
{
    char state = 0;
    int err = 0;

    {                                  // ensure the instance is known and save its last state on the stack
        sem_p(inst_sem);
        ncInstance *instance = find_instance(&global_instances, instanceId);
        if (instance == NULL) {
            sem_v(inst_sem);
            return EUCA_NOT_FOUND_ERROR;
        }
        state = instance->state;
        sem_v(inst_sem);
    }

    // try stopping the domain
    err = shutdown_then_destroy_domain(instanceId);

    // log the outcome at the appropriate log level
    if (err == 0) {
        LOGINFO("[%s] instance terminated\n", instanceId);
    } else {
        if (state != BOOTING && state != STAGING && state != TEARDOWN) {
            LOGERROR("[%s] failed to terminate instance\n", instanceId);
        } else {
            LOGDEBUG("[%s] failed to terminate instance\n", instanceId);
        }
    }

    return EUCA_OK;
}
int find_and_terminate_instance(char *instanceId)
{
    char state = 0;
    int err = 0;

    {                                   
        sem_p(inst_sem);
        ncInstance *instance = find_instance(&global_instances, instanceId);
        if (instance == NULL) {
            sem_v(inst_sem);
            return EUCA_NOT_FOUND_ERROR;
        }
        state = instance->state;
        sem_v(inst_sem);
    }

     
    err = shutdown_then_destroy_domain(instanceId);

     
    if (err == 0) {
        LOGINFO("[%s] instance terminated\n", instanceId);
    } else {
        if (state != BOOTING && state != STAGING && state != TEARDOWN) {
            LOGERROR("[%s] failed to terminate instance\n", instanceId);
        } else {
            LOGDEBUG("[%s] failed to terminate instance\n", instanceId);
        }
    }

    return EUCA_OK;
}