/* Parse CorrectiveAction string list from filename String list must be freed. */ static gint parse_corrective_action(gchar * file_path, gchar *** out_str_list, gsize * out_str_list_len, CorrectiveActionType corr_act_type, gboolean is_target){ GKeyFile * keyFile = NULL; GError * error = NULL; gint r = 0; gsize str_len = 0; gchar ** str_list = NULL; gchar * opt_group = is_target ? CORRECTIVE_ACTION_GROUP_OPTION_T : CORRECTIVE_ACTION_GROUP_OPTION_S; keyFile = g_key_file_new(); if (!g_key_file_load_from_file(keyFile, file_path, 0 /* flag */, &error)){ log_error_message("Could not load key file from '%s'\n%s\n", file_path, (error ? error->message : "")); if (error){ g_error_free(error); error = NULL; } r = 1; goto free_res; } if (!g_key_file_has_group(keyFile, opt_group)){ log_error_message("File '%s' doesn't contain '%s' group!\n", file_path, opt_group); r = 1; goto free_res; } if (!g_key_file_has_key(keyFile, opt_group, g_corr_act_type_key[corr_act_type], NULL)){ log_error_message("File '%s', group '%s' doesn't contain '%s' key!\n", file_path, opt_group, g_corr_act_type_key[corr_act_type]); r = 1; goto free_res; } g_key_file_set_list_separator(keyFile, ' '); str_list = g_key_file_get_string_list(keyFile, opt_group, g_corr_act_type_key[corr_act_type], &str_len, &error); if (!str_list || str_len < 1 || error){ log_error_message("Could not obtain %s from file '%s'\n%s\n", g_corr_act_type_key[corr_act_type], file_path, (error ? error->message : "")); if (error) { g_error_free(error); error = NULL; } r = 1; goto free_res; } *out_str_list = str_list; *out_str_list_len = str_len; free_res: /* Free resources */ if (keyFile){ g_key_file_free(keyFile); keyFile = NULL; } return r; }
/* Gets proxy to AL. Also initializes connection and proxy if it's not. */ static DBusGProxy * get_AL_proxy(){ GError * error = NULL; if (g_AL_proxy) return g_AL_proxy; if (!g_conn){ g_conn = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error); if (!g_conn || error){ log_error_message("Could not obtain dbus connection!\n%s\n", (error ? error->message : "")); g_error_free(error); error = NULL; goto failure; } } g_AL_proxy = dbus_g_proxy_new_for_name(g_conn, AL_SERVICE, AL_PATH, AL_INTF); if (!g_AL_proxy){ log_error_message("Could not obtain proxy to AL!\n", 0); goto failure; } return g_AL_proxy; failure: if (g_AL_proxy) g_object_unref(g_AL_proxy); return NULL; }
/* Gets pid for an appl. giving its dbus-path */ static guint get_pid_from_app_path(const gchar * inPath){ DBusGProxy * lPropProxy = NULL; GValue lServicePidV = {0}; guint lServicePid = 0; GError * lError = NULL; assert(inPath); if (!g_conn){ g_conn = dbus_g_bus_get(DBUS_BUS_SYSTEM, &lError); if (!g_conn || lError){ log_error_message("Could not obtain dbus connection!\n%s\n", (lError ? lError->message : "")); g_error_free(lError); lError = NULL; goto res_free; } } /* Get a proxy to systemd Properties */ lPropProxy = dbus_g_proxy_new_for_name(g_conn, SYSD_SERVICE_NAME, //systemd service name inPath, //service path SYSD_INTERFACE_PROP); //systemd properties interface if (NULL == lPropProxy){ log_error_message("Failed to get Properties proxy!\n", 0); goto res_free; } /* Call Get method of dbus Properties interface Find out Service ControlGroups list. */ if (!dbus_g_proxy_call_with_timeout(lPropProxy, "Get", REPLY_TIMEOUT, &lError, G_TYPE_STRING, SYSD_INTERFACE_SERVICE, //systemd Service interface G_TYPE_STRING, "ExecMainPID", //look for property G_TYPE_INVALID, G_TYPE_VALUE, &lServicePidV, //property value G_TYPE_INVALID)){ log_error_message("Method call failed: %s\n", lError->message); g_error_free(lError); goto res_free; } log_debug_message("[%s] Got GValue, taking guint...\n", __func__); lServicePid = g_value_get_uint(&lServicePidV); log_debug_message("[%s] Got pid=%u\n", __func__, lServicePid); res_free: if (lPropProxy){ g_object_unref(lPropProxy); lPropProxy = NULL; } return lServicePid; }
/* Function responsible with the daemonization procedure */ static void daemonize() { /* file descriptor */ int l_fp; /* container for the pid */ char l_str[10]; /* setup a PID and a SID for our HM Daemon */ pid_t l_al_sid, l_al_pid; /* fork process */ l_al_pid=fork(); /* test for forking errors */ if (l_al_pid<0) { log_error_message( "Cannot fork off parent process!\n", 0); exit(EXIT_FAILURE); } /* check parent exit */ if (l_al_pid>0) { log_message(stdout, "Parent process exited!\n", 0); exit(0); } /* child (daemon) continues */ l_al_sid = setsid(); /* obtain a new process group */ if (l_al_sid < 0) { log_error_message("Cannot set SID for the process!\n", 0); exit(EXIT_FAILURE); } /* set newly created file permissions */ umask(0); l_fp=open(WATCHDOG_PID_FILE, O_RDWR|O_CREAT, 0640); /* test if pid file can be open */ if (l_fp<0) { log_error_message("Cannot open pid file\n", 0); exit(1); } /* test if pid file can locked */ if (lockf(l_fp, F_TLOCK,0)<0) { log_error_message("HM Daemon : Cannot obtain lock on pid file\n", 0); exit(0); } /* first instance continues */ sprintf(l_str, "%d\n", getpid()); /* record pid to lockfile */ write(l_fp, l_str, strlen(l_str)); /* close unneeded file descriptors to maintain security */ close(STDIN_FILENO); }
static void *memory_monitor(void *argv) { int fd = -1; int read_count = 0; char *buf = NULL, *p = NULL; if((buf = malloc(READ_FILE_MAX)) == NULL) { log_error_message("alloc memory fail"); goto clean; } while(!g_exit) { fd = open("/proc/meminfo", O_RDONLY); if(fd < 0) { log_error_message("open /proc/meminfo fail"); goto clean; } memset(buf, 0, READ_FILE_MAX); read_count = read(fd, buf, READ_FILE_MAX); if(read_count <= 0) { log_error_message("read /proc/meminfo fail or empty"); goto clean; } buf[read_count] = '\0'; p = buf; p = skip_token(p); mem_total = strtoul(p, &p, 10); p = strchr(p, '\n'); p = skip_token(p); mem_free = strtoul(p, &p, 10); close(fd); sleep(1); } clean: if(NULL != buf) { free(buf); } if(fd > 0) { close(fd); } return NULL; }
static void *disk_monitor(void *argv) { FILE *fh = NULL; struct mntent *mnt_info; struct statfs fs_info; long long sum_disk_total = 0, sum_disk_free = 0; int ret = -1; if ((fh = setmntent("/etc/mtab", "r")) == NULL) { log_error_message("setmentent /etc/mtab fail."); return NULL; } while ((mnt_info = getmntent(fh))) { if (mnt_info->mnt_fsname && ((0 == strncmp(mnt_info->mnt_fsname, "/dev/", 5)))) { if (statfs(mnt_info->mnt_dir, &fs_info) < 0) continue; if (fs_info.f_blocks !=0) { sum_disk_total += fs_info.f_blocks * fs_info.f_bsize / 1024; sum_disk_free += fs_info.f_bfree * fs_info.f_bsize / 1024; } } } endmntent(fh); disk_total = sum_disk_total; disk_free = sum_disk_free; ret = 0; }
/* Calls AL Run method: runs an appl. with given appName */ static gint call_AL_run_app(gchar * appName){ GError * error = NULL; gint al_reply_pid; gboolean method_call_status; int r = 0; assert(appName); method_call_status =dbus_g_proxy_call_with_timeout(get_AL_proxy(), "Run", REPLY_TIMEOUT, &error, G_TYPE_STRING, appName, G_TYPE_INT, 0, G_TYPE_BOOLEAN, TRUE, G_TYPE_INVALID, G_TYPE_INT, &al_reply_pid, G_TYPE_INVALID); if (!method_call_status || error){ log_error_message("Could not call AL Run method!\n%s\n", (error ? error->message : "")); g_error_free(error); error = NULL; r = 1; } log_message("called AL Run with: %s, True ; reply-pid: %d\n", appName, al_reply_pid); return r; }
int host_monitor_init() { if(-1 == pthread_create(&cpu_tid, NULL, cpu_monitor, NULL)) { log_error_message("create thread host monitor fail"); return -1; } if(-1 == pthread_create(&mem_tid, NULL, memory_monitor, NULL)) { log_error_message("create thread memory monitor fail"); return -1; } if(-1 == pthread_create(&disk_tid, NULL, disk_monitor, NULL)) { log_error_message("create thread disk monitor fail"); return -1; } }
int get_log_level_from_config() { FILE *fp = NULL; char level[8] = {0}; int nread = 0, log_level = -1; if((fp = fopen(LOG_CONFIG_FILE, "r")) == NULL) { log_error_message("fopen %s fail", LOG_CONFIG_FILE); return -1; } if((nread = fread(level, sizeof(char), sizeof(level), fp)) <= 0) { log_error_message("read date from %s fail", LOG_CONFIG_FILE); fclose(fp); return -1; } level[nread] = 0; sscanf(level, "%d", &log_level); return log_level; }
int log_init() { log_filter = get_log_level_from_config(); log_info_message("log filter is %s", log_level_string(log_filter)); pthread_mutex_init(&log_thread_mutex, NULL); if(0 != pthread_create(&log_thread_t, NULL, log_monitor, NULL)) { log_error_message("log monitor thread fail"); pthread_mutex_destroy(&log_thread_mutex); return -1; } return 0; }
int socket_init() { char *ip = NULL; g_sockfd = socket(AF_INET, SOCK_STREAM, 0); if(-1 == g_sockfd) { log_error_message("socket fail"); return -1; } server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(SERVER_ADDR); server_addr.sin_port = htons(SERVER_PORT); ip = inet_ntoa(server_addr.sin_addr); if(NULL == ip) { log_error_message("inet_ntoa fail"); return -1; } int on; on = 1; setsockopt(g_sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ); if(-1 == bind(g_sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr))) { log_error_message("bind fail"); return -1; } if(-1 == listen(g_sockfd, 3)) { log_error_message("listen fail"); return -1; } log_info_message("server ip:%s listen in:%d", ip, ntohs(server_addr.sin_port)); return g_sockfd; }
/* Print out all errors messages generated to the error log file. */ int log_odbc_error(char *filename, int line, SQLSMALLINT handle_type, SQLHANDLE handle) { SQLCHAR sqlstate[5]; SQLCHAR message[256]; SQLSMALLINT i; char msg[1024]; i = 1; while (SQLGetDiagRec(handle_type, handle, i, sqlstate, NULL, message, sizeof(message), NULL) == SQL_SUCCESS) { sprintf(msg, "[%d] sqlstate %s : %s", i, sqlstate, message); log_error_message(filename, line, msg); ++i; } return OK; }
HOST_INFO *get_host_info_impl() { HOST_INFO *host_info = NULL; host_info = (HOST_INFO *)malloc(sizeof(HOST_INFO)); if(NULL == host_info) { log_error_message("alloc memory fail"); return NULL; } host_info->cpu_rate = cpu_rate; host_info->memory_total = mem_total/1024; host_info->memory_free = mem_free/1024; host_info->disk_total = disk_total/1024; host_info->disk_free = disk_free/1024; return host_info; }
/* Calls AL Restart method: restarts appl. with given appName */ static gint call_AL_restart_app(gchar * appName){ GError * error = NULL; gboolean al_reply_bool; guint al_reply_uint; gboolean method_call_status; int r = 0; method_call_status =dbus_g_proxy_call_with_timeout(get_AL_proxy(), "Restart", REPLY_TIMEOUT, &error, G_TYPE_STRING, appName, G_TYPE_INVALID, G_TYPE_INVALID); if (!method_call_status || error){ log_error_message("Could not call AL Restart method!\n%s\n", (error ? error->message : "")); g_error_free(error); error = NULL; r = 1; } log_message("called AL Restart with: %s, reply: %s, %u\n", appName, (al_reply_bool ? "true" : "false"), al_reply_uint); return r; }
/* Calls AL Stop method: stops appl. with given pid */ static gint call_AL_stop_app(guint pid){ GError * error = NULL; gboolean al_reply_bool; guint al_reply_uint; gboolean method_call_status; int r = 0; method_call_status =dbus_g_proxy_call_with_timeout(get_AL_proxy(), "Stop", REPLY_TIMEOUT, &error, G_TYPE_INT, pid, G_TYPE_INVALID, G_TYPE_INVALID); if (!method_call_status || error){ log_error_message("Could not call AL Stop method!\n%s\n", (error ? error->message : "")); g_error_free(error); error = NULL; r = 1; } log_message("called AL Stop with %u, reply: %s, %u\n", pid, (al_reply_bool ? "true" : "false"), al_reply_uint); return r; }
static void w_dbus_unregister_object(WatchdogService * wservice, DBusGProxy *bus_proxy, DBusGConnection *connection) { guint release_result = 0; GError *error = NULL; if(bus_proxy == NULL || !dbus_g_proxy_call(bus_proxy, "ReleaseName", &error, G_TYPE_STRING, WATCHDOG_SERVICE, G_TYPE_INVALID, G_TYPE_UINT, &release_result, G_TYPE_INVALID)){ log_error_message("failed to release '%s' (proxy=%p)\n", WATCHDOG_SERVICE, bus_proxy); if(error) g_error_free(error); } dbus_g_connection_unregister_g_object(connection, wservice); g_object_unref(wservice); return; }
/* Calls AL Run method to reboot system */ static gint call_AL_reboot_system(){ GError * error = NULL; gint al_reply_pid; gboolean method_call_status; int r = 0; method_call_status =dbus_g_proxy_call_with_timeout(get_AL_proxy(), "Run", REPLY_TIMEOUT, &error, G_TYPE_STRING, "reboot 0s", G_TYPE_INT, 0, G_TYPE_BOOLEAN, TRUE, G_TYPE_INVALID, G_TYPE_INT, &al_reply_pid, G_TYPE_INVALID); if (!method_call_status || error){ log_error_message("Could not call AL Run method to reboot in 0s!\n%s\n", (error ? error->message : "")); g_error_free(error); error = NULL; r = 1; } log_message("called AL Run with 'reboot 0s', True ; reply:%d\n", al_reply_pid); return r; }
int main(int argc, char **argv) { char log_text[2000]; char* nombre = string_substring_from(argv[1], 2); char* nombre_log = string_duplicate(nombre); char* log = ".log"; string_append(&nombre_log, log); inicializar_log(nombre_log, "Programa"); habilitar_log_info(); sprintf(log_text, "Proceso Programa %s Iniciado", nombre); log_info_message(log_text); log_info_message("Chequeando el path del script..."); if (argv[1] == NULL ) { log_error_message("El path del script no puede ser vacio."); finalizar_log(); return EXIT_FAILURE; } // CONEXION CON KERNEL t_KER_PRO_CPU_UMV mensajeAEnviar = obtener_nueva_shared_str(); t_KER_PRO_CPU_UMV* mensajeARecibir; log_debug_message("Se inicia la conexion con el KERNEL"); int socket; // ACA VA LO DE LA VARIABLE DE ENTORNO char* rutaConfiguracion = getenv("ANSISOP_CONFIG"); t_config *config = config_create(rutaConfiguracion); int puerto = config_get_int_value(config, "Puerto"); char* ip = config_get_string_value(config, "IP"); sprintf(log_text, "LA IP ES: %s\n", ip); log_info_message(log_text); sprintf(log_text, "EL PUERTO ES: %i\n", puerto); log_info_message(log_text); socket = conectar_a_servidor(ip, puerto); if (socket == -1) { return EXIT_FAILURE; } log_debug_message("Conectado\n"); // SE LEVANTA EL SCRIPT sprintf(log_text, "Se levantan datos del script en el path:%s", argv[1]); log_info_message(log_text); int num = 0; log_debug_message("se abre el archivo"); FILE* script; script = fopen(argv[1], "r"); log_debug_message("se abrio el archivo"); int tamanio; fseek(script, 0, SEEK_END); tamanio = ftell(script) + 1; sprintf(log_text, "El tamanio del script es: (%d)", tamanio); log_info_message(log_text); char codigo[tamanio]; rewind(script); char aux; while (feof(script) == 0) { aux = fgetc(script); codigo[num] = aux; num++; } log_debug_message("se termino de leer"); // printf("num vale: (%d)\n", num); num = num - 1; // printf("ahora num vale: (%d)\n", num); sprintf(log_text, "LEO: ('nueva linea')y pongo en posicion (%d)", num); log_debug_message(log_text); codigo[num] = '\n'; num++; sprintf(log_text, "LEO: ('barra 0')y pongo en posicion (%d)", num); log_debug_message(log_text); codigo[num] = '\0'; sprintf(log_text, "El script es: \n%s", codigo); log_debug_message(log_text); sprintf(log_text, "La longitud del codigo es: %i\n", strlen(codigo)); log_info_message(log_text); fclose(script); mensajeAEnviar.codigo = codigo; mensajeAEnviar.mensaje = nombre; log_debug_message("se copia el codigo"); sprintf(log_text, "El codigo copiado en el mensaje es: (%s)", mensajeAEnviar.codigo); log_debug_message(log_text); // SE ENVIA EL HANDSHAKE log_info_message( "Se envia HANDSHAKE al PLP con el Codigo y el Nombre del programa\n"); enviar_mensaje_a_servidor(socket, HANDSHAKE_PROGRAMA_PLP, &mensajeAEnviar); void *msj = recibir_mensaje_de_servidor(socket); if (msj != NULL ) { mensajeARecibir = (t_KER_PRO_CPU_UMV*) msj; } else { log_debug_message("ERROR AL RECIBIR MENSAJE NULO"); return -1; } if (mensajeARecibir->gen_msg.id_MSJ != HANDSHAKE_PROGRAMA_PLP || mensajeARecibir->OK != 1) { sprintf(log_text, "%s\n", mensajeARecibir->mensaje); log_info_message(log_text); return -1; } else { log_info_message("Respuesta Handshake entre PROGRAMA-KERNEL recibida"); } while (1) { log_info_message( "\nEL PROGRAMA SE QUEDA ESPERANDO MENSAJES DE IMPRIMIR/ IMPRIMIR TEXTO O FINALIZAR EJECUCION\n"); msj = recibir_mensaje_de_servidor(socket); if (msj != NULL ) { mensajeARecibir = (t_KER_PRO_CPU_UMV*) msj; } else { log_debug_message("ERROR AL RECIBIR MENSAJE NULO"); return -1; } switch (mensajeARecibir->gen_msg.id_MSJ) { case IMPRIMIR: { log_info_message("LLEGO MENSAJE CON ID IMPRIMIR"); sprintf(log_text, "SE IMPRIME EL VALOR DE LA VARIABLE: %i\n", mensajeARecibir->valor); log_info_message(log_text); break; } case IMPRIMIR_TEXTO: { // SE HACE LO DE IMPRIMIR TEXTO log_info_message("LLEGO MENSAJE CON ID IMPRIMIR TEXTO"); sprintf(log_text, "SE IMPRIME EL TEXTO:\n\n %s\n", mensajeARecibir->texto); log_info_message(log_text); break; } case FINALIZACION_EJECUCION_PROGRAMA: { log_info_message( "\n---------------LLEGO UN MENSAJE DE FINALIZACION----------------\n"); log_info_message("\nLA EJECUCION DE ESTE PROGRAMA HA CONCLUIDO\n"); return EXIT_SUCCESS; break; } default: { log_info_message( "\n---------------LLEGO UN MENSAJE DESCONOCIDO A PROGRAMA----------------\n"); } } } return EXIT_SUCCESS; }
int main(int argc, char **argv) { DBusGConnection *bus = NULL; DBusGProxy *bus_proxy = NULL; GError *error = NULL; guint request_name_result = 0; WatchdogService *wservice = NULL; GOptionContext *lOptContext = NULL; int ret = 0; int log = LOG_MASK (LOG_ERR) | LOG_MASK (LOG_INFO); #ifdef DEBUG log = log | LOG_MASK(LOG_DEBUG); #endif openlog ("HM-WATCHDOG", 0x0, LOG_USER); setlogmask(log); g_type_init (); mainloop = g_main_loop_new(NULL, FALSE); lOptContext = g_option_context_new("- Wind River - System Health Monitor Watchdog"); g_option_context_add_main_entries(lOptContext, gOptEntries, NULL); g_option_context_parse(lOptContext, &argc, &argv, NULL); g_option_context_free(lOptContext); bus = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error); if (!bus) { log_error_message("could not connect to session bus\n", 0); if(error) g_error_free(error); ret = 1; goto res_free; } wservice = w_dbus_register_object(bus, WATCHDOG_TYPE_OBJECT, &dbus_glib_watchdog_service_object_info, WATCHDOG_SERVICE_PATH); bus_proxy = dbus_g_proxy_new_for_name(bus, DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS); #if 0 if (!org_freedesktop_DBus_request_name(driver_proxy, WATCHDOG_SERVICE, 0, &request_name_result, &error)) { g_assert (error != NULL); log_error_message ("failed to get name: %s\n", error->message); g_clear_error (&error); exit (1); } #else if (!dbus_g_proxy_call(bus_proxy, "RequestName", &error, G_TYPE_STRING, WATCHDOG_SERVICE, G_TYPE_UINT, 0, G_TYPE_INVALID, G_TYPE_UINT, &request_name_result, G_TYPE_INVALID)) { log_error_message("failed to acquire %s\n", WATCHDOG_SERVICE); ret = 1; goto res_free; } #endif g_timeout_add_seconds(TIMEOUT_INTERVAL, w_timeout, wservice); /* signal handlig */ signal(SIGINT, signalHandler); signal(SIGQUIT, signalHandler); signal(SIGABRT, signalHandler); signal(SIGTERM, signalHandler); /* Daemonize if it's the case */ if(gOptDaemonize) daemonize(); log_message("service started\n", 0); g_main_loop_run(mainloop); res_free: if(mainloop) g_main_loop_unref(mainloop); if(wservice) w_dbus_unregister_object(wservice, bus_proxy, bus); if(bus_proxy) g_object_unref(bus_proxy); log_message("watchdog service stopped\n", 0); closelog (); return ret; }
gint take_action(gchar * serviceName, gchar * serviceDbusPath, CorrectiveActionType corrActType){ gint r = 0; gchar * file_name = NULL; gchar * app_name = NULL; gchar * app_to_run = NULL; gchar ** corr_act_lst = NULL; gchar * action_type = NULL; gsize corr_act_lst_len = 0; gboolean isTarget = FALSE; g_return_if_fail(serviceName != NULL); g_return_if_fail(serviceDbusPath != NULL); /* Get absolute filename from appName */ file_name = resolve_file_name(serviceName); if (g_str_has_suffix(serviceName, ".target")) isTarget = TRUE; /* Parse CorrectiveAction string list from Unit Configuration File */ r = parse_corrective_action(file_name, &corr_act_lst, &corr_act_lst_len, corrActType, isTarget); if (r != 0){ goto free_res; } action_type = corr_act_lst[0]; log_debug_message("%s -> processing action '%s'\n", serviceName, action_type); /* PROCESSING CORRECTIVE ACTIONS */ if (g_str_equal(action_type, CORRECTIVE_ACTION_APP_STOP)){ if (isTarget) { /* For ".target" do NOT call AL to stop it, but workaround to call "systemctl stop" command */ char l_cmd[128]; int l_ret; sprintf(l_cmd, "systemctl stop %s", serviceName); l_ret = system(l_cmd); if (l_ret != 0) { log_error_message("Command '%s' FAILED! Exit code=%d\n", l_cmd, l_ret); } } else { /* For ".service" call AL to stop it */ /* but first find pid */ guint appPid = get_pid_from_app_path(serviceDbusPath); if (appPid <= 0){ r = 1; goto free_res; } r = call_AL_stop_app(appPid); if (r != 0){ goto free_res; } } } else if (g_str_equal(action_type, CORRECTIVE_ACTION_APP_RESTART)){ /* Get app.Name (without ".service" or ".target" suffix) */ app_name = resolve_app_name(serviceName); if (!app_name){ r = 1; goto free_res; } r = call_AL_restart_app(app_name); if (r!=0){ goto free_res; } } else if (g_str_equal(action_type, CORRECTIVE_ACTION_APP_RUN_APP)){ gchar * service_to_run = NULL; if (corr_act_lst_len < 2 || !corr_act_lst[1]){ log_error_message("In %s=%s service to run is not specified!\n", g_corr_act_type_key[corrActType], CORRECTIVE_ACTION_APP_RUN_APP); r = 1; goto free_res; } service_to_run = corr_act_lst[1]; app_to_run = resolve_app_name(service_to_run); if (!app_to_run){ r = 1; goto free_res; } r = call_AL_run_app(app_to_run); if (r!=0){ goto free_res; } } else if (g_str_equal(action_type, CORRECTIVE_ACTION_APP_REBOOT_SYS)){ r = call_AL_reboot_system(); if (r!=0){ goto free_res; } } else { log_error_message("CorrectiveAction=%s UNKNOWN ACTION\n", action_type); } free_res: if (file_name) g_free(file_name); if (app_name) g_free(app_name); if (app_to_run) g_free(app_to_run); if (corr_act_lst) g_strfreev(corr_act_lst); return r; }
static void *cpu_monitor(void *argv) { int read_count = 0, i; char buf[READ_FILE_MAX]; long long cpu_old[10], cpu_new[10]; long long old_cpu_time, new_cpu_time, idle_cpu_diff, total_cpu_diff; float cpu_usage = 0.0; char *p = NULL; int fd = open("/proc/stat", O_RDONLY); if(-1 == fd) { log_error_message("open /proc/stat fail"); return NULL; } read_count = read(fd, buf, READ_FILE_MAX - 1); if(read_count < 0) { log_error_message("read fail"); } buf[read_count] = '\0'; p = skip_token(buf); for(i = 0; i < 10; i++) { cpu_old[i] = strtoul(p, &p, 0); } close(fd); while(!g_exit) { sleep(1); fd = open("/proc/stat", O_RDONLY); if(-1 == fd) { log_error_message("open /proc/stat fail"); return NULL; } read_count = read(fd, buf, READ_FILE_MAX - 1); if(read_count < 0) { log_error_message("read fail"); } buf[read_count] = '\0'; p = skip_token(buf); for(i = 0; i < 10; i++) { cpu_new[i] = strtoul(p, &p, 10); } close(fd); old_cpu_time = 0; new_cpu_time = 0; for(i = 0; i < 10; i++) { old_cpu_time += cpu_old[i]; new_cpu_time += cpu_new[i]; } idle_cpu_diff = cpu_new[3] - cpu_old[3]; total_cpu_diff = new_cpu_time - old_cpu_time; if(0 != total_cpu_diff) { cpu_usage = 100 - ((float)100 * idle_cpu_diff)/total_cpu_diff; } else { cpu_usage = 0.0; } cpu_rate = cpu_usage; for (i = 0; i < 10; i++) { cpu_old[i] = cpu_new[i]; } } }
/* Application Launcher Daemon entrypoint */ int main(int argc, char **argv) { /* return code */ int l_ret; /* logging mechanism */ int log = LOG_MASK (LOG_ERR) | LOG_MASK (LOG_INFO); #ifdef DEBUG log = log | LOG_MASK(LOG_DEBUG); #endif openlog ("AL-DAEMON", 0x0, LOG_USER); setlogmask(log); /* handle signals */ signal(SIGTERM, AlSignalHandler); signal(SIGKILL, AlSignalHandler); /* parse cli options */ AlParseCLIOptions(argc, argv); if (g_stop) { AlDaemonShutdown(); return 0; } if (g_start) { /* daemonize the application launcher */ AlDaemonize(); log_message("Daemon process was started !\n", 0); #ifdef USE_LAST_USER_MODE /* initialise the last user mode */ if(!(l_ret=InitializeLastUserMode())){ log_error_message("Last user mode initialization failed !\n", 0); } else { log_message("Last user mode initialized. Listening for method calls ....\n", 0); } #endif /* initialize SRM Daemon */ if(!initialize_al_dbus()){ log_error_message("Failed to initialize AL Daemon!\n Stopping daemon ...", 0); terminate_al_dbus(); return 1; } /* start the signal dispatching thread */ al_dbus_signal_dispatcher(); /* main loop */ GMainLoop *l_loop = NULL; if(!(l_loop = g_main_loop_new(NULL, FALSE))){ log_error_message("Error creating main loop !\n", 0); exit(1); } /* run the main loop */ g_main_loop_run(l_loop); } log_message("Daemon exited !\n", 0); /* close logging mechanism */ closelog (); /* free res */ terminate_al_dbus(); return 0; }