Esempio n. 1
0
//
//	Called to rotate the access log
//
void MaHost::rotateLog()
{
	struct stat	sbuf;
	char		fileBuf[MPR_MAX_FNAME];
	struct tm	tm;
	time_t		when;

	//
	//	Rotate logs when full
	//
	if (fstat(logFd, &sbuf) == 0 && sbuf.st_mode & S_IFREG && 
			(unsigned) sbuf.st_size > maxSize) {

		char bak[MPR_MAX_FNAME];

		time(&when);
		mprGmtime(&when, &tm);

		mprSprintf(bak, sizeof(bak), "%s-%02d-%02d-%02d-%02d:%02d:%02d", 
			logPath, 
			tm->tm_mon, tm->tm_mday, tm->tm_year, tm->tm_hour, tm->tm_min, 
			tm->tm_sec);

		close(logFd);
		rename(logPath, bak);
		unlink(logPath);

		logFd = open(logPath, O_CREAT | O_TRUNC | O_WRONLY | O_TEXT, 0664);
		logConfig();
	}
}
Esempio n. 2
0
int MprLogToFile::start()
{
	logConfig();
	timer = new MprTimer(MPR_TIMEOUT_LOG_STAMP, writeTimeStampWrapper, 
		(void*) this);
	return 0;
}
Esempio n. 3
0
INITIALIZE_EASYLOGGINGPP

