Пример #1
0
void log_device_header(struct payload_header *header)
{
	if (header == NULL)
		return;

	char *msg;
	if (header->payload_size == 0)
		msg = "Confirmation";
	else if (header->payload_size > 0)
		msg = "Payload";
	else
		msg = "Header";

	switch ((enum command_type)header->type_id) {
		case CMD_COMMON:
			log_header(WRND_COMMON, msg, header);
			break;
		case CMD_WDT:
			log_header(WRND_WDT, msg, header);
			break;
		case CMD_RNG:
		case CMD_RNG_SEND:
			log_header(WRND_RNG, msg, header);
			break;
		case CMD_NRF:
		case CMD_NRF_FORWARD:
			log_header(WRND_NRF, msg, header);
			break;
		default:
			break;
	}
}
Пример #2
0
/*
 * intercept - This is where the highest level logic of hotpatching
 * is described. Upon startup, this routine looks for libc, and libpthread.
 * If these libraries are found in the process's address space, they are
 * patched.
 *
 * This is init routine of syscall_intercept. This library constructor
 * must be in a TU which also contains public symbols, otherwise linkers
 * might just get rid of the whole object file containing it, when linking
 * statically with libsyscall_intercept.
 */
static __attribute__((constructor)) void
intercept(int argc, char **argv)
{
	(void) argc;
	cmdline = argv[0];

	if (!syscall_hook_in_process_allowed())
		return;

	vdso_addr = (void *)(uintptr_t)getauxval(AT_SYSINFO_EHDR);
	debug_dumps_on = getenv("INTERCEPT_DEBUG_DUMP") != NULL;
	patch_all_objs = (getenv("INTERCEPT_ALL_OBJS") != NULL);
	intercept_setup_log(getenv("INTERCEPT_LOG"),
			getenv("INTERCEPT_LOG_TRUNC"));
	log_header();
	init_patcher();

	dl_iterate_phdr(analyze_object, NULL);
	if (!libc_found)
		xabort("libc not found");

	mprotect_asm_wrappers();
	for (unsigned i = 0; i < objs_count; ++i)
		activate_patches(objs + i);
}
Пример #3
0
/***********************************************************************//**
 * @brief Void constructor
 ***************************************************************************/