void InitializeLogger( CAppNodeImpl *applicationIn )
{
	// Load logger config file
	el::Configurations logConfig( ELOG_CONFIG_PATH );

	// Set configuration
	el::Loggers::reconfigureAllLoggers( logConfig );

	LOG( INFO ) << "<-------------------------------->";
	LOG( INFO ) << "<--------" << applicationIn->GetName();
	LOG( INFO ) << "<-------------------------------->";
}
Esempio n. 4
0
void MainWindow::load()
{
	console = new CConsoleHandler;
	CBasicLogConfigurator logConfig(VCMIDirs::get().userCachePath() / "VCMI_Launcher_log.txt", console);
	logConfig.configureDefault();

	CResourceHandler::initialize();
	CResourceHandler::load("config/filesystem.json");

	for (auto & string : VCMIDirs::get().dataPaths())
		QDir::addSearchPath("icons", pathToQString(string / "launcher" / "icons"));
	QDir::addSearchPath("icons", pathToQString(VCMIDirs::get().userDataPath() / "launcher" / "icons"));

	settings.init();
}
Esempio n. 5
0
void MprLogToFile::rotate()
{
	char bak[MPR_MAX_FNAME];

	mprSprintf(bak, sizeof(bak), "%s.old", logFileName);
	unlink(bak);

	mprFprintf(logFd, "Log size reached limit. Rotating\n");
	close(logFd);
	if (rename(logFileName, bak) != 0) {
		unlink(logFileName);
	}
	logFd = open(logFileName, O_CREAT | O_TRUNC | O_WRONLY | O_TEXT, 0664);
	rotationCount++;
	logConfig();
}
Esempio n. 6
0
int main(){
  pid_t pid, sid;
  int       list_s;                /*  listening socket          */
  int       conn_s;                /*  connection socket         */
  short int port = 1995;                  /*  port number               */
  struct    sockaddr_in servaddr;  /*  socket address structure  */
  int i;
  uint8_t numClients = 0;
  threadInfo* info;

  /* Fork off the parent process */
  pid = fork();
  if(pid < 0) {
    exit(EXIT_FAILURE);
  }

  /* If we got a good PID, then we can exit the parent process */
  if(pid > 0){
    exit(EXIT_SUCCESS);
  }

  umask(0);

  printf("Daemon started.  Writing all further notices to daemon log: /var/log/daemon.log\n");

  // Enable Signal Handler
  signal(SIGTERM, catch_term);

  /* Open Log File Here */
  openlog("SEASSERVER",LOG_PID,LOG_DAEMON);
  syslog(LOG_DAEMON|LOG_INFO,"Daemon Started.");

  /* Open Config File Here */
  if(!readConfig()){
    syslog(LOG_DAEMON|LOG_ERR,"Unable to Read Configuration File.  Daemon Terminated.\n");
    exit(EXIT_FAILURE);
  }

  /* Create a new SID for the child process */
  sid = setsid();
  if(sid < 0){
    syslog(LOG_DAEMON|LOG_ERR,"Unable to create a new SID for child process. Daemon Terminated.");
    exit(EXIT_FAILURE);
  }

  /* Change the current working directory */
  if((chdir("/")) < 0){
    syslog(LOG_DAEMON|LOG_ERR,"Unable to switch working directory. Daemon Terminated.");
    exit(EXIT_FAILURE);
  }

  close(STDIN_FILENO);
  close(STDOUT_FILENO);
  close(STDERR_FILENO);

  /* Setup TCP/IP Socket */
  if((list_s = socket(AF_INET, SOCK_STREAM, 0)) < 0){
      syslog(LOG_DAEMON|LOG_ERR,"Unable to create socket. Daemon Terminated.");
      exit(EXIT_FAILURE);
  }

  memset(&servaddr, 0, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(port);

#ifdef DEBUG
  syslog(LOG_DAEMON|LOG_INFO,"Opening Spectrometers.");
#endif
  // Power Cycle GPIO for USB Hub to make sure USB ports initialized correctly
  //system("echo 0 > /sys/class/gpio/gpio168/value");
  //sleep(3);
  //system("echo 1 > /sys/class/gpio/gpio168/value");
  //sleep(3);
  // Connect the USB Spectrometers
  char *serialNumbers[NUM_SPECS] = {getSerialNumber(0),getSerialNumber(1)};
  if(connectSpectrometers(serialNumbers) == CONNECT_ERR)
  {
      syslog(LOG_DAEMON|LOG_ERR,"Spectrometers could not be opened.  Daemon Exiting");
      exit(EXIT_FAILURE);
  }
#ifdef DEBUG
  syslog(LOG_DAEMON|LOG_INFO,"Spectrometers Opened.");
#endif

  applyConfig();
  logConfig();

  // Start LON Dispatch
  syslog(LOG_DAEMON|LOG_INFO,"Starting LON Connection.");
  if(startDispatch(LONPORT) == -1){
      syslog(LOG_DAEMON|LOG_ERR,"LON Not Connected!  Check serial port.");
      exit(EXIT_FAILURE);
  } else {
    syslog(LOG_DAEMON|LOG_INFO,"LON Connection Started.");
  }

  // Init Bench Config and Power Management GPIOs (See SEASPeriperalCommands.c)
  readBenchConfig();
  initPeripherals();

  // Start CTD Sink
  CTDSink* ctdSink = CTDSink::Instance();

  /*  Bind our socket addresss to the
	listening socket, and call listen()  */

  if ( bind(list_s, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 ) {
    syslog(LOG_DAEMON|LOG_ERR,"Unable to bind socket. Daemon Terminated.");
    exit(EXIT_FAILURE);
  }

  if ( listen(list_s, NUM_THREADS) < 0 ) {
    syslog(LOG_DAEMON|LOG_ERR,"Unable to listen on socket. Daemon Terminated.");
    exit(EXIT_FAILURE);
  }

  for(i=0; i < NUM_THREADS; i++)
      thread_bin_available[i] = AVAILABLE;

  execMode();

  while(keep_going){
    syslog(LOG_DAEMON|LOG_INFO,"Listening for connection on port %i", port);
    /* Wait for TCP/IP Connection */
    conn_s = accept(list_s, NULL, NULL);
    if ( conn_s < 0 ) {
        syslog(LOG_DAEMON|LOG_ERR,"Unable to call accept() on socket.");
        break;
    }

    /* Spawn a POSIX Server Thread to Handle Connected Socket */
    for(i=0; i < NUM_THREADS; i++){
        if(thread_bin_available[i]){
            thread_bin_available[i] = UNAVAILABLE;
            syslog(LOG_DAEMON|LOG_INFO,"Handling new connection on port %i",port);
            numClients++;
            info = (threadInfo*)malloc(sizeof(threadInfo));
            info->socket_connection = conn_s;
            info->thread_bin_index = i;
            pthread_create(&thread_bin[i],NULL,handleConnection, (void*)info);
            break;
        }
    }

    if(i > NUM_THREADS){
        syslog(LOG_DAEMON|LOG_ERR,"Unable to create thread to handle connection.  Continuing...");
    }
    
  }
  
  if(disconnectSpectrometers() == CONNECT_OK)
    syslog(LOG_DAEMON|LOG_INFO,"Spectrometers Successfully Disconnected");
  else
    syslog(LOG_DAEMON|LOG_ERR,"Unable to Disconnect Spectrometers");

  syslog(LOG_DAEMON|LOG_INFO,"Daemon Exited Politely.");
  exit(EXIT_SUCCESS);

}
Esempio n. 7
0
File: CMT.cpp Progetto: yzliang/vcmi
int main(int argc, char** argv)
#endif
{
#ifdef __APPLE__
	// Correct working dir executable folder (not bundle folder) so we can use executable relative pathes
    std::string executablePath = argv[0];
    std::string workDir = executablePath.substr(0, executablePath.rfind('/'));
    chdir(workDir.c_str());
    
    // Check for updates
    OSX_checkForUpdates();

    // Check that game data is prepared. Otherwise run vcmibuilder helper application
    FILE* check = fopen((VCMIDirs::get().localPath() + "/game_data_prepared").c_str(), "r");
    if (check == nullptr) {
        system("open ./vcmibuilder.app");
        return 0;
    }
    fclose(check);
#endif
    std::cout << "Starting... " << std::endl;
	po::options_description opts("Allowed options");
	opts.add_options()
		("help,h", "display help and exit")
		("version,v", "display version information and exit")
		("battle,b", po::value<std::string>(), "runs game in duel mode (battle-only")
		("start", po::value<std::string>(), "starts game from saved StartInfo file")
		("onlyAI", "runs without human player, all players will be default AI")
		("noGUI", "runs without GUI, implies --onlyAI")
		("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
		("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
		("autoSkip", "automatically skip turns in GUI")
		("disable-video", "disable video player")
		("nointro,i", "skips intro movies");

	if(argc > 1)
	{
		try
		{
			po::store(po::parse_command_line(argc, argv, opts), vm);
		}
		catch(std::exception &e) 
		{
            std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
		}
	}

	po::notify(vm);
	if(vm.count("help"))
	{
		prog_help(opts);
		return 0;
	}
	if(vm.count("version"))
	{
		prog_version();
		return 0;
	}
	if(vm.count("noGUI"))
	{
		gNoGUI = true;
		vm.insert(std::pair<std::string, po::variable_value>("onlyAI", po::variable_value()));
	}

	//Set environment vars to make window centered. Sometimes work, sometimes not. :/
	putenv((char*)"SDL_VIDEO_WINDOW_POS");
	putenv((char*)"SDL_VIDEO_CENTERED=1");

	// Have effect on X11 system only (Linux).
	// For whatever reason in fullscreen mode SDL takes "raw" mouse input from DGA X11 extension
	// (DGA = Direct graphics access). Because this is raw input (before any speed\acceleration proceesing)
	// it may result in very small \ very fast mouse when game in fullscreen mode
	putenv((char*)"SDL_VIDEO_X11_DGAMOUSE=0");

    // Init old logging system and new (temporary) logging system
	CStopWatch total, pomtime;
	std::cout.flags(std::ios::unitbuf);
	console = new CConsoleHandler;
	*console->cb = boost::bind(&processCommand, _1);
	console->start();
	atexit(dispose);

	CBasicLogConfigurator logConfig(VCMIDirs::get().userCachePath() + "/VCMI_Client_log.txt", console);
    logConfig.configureDefault();
	logGlobal->infoStream() <<"Creating console "<<pomtime.getDiff();

    // Init filesystem and settings
	preinitDLL(::console);
    settings.init();

    // Initialize logging based on settings
    logConfig.configure();

	// Some basic data validation to produce better error messages in cases of incorrect install
	auto testFile = [](std::string filename, std::string message) -> bool
	{
		if (CResourceHandler::get()->existsResource(ResourceID(filename)))
			return true;

        logGlobal->errorStream() << "Error: " << message << " was not found!";
		return false;
	};

	if (!testFile("DATA/HELP.TXT", "Heroes III data") &&
	    !testFile("MODS/VCMI/MOD.JSON", "VCMI mod") &&
	    !testFile("DATA/StackQueueBgBig.PCX", "VCMI data"))
		exit(1); // These are unrecoverable errors

	// these two are optional + some installs have them on CD and not in data directory
	testFile("VIDEO/GOOD1A.SMK", "campaign movies");
	testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds

	conf.init();
    logGlobal->infoStream() <<"Loading settings: "<<pomtime.getDiff();
    logGlobal->infoStream() << NAME;

	srand ( time(nullptr) );
	

	const JsonNode& video = settings["video"];
	const JsonNode& res = video["screenRes"];

	//something is really wrong...
	if (res["width"].Float() < 100 || res["height"].Float() < 100)
	{
        logGlobal->errorStream() << "Fatal error: failed to load settings!";
        logGlobal->errorStream() << "Possible reasons:";
        logGlobal->errorStream() << "\tCorrupted local configuration file at " << VCMIDirs::get().userConfigPath() << "/settings.json";
        logGlobal->errorStream() << "\tMissing or corrupted global configuration file at " << VCMIDirs::get().userConfigPath() << "/schemas/settings.json";
        logGlobal->errorStream() << "VCMI will now exit...";
		exit(EXIT_FAILURE);
	}

	if(!gNoGUI)
	{
		if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
		{
			logGlobal->errorStream()<<"Something was wrong: "<< SDL_GetError();
			exit(-1);
		}
		atexit(SDL_Quit);
		setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
		logGlobal->infoStream() <<"\tInitializing screen: "<<pomtime.getDiff();
	}


	CCS = new CClientState;
	CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
	// Initialize video
#if DISABLE_VIDEO
	CCS->videoh = new CEmptyVideoPlayer;
#else
	if (!gNoGUI && !vm.count("disable-video"))
		CCS->videoh = new CVideoPlayer;
	else
		CCS->videoh = new CEmptyVideoPlayer;
#endif

    logGlobal->infoStream()<<"\tInitializing video: "<<pomtime.getDiff();



	//we can properly play intro only in the main thread, so we have to move loading to the separate thread
	boost::thread loading(init);

	if(!gNoGUI )
	{
		if(!vm.count("battle") && !vm.count("nointro"))
			playIntro();
		SDL_FillRect(screen,nullptr,0);
	}

	CSDL_Ext::update(screen);
	loading.join();
    logGlobal->infoStream()<<"Initialization of VCMI (together): "<<total.getDiff();

	if(!vm.count("battle"))
	{
		Settings session = settings.write["session"];
		session["autoSkip"].Bool()  = vm.count("autoSkip");
		session["oneGoodAI"].Bool() = vm.count("oneGoodAI");

		std::string fileToStartFrom; //none by default
		if(vm.count("start"))
			fileToStartFrom = vm["start"].as<std::string>();

		if(fileToStartFrom.size() && boost::filesystem::exists(fileToStartFrom))
			startGameFromFile(fileToStartFrom); //ommit pregame and start the game using settings from fiel
		else
		{
			if(fileToStartFrom.size())
			{
                logGlobal->warnStream() << "Warning: cannot find given file to start from (" << fileToStartFrom
                    << "). Falling back to main menu.";
			}
			GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
		}
	}
	else
	{
		auto  si = new StartInfo();
		si->mode = StartInfo::DUEL;
		si->mapname = vm["battle"].as<std::string>();
		si->playerInfos[PlayerColor(0)].color = PlayerColor(0);
		si->playerInfos[PlayerColor(1)].color = PlayerColor(1);
		startGame(si);
	}

	if(!gNoGUI)
	{
		mainGUIThread = new boost::thread(&CGuiHandler::run, &GH);
		listenForEvents();
	}
	else
	{
		while(true)
			boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
	}

	return 0;
}