ctmodel::ctmodel(void) : GApplication(CTMODEL_NAME, CTMODEL_VERSION)
{
    // Initialise members
    init_members();

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #4
0
/***********************************************************************//**
 * @brief Void constructor
 ***************************************************************************/
ctselect::ctselect(void) : GApplication(CTSELECT_NAME, CTSELECT_VERSION)
{
    // Initialise members
    init_members();

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #5
0
/***********************************************************************//**
 * @brief Void constructor
 ***************************************************************************/
ctbin::ctbin(void) : GApplication(CTBIN_NAME, CTBIN_VERSION)
{
    // Initialise members
    init_members();

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #6
0
/* called to setup bootcharting */
int   bootchart_init( void )
{
    int  ret;
    char buff[4];
    int  timeout = 0, count = 0;

    buff[0] = 0;
    proc_read( LOG_STARTFILE, buff, sizeof(buff) );
    if (buff[0] != 0) {
        timeout = atoi(buff);
    }
    else {
        /* when running with emulator, androidboot.bootchart=<timeout>
         * might be passed by as kernel parameters to specify the bootchart
         * timeout. this is useful when using -wipe-data since the /data
         * partition is fresh
         */
        char  cmdline[1024];
        char* s;
#define  KERNEL_OPTION  "androidboot.bootchart="
        proc_read( "/proc/cmdline", cmdline, sizeof(cmdline) );
        s = strstr(cmdline, KERNEL_OPTION);
        if (s) {
            s      += sizeof(KERNEL_OPTION)-1;
            timeout = atoi(s);
        }
    }
    if (timeout == 0)
        return 0;

    if (timeout > BOOTCHART_MAX_TIME_SEC)
        timeout = BOOTCHART_MAX_TIME_SEC;

    count = (timeout*1000 + BOOTCHART_POLLING_MS-1)/BOOTCHART_POLLING_MS;

    do {ret=mkdir(LOG_ROOT,0755);}while (ret < 0 && errno == EINTR);
    selinux_android_restorecon(LOG_ROOT, 0);

    file_buff_open(log_stat,  LOG_STAT);
    file_buff_open(log_procs, LOG_PROCS);
    file_buff_open(log_disks, LOG_DISK);

    /* create kernel process accounting file */
    {
        int  fd = open( LOG_ACCT, O_WRONLY|O_CREAT|O_TRUNC,0644);
        if (fd >= 0) {
            close(fd);
            acct( LOG_ACCT );
        }
    }

    log_header();
    return count;
}
Пример #7
0
/***********************************************************************//**
 * @brief Void constructor
 ***************************************************************************/
ctobssim::ctobssim(void) : GApplication(CTOBSSIM_NAME, CTOBSSIM_VERSION)
{
    // Initialise members
    init_members();

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #8
0
/***********************************************************************//**
 * @brief Command line constructor
 *
 * @param[in] argc Number of arguments in command line.
 * @param[in] argv Array of command line arguments.
 ***************************************************************************/
ctmodel::ctmodel(int argc, char *argv[]) :
    GApplication(CTMODEL_NAME, CTMODEL_VERSION, argc, argv)
{
    // Initialise members
    init_members();

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #9
0
int main(int argc, char *argcv[])
{
    rayc::Logger log;
    log.add_target(rayc::log_target_ptr(new rayc::CoutLogTarget()));
    log_header(log);
    
    log.log(rayc::LogLevel::info, "Thunderbirds are Go!");
      
    log.log(rayc::LogLevel::info, "Good bye.");
    
    std::cin.get();
}
Пример #10
0
/***********************************************************************//**
 * @brief Command line constructor
 *
 * @param[in] argc Number of arguments in command line.
 * @param[in] argv Array of command line arguments.
 ***************************************************************************/
ctselect::ctselect(int argc, char *argv[]) : 
                   GApplication(CTSELECT_NAME, CTSELECT_VERSION, argc, argv)
{
    // Initialise members
    init_members();

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #11
0
/***********************************************************************//**
 * @brief Command line constructor
 *
 * @param[in] argc Number of arguments in command line.
 * @param[in] argv Array of command line arguments.
 *
 * Constructs application using command line arguments for parameter setting.
 ***************************************************************************/
ctobssim::ctobssim(int argc, char *argv[]) : 
          GApplication(CTOBSSIM_NAME, CTOBSSIM_VERSION, argc, argv)
{
    // Initialise members
    init_members();

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #12
0
static int bootchart_init() {
    int timeout = 0;

    std::string start;
    android::base::ReadFileToString(LOG_STARTFILE, &start);
    if (!start.empty()) {
        timeout = atoi(start.c_str());
    } else {
        // When running with emulator, androidboot.bootchart=<timeout>
        // might be passed by as kernel parameters to specify the bootchart
        // timeout. this is useful when using -wipe-data since the /data
        // partition is fresh.
        std::string cmdline;
        const char* s;
        android::base::ReadFileToString("/proc/cmdline", &cmdline);
#define KERNEL_OPTION  "androidboot.bootchart="
        if ((s = strstr(cmdline.c_str(), KERNEL_OPTION)) != NULL) {
            timeout = atoi(s + sizeof(KERNEL_OPTION) - 1);
        }
    }
    if (timeout == 0)
        return 0;

    if (timeout > BOOTCHART_MAX_TIME_SEC)
        timeout = BOOTCHART_MAX_TIME_SEC;

    int count = (timeout*1000 + BOOTCHART_POLLING_MS-1)/BOOTCHART_POLLING_MS;

    log_stat = fopen(LOG_STAT, "we");
    if (log_stat == NULL) {
        return -1;
    }
    log_procs = fopen(LOG_PROCS, "we");
    if (log_procs == NULL) {
        fclose(log_stat);
        return -1;
    }
    log_disks = fopen(LOG_DISK, "we");
    if (log_disks == NULL) {
        fclose(log_stat);
        fclose(log_procs);
        return -1;
    }

    // Create kernel process accounting file.
    close(open(LOG_ACCT, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644));
    acct(LOG_ACCT);

    log_header();
    return count;
}
Пример #13
0
/***********************************************************************//**
 * @brief Observations constructor
 *
 * This method creates an instance of the class by copying an existing
 * observations container.
 ***************************************************************************/
ctmodel::ctmodel(GObservations obs) : GApplication(CTMODEL_NAME, CTMODEL_VERSION)
{
    // Initialise members
    init_members();

    // Set observations
    m_obs = obs;

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #14
0
/***********************************************************************//**
 * @brief Observations constructor
 *
 * This constructor creates an instance of the class that is initialised from
 * an observation container.
 ***************************************************************************/
ctselect::ctselect(GObservations obs) : GApplication(CTSELECT_NAME, CTSELECT_VERSION)
{
    // Initialise members
    init_members();

    // Set observations
    m_obs = obs;

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #15
0
/* GENERATE_CLSF

   15nov94 wmt: pass n_data = 0, rather than 300 to read_database;
        use apply_search_start_fn
   25apr95 wmt: add binary data file capability
   20may95 wmt: added G_prediction_p

   Generates and returns a classification from data-base and model(s).
   Checks for data-base and model(s) already available in *db-list* and
   *model-list* and if found uses them, otherwise it generates data-base
   and model(s) by combining information from data-file, header-file, and
   model-file.  Optionally initializes the classification using the start-fn.
   N-CLASSES is the initial value for the initialized classification.
   DATA-FILE is fully qualified pathname (file type forced to *data-file-type*).
   HEADER-FILE can be omitted (gets the same file name as data-file), be a file
   name (gets the same root as data-file), or be a fully qualified pathname.
   In all cases, the file type is forced to *header-file-type*.  MODEL-FILE has
   same behavior as header-file. The file type is forced to *model-file-type*.
   LOG-FILE-P can be nil (no log file produced). If t the file type is forced
   to be *log-file-type*.  OUTPUT-FILES-DEFAULT (names the log file) can be
   omitted (gets the same root as data-file and file-name of <data-file file
   name>&<header-file file name>& <model-file file name>, be a file name
   (gets the same root as data-file), or be a fully qualified pathname.
   (REREAD_P T) forces a re-read of data-file, and (REGENERATE_P T) forces a
   re-generation of the model(s) even if they are found in *db-list* and
   *model-list*.  CLSF-INIT-FUN specifies the classification initialization
   function.  (DISPLAY-WTS T) will display class weights produced by the
   initialization.  *package* is bound for interns by read.
   */
clsf_DS generate_clsf( int n_classes, FILE *header_file_fp, FILE *model_file_fp,
        FILE *log_file_fp, FILE *stream, int reread_p, int regenerate_p,
        char *data_file_ptr, char *header_file_ptr, char *model_file_ptr,
        char *log_file_ptr, int restart_p, char *start_fn_type,
        unsigned int initial_cycles_p, int max_data,
                       int start_j_list_from_s_params)
{
  int total_error_cnt, total_warning_cnt, num_models = 0;
  clsf_DS clsf;
  database_DS db;
  model_DS *models;
  int expand_p = FALSE;

  /* read_database & read_model_file are done here because jtp designed
     it this way, moving them to process_data_header_model_files breaks
     the program  - wmt */

  log_header(log_file_fp, stream, data_file_ptr, header_file_ptr, model_file_ptr,
             log_file_ptr);

  db = read_database( header_file_fp, log_file_fp, data_file_ptr, header_file_ptr,
                     max_data, reread_p, stream);

  models = read_model_file(model_file_fp, log_file_fp, db, regenerate_p, expand_p,
                           stream, &num_models, model_file_ptr); 

  process_data_header_model_files( log_file_fp, regenerate_p, stream, db, models,
                                  num_models, &total_error_cnt, &total_warning_cnt);

  if ((G_prediction_p == FALSE) && (start_j_list_from_s_params == FALSE) &&
      (restart_p == FALSE) && (db->n_data > 1000)) {
    to_screen_and_log_file("\nWARNING: the default start_j_list may not find the correct\n"
                           "         number of classes in your data set!\n",
                           log_file_fp, stream, TRUE);
    total_warning_cnt++;
  }
 
  check_stop_processing( total_error_cnt, total_warning_cnt, log_file_fp, stderr);

  if ((G_prediction_p == TRUE) && (G_training_clsf != NULL))
    models = G_training_clsf->models;

  clsf = set_up_clsf( n_classes, db, models, num_models);

  if ((restart_p == FALSE) && (G_prediction_p == FALSE))
    apply_search_start_fn (clsf, start_fn_type, initial_cycles_p, n_classes,
                           log_file_fp, stream);
  return(clsf);
} 
Пример #16
0
/***********************************************************************//**
 * @brief Observations constructor
 *
 * @param[in] obs Observation container.
 *
 * Constructs application by initialising from an observation container.
 ***************************************************************************/
ctobssim::ctobssim(GObservations obs) :
          GApplication(CTOBSSIM_NAME, CTOBSSIM_VERSION)
{
    // Initialise members
    init_members();

    // Set observations
    m_obs = obs;

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #17
0
/*!
 * Outputs a message to the appropriate log with information.
 *
 * @param log_level integer representing the level to log
 * @param message to write to the log
 * @return 1 if the log was successfully written
 */
int printlog(int log_level, char * fmt, ...) {
    char message[256];
    va_list args;
    int retval = 1;
    char * header = log_header(log_level);

    va_start(args, fmt);
    vsprintf(message, fmt, args);
    va_end(args);

    if (log_level >= PROGRAM_LOG_LEVEL) {
        fprintf(context->logfile, "%s: %s\n", header, message);
    }
    
    if (log_level == LOG_LEVEL_ERROR) {
        fprintf(stderr, "%s: %s\n", header, message);        
    }
    return retval;
}
Пример #18
0
/***********************************************************************//**
 * @brief Clear ctexpcube tool
 *
 * Clears ctexpcube tool.
 ***************************************************************************/
void ctexpcube::clear(void)
{
    // Free members
    free_members();
    this->ctobservation::free_members();
    this->ctool::free_members();

    // Clear base class (needed to conserve tool name and version)
    this->GApplication::clear();

    // Initialise members
    this->ctool::init_members();
    this->ctobservation::init_members();
    init_members();

    // Write header into logger
    log_header();

    // Return
    return;
}
Пример #19
0
/* called to setup bootcharting */
void  bootchart_init( void )
{
    int  ret;
    char buff[4];

    do {ret=mkdir(LOG_ROOT,0755);}while (ret < 0 && errno == EINTR);

    file_buff_open(log_stat,  LOG_STAT);
    file_buff_open(log_procs, LOG_PROCS);
    file_buff_open(log_disks, LOG_DISK);

    /* create kernel process accounting file */
    {
        int  fd = open( LOG_ACCT, O_WRONLY|O_CREAT|O_TRUNC,0644);
        if (fd >= 0) {
            close(fd);
            acct( LOG_ACCT );
        }
    }

    log_header();
    gettimeofday(&start_time, 0);
}
Пример #20
0
int main(int argc, char *argv[]) {
    options_t options;
    int exit_code = 0;
    int pid_file_fd = -1;
    int try_failsafe = 0;
    int failsafe_mode = 0;
    int prune_packages = 0;
    int report_errors = 0;
    FILE *hostclass_file = NULL,
         *host_file = NULL;
    FILE *fp = NULL;
    host_config_t host_config;
    hostclass_config_t hostclass_config;
    struct stat st;
    char hostclass_file_tmpname[PATH_MAX],  /* "/tmp/hostclass.yml" */
         hostclass_file_name[PATH_MAX],     /* "/usr/local/etc/hostclass.yml" */
         host_file_tmpname[PATH_MAX],       /* "/tmp/host.yml" */
         host_file_name[PATH_MAX],          /* "/usr/local/etc/host.yml" */
         hostclass_config_url[PATH_MAX],
         host_config_url[PATH_MAX],
         download_url_format[PATH_MAX],
         temp_package_link_dir[PATH_MAX],
         previous_package_link_dir[PATH_MAX],
         package_download_dir[PATH_MAX],
         package_temp_dir[PATH_MAX],
         package_stow_dir[PATH_MAX],
         package_target_dir[PATH_MAX],
         package_link_dir[PATH_MAX],
         local_profiled_file_copy[PATH_MAX], *local_profiled_dir,
         pathbuf[PATH_MAX];
    char hostname[HOST_NAME_MAX];
    const char *base_groups[] = {"production", NULL};
    const char *failsafe_groups[] = {"failsafe", NULL};
    const char *download_groups[] = {"production", "failsafe", NULL};

    #define SNPRINTF_OR_ERROR(label, str, size, fmt, ...) \
        { int n = snprintf((str), (size), (fmt), __VA_ARGS__); \
          if(n == (size)) { log_error("%s is too long for buffer", (label)); \
              goto error; } }
    #define MKPATH_OR_ERROR(label, path) \
        { strlcpy(pathbuf, (path), sizeof(pathbuf)); \
          if(0 != mkpath((pathbuf)) && EEXIST != errno) { \
              log_error("Cannot make %s directory %s", (label), (pathbuf)); \
              goto error; } \
          if(0 != chmod((path), 0755)) { \
              log_error("Cannot chmod %s directory %s", (label), (path)); \
              goto error; } }
    #define RMRF_OR_ERROR(label, path) \
        { if(dir_exists(path) && !rmrf(path)) { \
              log_error("Cannot remove %s directory %s", (label), (path)); \
              goto error; } }
    #define CP_OR_ERROR(label, source, dest, dest_mode)       \
        { if(0 != cp(source, dest, dest_mode)) { \
              log_error ("Cannot copy %s to destination %s", (label), (dest)); \
              goto error; } }

    memset(&host_config, 0, sizeof(host_config_t));
    memset(&hostclass_config, 0, sizeof(hostclass_config_t));
    memset(&options, 0, sizeof(options_t));
    memset(hostclass_file_tmpname, 0, sizeof(hostclass_file_tmpname));
    memset(host_file_tmpname, 0, sizeof(host_file_tmpname));
    memset(previous_package_link_dir, 0, sizeof(previous_package_link_dir));

    options.base_url = BASE_URL;
    options.package_dir = PACKAGE_DIR;
    options.local_initd_file = LOCAL_INITD_FILENAME;
    options.local_profiled_file = LOCAL_PROFILED_FILENAME;
    options.config_dir = CONFIG_DIR;
    options.log_file = NULL;
    options.pid_file = PID_FILE;
    options.proxy = NULL;

    /* === Start ====================================================== */
    if(!parse_commandline(argc, argv, &options)) {
        goto error;
    }

    if(options.failsafe) {
        failsafe_mode = 1;
    }

    if(options.prune) {
      prune_packages = 1;
    }

    if(!(options.dryrun || has_root_privileges())) {
        goto error;
    }

    if(!open_pid_file(&pid_file_fd, options.pid_file)) {
        goto error;
    }

    if(!log_init(options.log_file, NULL)) {
        goto error;
    }

    report_errors = 1;
    log_header("Initializing", failsafe_mode);
    log_message("Roll starting with pid %ld\n", (long)getpid());
    log_message("Logging to %s\n", get_log_filename());

    if(!sanitize_environment()) {
        goto error;
    }

    if(!get_hostname(hostname)) {
        goto error;
    }
    log_message("Hostname is %s\n", hostname);

    /* === Fetch configuration ======================================== */
    log_header("Fetching config files", failsafe_mode);

    /* fetch host file, a versioned snapshot of a host file */
    if(options.host_file) {
        log_info("Using user specified host file %s", options.host_file);
        strlcpy(host_file_tmpname, options.host_file, sizeof(host_file_tmpname));
    } else {
        /* fetch the host config file */
        SNPRINTF_OR_ERROR(
            "Host configuration URL",
            host_config_url, PATH_MAX, HOST_CONFIG_URL_FORMAT,
            options.base_url, hostname
        );
        SNPRINTF_OR_ERROR(
            "Temporary host filename",
            host_file_tmpname, PATH_MAX, "/var/tmp/roll_host.%ld",
            (long)getpid()
        );
        unlink(host_file_tmpname); /* ignore error */
        log_info("Downloading host config from %s", host_config_url);
        if(!download(host_config_url, host_file_tmpname, options.proxy)) {
            goto error;
        }
        log_info("Saved host file to %s", host_file_tmpname);
    }

    host_file = fopen(host_file_tmpname, "rb");
    if(!host_file) {
        log_error("Unable to open %s: %s", host_file_tmpname, strerror(errno));
        goto error;
    }

    /* parse the host file, figure out which hostclass file to fetch */
    log_info("Parsing host config file");
    if(!parse_host_config(&host_config, host_file)) {
        goto error;
    }
    if(!host_config.hostclass_tag) {
        log_error("The host configuration does not specify a hostclass tag");
        goto error;
    }

    /* fetch hostclass file, a verisioned snapshot of a hostclass file */
    if(options.hostclass_file) {
        log_info("Using user specified hostclass file %s", options.hostclass_file);
        strlcpy(hostclass_file_tmpname, options.hostclass_file, sizeof(hostclass_file_tmpname));
    } else {
        /* fetch the hostclass config file */
        SNPRINTF_OR_ERROR(
            "Hostclass configuration URL",
            hostclass_config_url, PATH_MAX, HOSTCLASS_CONFIG_URL_FORMAT,
            options.base_url, host_config.hostclass_tag
        );
        SNPRINTF_OR_ERROR(
            "Temporary hostclass filename",
            hostclass_file_tmpname, PATH_MAX, "/var/tmp/roll_hostclass.%ld",
            (long)getpid()
        );
        unlink(hostclass_file_tmpname); /* ignore error */
        log_info("Downloading hostclass config from %s", hostclass_config_url);
        if(!download(hostclass_config_url, hostclass_file_tmpname, options.proxy)) {
            goto error;
        }
        log_info("Saved hostclass config file to %s", hostclass_file_tmpname);
    }

    log_info("Parsing hostclass config file");
    hostclass_file = fopen(hostclass_file_tmpname, "rb");
    if(!hostclass_file) {
        log_error("Unable to open %s: %s", hostclass_file_tmpname, strerror(errno));
        goto error;
    }
    if(!parse_hostclass_config(&hostclass_config, hostclass_file)) {
        goto error;
    }

    /* === Configuration ======================================== */
    log_header("Configuration", failsafe_mode);
    /* TODO verify image is defined */
    /* TODO verify current image matches desired image */

    log_message("Hostclass tag:     %s\n", host_config.hostclass_tag);
    log_message("Hardware type:     %s\n", "__TODO__");
    log_message("Current OS image:  %s\n", "__TODO__");
    log_message("Required OS image: %s\n", "__TODO__");

    /* === Download packages ========================================== */
    log_header("Downloading packages", failsafe_mode);

    SNPRINTF_OR_ERROR(
        "Package stow directory name",
        package_stow_dir, PATH_MAX, PACKAGE_STOW_DIR_FORMAT,
        options.package_dir
    );
    SNPRINTF_OR_ERROR(
        "Package download directory name",
        package_download_dir, PATH_MAX, PACKAGE_DOWNLOAD_DIR_FORMAT,
        options.package_dir
    );
    SNPRINTF_OR_ERROR(
        "Package temp directory name",
        package_temp_dir, PATH_MAX, PACKAGE_TEMP_DIR_FORMAT,
        options.package_dir
    );
    SNPRINTF_OR_ERROR(
        "Download URL format",
        download_url_format, PATH_MAX, DOWNLOAD_URL_METAFORMAT,
        options.base_url
    );
    MKPATH_OR_ERROR("package repository", package_stow_dir);
    MKPATH_OR_ERROR("package download", package_download_dir);
    MKPATH_OR_ERROR("package temp", package_temp_dir);
    if(!download_packages(hostclass_config.package_list,
                          download_groups,
                          download_url_format,
                          package_stow_dir,
                          package_download_dir,
                          package_temp_dir,
                          options.proxy))
    {
        goto error;
    }

 failsafe:

    /* === Build symlink tree ========================================= */
    log_header("Building symlink tree", failsafe_mode);
    /* TODO determine additional package groups to link from host */

    /* Figure out where to put things */
    SNPRINTF_OR_ERROR(
        "Package target directory name",
        package_target_dir, PATH_MAX, PACKAGE_TARGET_DIR_FORMAT,
        options.package_dir
    );
    SNPRINTF_OR_ERROR(
        "Hostclass symlink tree directory name",
        package_link_dir, PATH_MAX, "%s/%s%s",
        package_target_dir,
        (failsafe_mode ?
            (options.hostclass_file ? "__FAILSAFE__DEV__" : "__FAILSAFE__") :
            (options.hostclass_file ? "__DEV__" : "") ),
        host_config.hostclass_tag
    );
    SNPRINTF_OR_ERROR(
        "Hostclass temp symlink tree directory name",
        temp_package_link_dir, PATH_MAX, "%s.%ld",
        package_link_dir, (long)getpid()
    );

    RMRF_OR_ERROR("temporary package link", temp_package_link_dir);
    MKPATH_OR_ERROR("temporary package link", temp_package_link_dir);

    if(!create_package_tree(hostclass_config.package_list,
                            (failsafe_mode ? failsafe_groups : base_groups),
                            package_stow_dir,
                            temp_package_link_dir))
    {
        goto error;
    }

    /* !! Any failures from here on out will trigger failsafe mode */
    try_failsafe = 1;

    /* === Install /etc/init.d/local_initd ============================ */
    log_header("Installing local_initd script", failsafe_mode);
    if(!(fp = fopen(options.local_initd_file, "w")) ) {
        log_error("  Cannot open %s for writing.", options.local_initd_file);
        goto error;
    }
    fputs(LOCAL_INITD_SCRIPT, fp);
    fclose(fp);
    if(0 != chmod(options.local_initd_file, EXE_MODE)) {
        log_error("  Could not chmod %04o %s", EXE_MODE, options.local_initd_file);
        goto error;
    }
    log_info("Installed %s", options.local_initd_file);

    if(options.dryrun) {
        log_info("Skipping symlink creation in dry run mode");
    } else {

        /* If Gentoo/OpenRC, use textual default runlevel */
        if(dir_exists("/etc/runlevels/default")) {

            unlink(OPENRC_LOCAL_INITD_SYMLINK);    /* ignore errors */
            if(0 != symlink(LOCAL_INITD_FILENAME, OPENRC_LOCAL_INITD_SYMLINK)) {
                log_error("  Could not symlink %s to %s: %s", LOCAL_INITD_SCRIPT, OPENRC_LOCAL_INITD_SYMLINK, strerror(errno));
                goto error;
            }
            log_info("Installed Gentoo/OpenRC runlevel symlink %s", OPENRC_LOCAL_INITD_SYMLINK);

        /* Otherwise, assume SysV numeric runlevels */
        } else {

            char **s, *symlink_dests[] = LOCAL_INITD_SYMLINKS;
            for(s = symlink_dests; *s != NULL; s++) {
                unlink(*s);
                if(0 != symlink(LOCAL_INITD_FILENAME, *s)) {
                    log_error("  Could not symlink %s to %s: %s", LOCAL_INITD_SCRIPT, *s, strerror(errno));
                    goto error;
                }
                log_info("Installed SysV runlevel symlink %s", *s);
            }

        }
    }

    /* === Install /etc/profile.d/local_profiled.sh =================== */
    log_header("Installing local_profiled.sh script", failsafe_mode);
    strlcpy(local_profiled_file_copy, options.local_profiled_file, sizeof(local_profiled_file_copy));
    local_profiled_dir = dirname(local_profiled_file_copy);
    MKPATH_OR_ERROR("bash local_profiled.sh directory", local_profiled_dir);
    if(!(fp = fopen(options.local_profiled_file, "w")) ) {
        log_error("  Cannot open %s for writing.", options.local_profiled_file);
        goto error;
    }
    fputs(LOCAL_PROFILED_SCRIPT, fp);
    fclose(fp);
    log_info("Installed %s", options.local_profiled_file);

    /* === Run /etc/init.d/local_initd stop =========================== */
    log_header("Shutting down services", failsafe_mode);
    if(options.dryrun) {
        log_info("Skipping in dry run mode");
    } else {
        exit_code = run_command(options.local_initd_file, "stop", NULL);
        if(0 != exit_code) {
            log_error("  Could not run %s stop (status = %d)", options.local_initd_file, exit_code);
            goto error;
        }
    }

    /* === Move symlink tree into place =============================== */
    log_header("Moving package link tree into /usr/local", failsafe_mode);
    if(options.dryrun) {
        log_info("Skipping in dry run mode");
    } else {
        if(0 == lstat(PACKAGE_TARGET_LINK, &st)) {
            if(S_ISLNK(st.st_mode)) {
                log_message("Removing old %s symlink\n", PACKAGE_TARGET_LINK);

                /* Remember the current value for later; ignore error */
                readlink(PACKAGE_TARGET_LINK, previous_package_link_dir, PATH_MAX);

                if(0 != unlink(PACKAGE_TARGET_LINK)) {
                    log_error("Cannot unlink %s: %s", PACKAGE_TARGET_LINK, strerror(errno));
                    goto error;
                }
            } else {
                log_error("%s is expected to be missing or a symlink", PACKAGE_TARGET_LINK);
                goto error;
            }
        } else {
            if(ENOENT != errno) {
                log_error("%s: cannot stat", PACKAGE_TARGET_LINK);
                goto error;
            }
        }

        if(dir_exists(package_link_dir)) {
            log_message("Removing old link tree\n");
            RMRF_OR_ERROR("old package link", package_link_dir);
        }

        log_message("Moving link tree to %s\n", package_link_dir);
        if(0 != rename(temp_package_link_dir, package_link_dir)) {
            log_error("Cannot move temp symlink tree from %s to %s: %s", temp_package_link_dir, package_link_dir, strerror(errno));
            goto error;
        }

        log_message("Creating symlink from %s to %s\n", PACKAGE_TARGET_LINK, package_link_dir);
        if(0 != symlink(package_link_dir, PACKAGE_TARGET_LINK)) {
            log_error("Cannot create symlink from %s to %s: %s", PACKAGE_TARGET_LINK, package_link_dir, strerror(errno));
            goto error;
        }
    }

    /* === Copy hostclass file and host file to config_dir ====== */
    SNPRINTF_OR_ERROR(
        "hostclass configuration file",
        hostclass_file_name, PATH_MAX, "%s/hostclass.yml",
        options.config_dir
    );
    CP_OR_ERROR("hostclass configuration file",
        hostclass_file_tmpname,
        hostclass_file_name,
        0644
    );

    SNPRINTF_OR_ERROR(
        "host configuration file",
        host_file_name, PATH_MAX, "%s/host.yml",
        options.config_dir
    );
    CP_OR_ERROR("host configuration file",
        host_file_tmpname,
        host_file_name,
        0644
    );

    /* === Run configuration scripts ================================== */
    log_header("Processing package configuration scripts", failsafe_mode);

    MKPATH_OR_ERROR("config output directory", options.config_dir);

    exit_code = run_command(CONFIGURATE,
                            "--template-outdir", options.config_dir,
                            hostclass_file_tmpname,
                            host_file_tmpname,
                            NULL
    );
    if(0 != exit_code) {
        log_error("  Exit code from %s is %d", CONFIGURATE, exit_code);
        goto error;
    }

    /* === Run /etc/init.d/local_initd start ========================== */
    log_header("Starting services", failsafe_mode);
    if(options.dryrun) {
        log_info("Skipping in dry run mode");
    } else {
        exit_code = run_command(options.local_initd_file, "start", NULL);
        if(0 != exit_code) {
            log_error("  Could not run %s start", options.local_initd_file);
            goto error;
        }
    }

    /* === Cleanup ==================================================== */
    log_header("Cleanup", failsafe_mode);

    if(!failsafe_mode) {
        log_info("Removing package target directories from prior installations.");
        /* ignore errors */
        clean_previous_package_trees(package_target_dir,
                                     options.dryrun ? temp_package_link_dir : package_link_dir,
                                     previous_package_link_dir);
        if(options.dryrun) {
          log_info("Skipping package prune in dry run mode");
        }
        else if (prune_packages) {
          log_info("Removing unused packages from prior installations.");
          clean_previous_packages(hostclass_config.package_list,
                                  package_stow_dir);
        }
    } else {
        log_info("Not removing package target directories from prior installations in failsafe mode.");
    }

    /* TODO reboot if necessary */

    goto done;
 error:
    if(!failsafe_mode && try_failsafe) {
        if(hostclass_config.has_failsafe) {
            failsafe_mode = 1;
            log_message("\n!!! Falling back to failsafe configuration...\n");
            goto failsafe;
        } else {
            log_message("\n!!! Tried to enter failsafe mode, but the hostclass config is\n");
            log_message("!!! missing a failsafe mode definition.\n");
        }
    }
    exit_code = 1;
 done:
    if(host_file)
        fclose(host_file);
    host_file = NULL;
    if(host_file_tmpname[0] && !options.host_file)
        unlink(host_file_tmpname);

    if(hostclass_file)
        fclose(hostclass_file);
    hostclass_file = NULL;
    if(hostclass_file_tmpname[0] && !options.hostclass_file)
        unlink(hostclass_file_tmpname);
    free_hostclass_config(&hostclass_config);

    if(report_errors) {
        if(failsafe_mode) {
            if(exit_code != 0) {
                log_header("Failsafe roll failed", failsafe_mode);
                log_message("!!! An error occurred during both normal and failsafe mode.\n\n");
            } else {
                log_header("Failsafe roll succeeded", failsafe_mode);
                log_message("!!! An error occurred during normal roll.\n");
                log_message("!!! Failsafe mode completed successfully.\n\n");
                exit_code = 6;
            }
        } else {
            if(exit_code != 0) {
                log_header("Roll failed; failsafe mode not attempted", failsafe_mode);
                log_message("!!! An error occurred during roll.\n\n");
            } else {
                log_header("Roll succeeded", failsafe_mode);
                log_message("!!! Done.\n\n");
            }
        }
    }

    log_close();
    if(pid_file_fd >= 0)
        close_pid_file(pid_file_fd, options.pid_file);
    return exit_code;

    #undef SNPRINTF_OR_ERROR
    #undef MKPATH_OR_ERROR
    #undef RMRF_OR_ERROR
}
Пример #21
0
void KMLProxy::run(Particles *initial_centers) {
  IMP_INTERNAL_CHECK(is_init_,"The proxy was not initialized");
  IMP_LOG(VERBOSE,"KMLProxy::run start \n");
  //use the initial centers if provided
  KMPointArray *kmc=nullptr;
  if (initial_centers != nullptr)  {
    IMP_INTERNAL_CHECK(kcenters_ == initial_centers->size(),
    "the number of initial points differs from the number of required"
    <<" centers\n");
    IMP_LOG(VERBOSE,"KMLProxy::run initial centers provided : \n");
    kmc = allocate_points(kcenters_,atts_.size());
    for (unsigned int i=0;i<kcenters_;i++){
      Particle *cen=(*initial_centers)[i];
      for(unsigned int j=0;j<atts_.size();j++) {
        (*(*kmc)[i])[j]=cen->get_value(atts_[j]);
       }
    }
  }
  IMP_LOG(VERBOSE,"KMLProxy::run load initial guess \n");
  //load the initail guess
  KMFilterCenters ctrs(kcenters_, data_, kmc,damp_factor_);

  //apply lloyd search
  IMP_LOG(VERBOSE,"KMLProxy::run load lloyd \n");
  lloyd_alg_ = new KMLocalSearchLloyd(&ctrs,&term_);
  log_header();
  IMP_CHECK_CODE(clock_t start = clock());
  IMP_LOG(VERBOSE,"KMLProxy::run excute lloyd \n");
  lloyd_alg_->execute();
  IMP_LOG(VERBOSE,"KMLProxy::run analyse \n");
  KMFilterCentersResults best_clusters = lloyd_alg_->get_best();
  IMP_CHECK_CODE(Float exec_time = elapsed_time(start));
  // print summary
  IMP_LOG_WRITE(TERSE,log_summary(&best_clusters,exec_time));
  IMP_LOG_WRITE(TERSE,best_clusters.show(IMP_STREAM));
  IMP_INTERNAL_CHECK(kcenters_
                     == (unsigned int) best_clusters.get_number_of_centers(),
             "The final number of centers does not match the requested one");
  IMP_INTERNAL_CHECK (dim_ == (unsigned int) best_clusters.get_dim(),
              "The dimension of the final clusters is wrong");
  //TODO clear the centroids list
  //set the centroids:
  Particle *p;
  IMP_LOG(VERBOSE,"KMLProxy::run load best results \n");
  for (unsigned int ctr_ind = 0; ctr_ind < kcenters_; ctr_ind++) {
    KMPoint *kmp = best_clusters[ctr_ind];
    //create a new particle
    p = new Particle(m_);
    centroids_.push_back(p);
    for (unsigned int att_ind = 0; att_ind < dim_; att_ind++) {
      p->add_attribute(atts_[att_ind],(*kmp)[att_ind],false);
    }
  }
  //set the assignment of particles to centers
  //array of number of all points
  //TODO - return this
  IMP_LOG(VERBOSE,"KMLProxy::run get assignments \n");
  const Ints *close_center = best_clusters.get_assignments();
  IMP_LOG(VERBOSE,"KMLProxy::run get assignments 2\n");
  for (int i=0;i<data_->get_number_of_points();i++) {
    //std::cout<<"ps number i: " << i << " close center : "
    //<< (*close_center)[i] << std::endl;
    assignment_[ps_[i]]=(*close_center)[i];
  }
}