コード例 #1
0
ファイル: XInterface.unix.cpp プロジェクト: AlainRoy/htcondor
void
XInterface::ReadUtmp() {
#if USES_UTMPX
	struct utmpx utmp_entry;
#else
	struct utmp utmp_entry;
#endif

	if ( logged_on_users ) {
		for (int foo =0; foo <= logged_on_users->getlast(); foo++) {
			delete[] (*logged_on_users)[foo];
		}
		delete logged_on_users;
	}

	logged_on_users = new ExtArray< char * >;


	// fopen the Utmp.  If we fail, bail...
	if ((utmp_fp=safe_fopen_wrapper(UtmpName,"r")) == NULL) {
		if ((utmp_fp=safe_fopen_wrapper(AltUtmpName,"r")) == NULL) {                      
			EXCEPT("fopen of \"%s\" (and \"%s\") failed!", UtmpName,
				AltUtmpName);                        
		}                             
	}                                 
 
	while(fread((char *)&utmp_entry,
#if USES_UTMPX
		sizeof( struct utmpx ),
#else
		sizeof( struct utmp ),
#endif
		1, utmp_fp)) {

		if (utmp_entry.ut_type == USER_PROCESS) {
			bool _found_it = false;
			for (int i=0; (i<=logged_on_users->getlast()) && (! _found_it); i++) {
				if (!strcmp(utmp_entry.ut_user, (*logged_on_users)[i])) {
					_found_it = true;
				}
			}
			if (! _found_it) {
				dprintf(D_FULLDEBUG, "User %s is logged in.\n",
					utmp_entry.ut_user );
				(*logged_on_users)[logged_on_users->getlast()+1] =
					strnewp( utmp_entry.ut_user );
			}
		}
	}
	int fclose_ret = fclose( utmp_fp );
 	if( fclose_ret ) {
		EXCEPT("fclose of \"%s\" (or \"%s\") failed! "
			"This message brought to you by the fatal error %d",
			UtmpName, AltUtmpName, errno);
	}

	return;
}
コード例 #2
0
// *****************************************
// Linux hibernator "Sys IF" class methods
// *****************************************
bool
SysIfLinuxHibernator::Detect ( void )
{
	FILE	*fp;
	char	buf[128];

	memset( buf, 0, sizeof(buf) );

	// Look at the "/sys" file(s)
	fp = safe_fopen_wrapper( SYS_POWER_FILE, "r" );
	if ( NULL == fp ) {
		return false;
	}

	if ( fgets( buf, sizeof(buf)-1, fp ) ) {
		strip(buf);
		char	*token, *save = NULL;

		token = strtok_r( buf, " ", &save );
		while( token ) {
			m_hibernator->addState( token );
			token = strtok_r( NULL, " ", &save );
		}
	}
	fclose( fp );

	// If we can't read the disk file, we've had at least some success, right?
	fp = safe_fopen_wrapper( SYS_DISK_FILE, "r" );
	if ( NULL == fp ) {
		return true;
	}
	if ( fgets( buf, sizeof(buf)-1, fp ) ) {
		strip(buf);
		char	*token, *save = NULL;

		token = strtok_r( buf, " ", &save );
		while( token ) {
			int len = strlen( token );
			if ( token[0] == '[' && token[len] == ']' ) {
				token[len] = '\0';
				token++;
			}
			if ( strcmp( token, "platform" ) == 0 ) {
				m_hibernator->addState( HibernatorBase::S4 );
			}
			else if ( strcmp( token, "shutdown" ) == 0 ) {
				m_hibernator->addState( HibernatorBase::S5 );
			}
			token = strtok_r( NULL, " ", &save );
		}
	}
	fclose( fp );

	return true;
}
コード例 #3
0
int
InitJobAd(int cluster, int proc)
{
  if (!JobAd) {   // just get the job ad from the schedd once

	if ( IpcFile ) {
		// get the jobad file a file
		priv_state priv = set_condor_priv();
		bool is_stdin = false;
		FILE* ipc_fp = NULL;
		if( IpcFile[0] == '-' && IpcFile[1] == '\0' ) {
			ipc_fp = stdin;
			is_stdin = true;
		} else {
			ipc_fp = safe_fopen_wrapper(IpcFile,"r");
		}
		dprintf( D_FULLDEBUG, "Reading job ClassAd from %s\n",
				 is_stdin ? "STDIN" : IpcFile );
		int isEOF = 0;
		int isError = 0;
		int isEmpty = 0;
		if ( ipc_fp ) {
			JobAd = new ClassAd(ipc_fp,"***",isEOF,isError,isEmpty);
			if( ! is_stdin ) {
				fclose( ipc_fp );
				unlink( IpcFile );
			}
		}
		set_priv(priv);
		// if constructor failed, remove the JobAd, and
		// fallback on getting it via sockets.
		if (isError != 0 ) {
			if (JobAd) delete JobAd;
			JobAd = NULL;
		}
		if (JobAd) {
			// we're done
			checkForDebugging( JobAd );
			return 0;
		}

		// if we made it here, we wanted to get the job ad
		// via the file, but failed
		dprintf(D_FULLDEBUG,
			"Failed to read job ad file %s, using socket\n",
			IpcFile);
	}

	if (!ConnectQ(schedd, SHADOW_QMGMT_TIMEOUT, true)) {
		EXCEPT("Failed to connect to schedd!");
	}
	JobAd = GetJobAd( cluster, proc );
	DisconnectQ(NULL);
	checkForDebugging( JobAd );
  }
  if (!JobAd) {
	EXCEPT( "failed to get job ad" );
  }
  return 0;
}
コード例 #4
0
void
XferSummary::log_transfer(time_t now, transferinfo *tinfo, bool success_flag,
						  struct in_addr peer, int xfer_size)
{
	struct tm *tm;
	char peer_IP[20];

	if (log_file == 0) {
		log_file = safe_fopen_wrapper("TransferLog", "a");
	}
	if (log_file == 0) {
		return;
	}

	tm = localtime( &now );
	// make local copy of peer address to avoid calling inet_ntoa twice in
	// fprintf below
	strcpy(peer_IP, inet_ntoa(peer));
	fprintf( log_file, "%d/%d %02d:%02d:%02d ", tm->tm_mon + 1, tm->tm_mday,
			tm->tm_hour, tm->tm_min, tm->tm_sec );
	fprintf( log_file, "%s %s %d bytes %d sec %s %s@%s\n",
			(tinfo->status == RECV ? "R" : "S"),
			(success_flag ? "S" : "F"),
			xfer_size,
			(int) (now - tinfo->start_time),
			peer_IP,
			tinfo->owner,
			inet_ntoa(tinfo->shadow_addr));
	fflush( log_file );
}
コード例 #5
0
ファイル: credd.cpp プロジェクト: blueskyll/condor
int
SaveCredentialList() {
  priv_state priv = set_root_priv();
  FILE * fp = safe_fopen_wrapper(cred_index_file, "w");
  if (!fp) {
    set_priv (priv);
    dprintf (D_ALWAYS, "Unable to open credential index file %s!\n", cred_index_file);
    return FALSE;
  }


  classad::ClassAdXMLUnParser unparser;
  CredentialWrapper * pCred = NULL;

  // Clear the old list
  credentials.Rewind();
  while (credentials.Next(pCred)) {
    const classad::ClassAd * pclassad = pCred->cred->GetMetadata();
	classad::ClassAd temp_classad(*pclassad); // lame
    std::string buff;
    unparser.Unparse (buff, &temp_classad);
    fprintf (fp, "%s\n", buff.c_str());
  }

  fclose (fp);
  
  set_priv (priv);
  return TRUE;
}
コード例 #6
0
void write_file(const char * filename, const char * data) {
    FILE * f = safe_fopen_wrapper(filename, "w");
    if( ! f ) {
        die("Failed to open output");
    }
    fprintf(f, "%s\n", data);
    fclose(f);
}
コード例 #7
0
ファイル: Job.cpp プロジェクト: blueskyll/condor
// specialization: this GetFullAd has to retrieve its classad attributes
// from the history file based on index pointers
void
HistoryJobImpl::GetFullAd ( ClassAd& _ad) const
{
    // fseek to he.start
    // ClassAd method to deserialize from a file with "***"

    FILE * hFile;
    int end = 0;
    int error = 0;
    int empty = 0;
    std::ostringstream buf;
    // placeholder in case we want to expose error details to UI
    std::string text;

    // TODO: move the ClassAd/file deserialize back to HistoryFile???
    const char* fName = m_he.file.c_str();
    if ( ! ( hFile = safe_fopen_wrapper ( fName, "r" ) ) )
    {
        buf <<  "unable to open history file " << m_he.file;
        text = buf.str();
        dprintf ( D_ALWAYS, "%s\n", text.c_str());
        _ad.Assign("JOB_AD_ERROR",text.c_str());
        return;
    }
    if ( fseek ( hFile , m_he.start , SEEK_SET ) )
    {
        buf << "bad seek in " << m_he.file << " at " << m_he.start;
        text = buf.str();
        dprintf ( D_ALWAYS, "%s\n", text.c_str());
        _ad.Assign("JOB_AD_ERROR",text.c_str());
        return;
    }

    ClassAd myJobAd ( hFile, "***", end, error, empty );
    fclose ( hFile );

    // TODO: debug logging and error to i/f for now
    // we might not have our original history file anymore
    if ( error )
    {
        buf <<  "malformed ad for job '" << m_job->GetKey() << "' in " << m_he.file;
        text = buf.str();
        dprintf ( D_FULLDEBUG, "%s\n", text.c_str());
        _ad.Assign("JOB_AD_ERROR",text.c_str());
        return;
    }
    if ( empty )
    {
        buf << "empty ad for job '" << m_job->GetKey() << "' in " << m_he.file;
        text = buf.str();
        dprintf ( D_FULLDEBUG,"%s\n", text.c_str());
        _ad.Assign("JOB_AD_ERROR",text.c_str());
        return;
    }

    _ad = myJobAd;

}
コード例 #8
0
static void
serialize_input( void )
{

	char sinful[16 + 10];
	int  found_eof		= 0,
		 found_error	= 0,
		 empty			= 0;

	/**	Determine if we are using the command-line options, a file,
		or standard input as input */
	if ( !stdio ) {

		/**	Contrive a sinful string based on our IP address */
		sprintf ( sinful, "<255.255.255.255:1234>" );

		/**	We were give all the raw data, so we're going to create
			a fake machine ad that we will use when invoking the waking
			mechanism */
		ad = new ClassAd ();
		ad->SetMyTypeName ( STARTD_ADTYPE );
		ad->SetTargetTypeName ( JOB_ADTYPE );
		ad->Assign ( ATTR_HARDWARE_ADDRESS, mac );
		ad->Assign ( ATTR_SUBNET_MASK, mask );
		ad->Assign ( ATTR_MY_ADDRESS, sinful );
		ad->Assign ( ATTR_WOL_PORT, port );

	} else {

		/**	Open the machine ad file or read it from stdin */
		if ( fn_in && *fn_in ) {
			in = safe_fopen_wrapper ( fn_in, "r" );
		} else {
			in = stdin;
			fn_in = "<stdin>";
		}

		if ( !in ) {
			error ( E_FOPEN, fn_in, strerror ( errno ), errno );
		}

		/**	Serialize the machine ad from a file */
		ad = new ClassAd (
			in,
			"?$#%^&*@", /* sufficiently random garbage? */
			found_eof,
			found_error,
			empty );

		if ( found_error ) {
			error (
				E_CLASSAD,
				found_error );
		}

	}

}
コード例 #9
0
int
MultiFileCurlPlugin::BuildTransferRequests(const std::string &input_filename, std::vector<std::pair<std::string, transfer_request>> &requested_files) const {
    CondorClassAdFileIterator adFileIter;
    FILE* input_file;

    // Read input file containing data about files we want to transfer. Input
    // data is formatted as a series of classads, each with an arbitrary number
    // of inputs.
    input_file = safe_fopen_wrapper( input_filename.c_str(), "r" );
    if( input_file == NULL ) {
        fprintf( stderr, "Unable to open curl_plugin input file %s.\n", 
            input_filename.c_str() );
        return 1;
    }

    if( !adFileIter.begin( input_file, false, CondorClassAdFileParseHelper::Parse_new )) {
        fprintf( stderr, "Failed to start parsing classad input.\n" );
        return 1;
    }
    else {
        // Iterate over the classads in the file, and insert each one into our
        // requested_files map, with the key: url, value: additional details 
        // about the transfer.
        ClassAd transfer_file_ad;
        std::string local_file_name;
        std::string url;
        transfer_request request_details;
        std::pair< std::string, transfer_request > this_request;

        int count = 0;
        while ( adFileIter.next( transfer_file_ad ) > 0 ) {
            transfer_file_ad.EvaluateAttrString( "LocalFileName", local_file_name );
            transfer_file_ad.EvaluateAttrString( "Url", url );
            request_details.local_file_name = local_file_name;

            if (url.substr(0, 7) == "davs://") {
                url = std::string("https://") + url.substr(7);
            } else if (url.substr(0, 6) == "dav://") {
                url = std::string("http://") + url.substr(6);
            }

            this_request = std::make_pair( url, request_details );
            requested_files.push_back( this_request );
            count ++;
            if ( _diagnostic ) {
                fprintf( stderr, "Will transfer between URL %s and local file %s.\n", url.c_str(), local_file_name.c_str() );
            }
        }
        if ( _diagnostic ) {
            fprintf( stderr, "There are a total of %d files to transfer.\n", count );
        }
    }
    fclose(input_file);

    return 0;
}
コード例 #10
0
ファイル: credd.cpp プロジェクト: blueskyll/condor
int
LoadCredentialList () {
  CredentialWrapper * pCred;

  // Clear the old list
  if (!credentials.IsEmpty()) {
    credentials.Rewind();
    while (credentials.Next(pCred)) {
      credentials.DeleteCurrent();
      delete pCred;
    }
  }

  credentials.Rewind();
  
  classad::ClassAdXMLParser parser;
  char buff[50000];
  
  priv_state priv = set_root_priv();

  FILE * fp = safe_fopen_wrapper(cred_index_file, "r");
  
  if (!fp) {
    dprintf (D_FULLDEBUG, "Credential database %s does not exist!\n", cred_index_file);
    set_priv (priv);
    return TRUE;
  }

  while (fgets(buff, 50000, fp)) {
    if ((buff[0] == '\n') || (buff[0] == '\r')) {
      continue;
    }
    
	classad::ClassAd * classad = parser.ParseClassAd (buff);
    int type=0;

    if ((!classad) || (!classad->EvaluateAttrInt ("Type", type))) {
      dprintf (D_ALWAYS, "Invalid classad %s\n", buff);
      set_priv (priv);
      fclose (fp);
      return FALSE;
    }

    if (type == X509_CREDENTIAL_TYPE) {
      pCred = new X509CredentialWrapper (*classad);
      credentials.Append (pCred);
    }
    else {
      dprintf (D_ALWAYS, "Invalid type %d\n",type); 
    }
  }
  fclose (fp);
  set_priv (priv);

  return TRUE;
}
コード例 #11
0
//! Gets the writer password required by the quill++
//  daemon to access the database
static MyString getWritePassword(const char *write_passwd_fname, 
							   const char *host, const char *port, 
							   const char *db,
							   const char *dbuser) {
	FILE *fp = NULL;
	MyString passwd;
	int len;
	MyString prefix;
	MyString msbuf;
	const char *buf;
	bool found = FALSE;

		// prefix is for the prefix of the entry in the .pgpass
		// it is in the format of the following:
		// host:port:db:user:password

	prefix.sprintf("%s:%s:%s:%s:", host, port, db, dbuser);

	len = prefix.Length();

	fp = safe_fopen_wrapper(write_passwd_fname, "r");

	if(fp == NULL) {
		EXCEPT("Unable to open password file %s\n", write_passwd_fname);
	}
	
		//dprintf(D_ALWAYS, "prefix: %s\n", prefix);

	while(msbuf.readLine(fp)) {
		msbuf.chomp();
		buf = msbuf.Value();

			//fprintf(stderr, "line: %s\n", buf);

			// check if the entry matches the prefix
		if (strncmp(buf, prefix.Value(), len) == 0) {
				// extract the password
			passwd = msbuf.Substr(len, msbuf.Length());
			found = TRUE;

			break;
		}

	}

    fclose(fp);
	if (!found) {
		EXCEPT("Unable to find password from file %s\n", write_passwd_fname);
	}

	return passwd;
}
コード例 #12
0
ファイル: xen_type.linux.cpp プロジェクト: emaste/htcondor
bool
VirshType::createCkptFiles(void)
{
	vmprintf(D_FULLDEBUG, "Inside VirshType::createCkptFiles\n");

	// This function will suspend a running VM.
	if( getVMStatus() == VM_STOPPED ) {
		vmprintf(D_ALWAYS, "createCkptFiles is called for a stopped VM\n");
		return false;
	}

	if( getVMStatus() == VM_RUNNING ) {
		if( Suspend() == false ) {
			return false;
		}
	}

	if( getVMStatus() == VM_SUSPENDED ) {
		// we create timestampfile
		time_t current_time = time(NULL);
		MyString timestampfile(m_suspendfile);
		timestampfile += XEN_CKPT_TIMESTAMP_FILE_SUFFIX;

		FILE *fp = safe_fopen_wrapper(timestampfile.Value(), "w");
		if( !fp ) {
			vmprintf(D_ALWAYS, "failed to safe_fopen_wrapper file(%s) for "
					"checkpoint timestamp : safe_fopen_wrapper returns %s\n",
					timestampfile.Value(), strerror(errno));
			Resume();
			return false;
		}
		if( fprintf(fp, "%d\n", (int)current_time) < 0 ) {
			fclose(fp);
			unlink(timestampfile.Value());
			vmprintf(D_ALWAYS, "failed to fprintf for checkpoint timestamp "
					"file(%s:%s)\n", timestampfile.Value(), strerror(errno));
			Resume();
			return false;
		}
		fclose(fp);

		// checkpoint succeeds
		m_is_checkpointed = true;
		return true;
	}

	return false;
}
コード例 #13
0
void main_init(int  argc , char *  argv  [])
{
	char *testfile = NULL;
	ClassAd *inputAd = NULL;
	int i;

	dprintf(D_ALWAYS, "main_init() called\n");

	for (i=1; i<argc; i++ ) {
	
		if (match_prefix(argv[i],"-withfile")) {
			i++;
			if (argc <= i) {
				fprintf(stderr,
						"ERROR: Argument -withfile requires a parameter\n ");
				exit(1);
			}
			testfile = argv[i];
		}
	
	}	// end of parsing command line options

	if ( testfile ) {
		FILE* fp = safe_fopen_wrapper(testfile,"r");
		if (!fp) {
			fprintf(stderr,"ERROR: Unable to open test file %s\n",
					testfile);
			DC_Exit(1);
		}
		int EndFlag=0, ErrorFlag=0, EmptyFlag=0;
        if( !( inputAd=new ClassAd(fp,"***", EndFlag, ErrorFlag, EmptyFlag) ) ){
            fprintf( stderr, "ERROR:  Out of memory\n" );
            DC_Exit( 1 );
        }
		fclose(fp);
		if ( ErrorFlag || EmptyFlag ) {
			fprintf( stderr, "ERROR - file %s does not contain a parseable ClassAd\n",
					 testfile);
			DC_Exit(1);
		}
		// since this option is for testing, process then exit
		ClassAd * resultAd =  process_request(inputAd);
		dPrintAd(D_ALWAYS, *resultAd);
		DC_Exit( 0 );
	}
}
コード例 #14
0
bool
check_create_file(const char *file, mode_t mode)
{
	if( !file || file[0] == '\0' ) {
		return false;
	}

	FILE *fp = NULL;

	fp = safe_fopen_wrapper(file, "w", mode);
	if( !fp ) {
		dprintf(D_ALWAYS, "failed to safe_fopen_wrapper %s in write mode: "
				"safe_fopen_wrapper returns %s\n", file, strerror(errno));
		return false;
	}

	fclose(fp);
	return true;
}
コード例 #15
0
/* Helper function: encode file filename into the resultAd as attribute attrname */
bool
stash_output_file(ClassAd* resultAd, const char* filename, const char* attrname)
{
	ASSERT(filename);
	ASSERT(attrname);
	ASSERT(resultAd);

	FILE *fp = safe_fopen_wrapper(filename,"r");
	if (!fp) return false;

	/* get the file size */
    fseek (fp, 0 , SEEK_END);
    long file_size = ftell (fp);
    rewind (fp);
   
	char *buffer = NULL;
	if ( file_size > 0 ) {
		/* allocate memory to contain the whole file */
		buffer = (char*) malloc (file_size);
		ASSERT(buffer);
		
		/* read the file into the buffer. */
		fread(buffer,1,file_size,fp);    

		/* Encode - note caller needs to free the returned pointer */
		char* encoded_data = condor_base64_encode((const unsigned char*)buffer, file_size);

		/* Shove into ad */
		if ( encoded_data ) {
			resultAd->Assign(attrname,encoded_data);
			free(encoded_data);
		}
	} else {
		resultAd->Assign(attrname,"");
	}

	if (buffer) free(buffer);
	fclose(fp);

	return true;
}
コード例 #16
0
FILE *
MultiFileCurlPlugin::OpenLocalFile(const std::string &local_file, const char *mode) const {
    FILE *file = nullptr;
    if ( !strcmp( local_file.c_str(), "-" ) ) {
        int fd = dup(1);
        if ( -1 != fd ) {
            if ( _diagnostic ) { fprintf( stderr, "Fetching %s to stdout\n", local_file.c_str() ); }
            file = fdopen(fd, mode);
        }
    }
    else {
        if ( _diagnostic ) { fprintf( stderr, "Fetching to %s\n", local_file.c_str() ); }
        file = safe_fopen_wrapper( local_file.c_str(), mode );
    }

    if( !file ) {
        fprintf( stderr, "ERROR: could not open local file %s, error %d (%s)\n", local_file.c_str(), errno, strerror(errno) );
    }

    return file;
}
コード例 #17
0
// *****************************************
// Linux hibernator "Proc IF" class methods
// *****************************************
bool
ProcIfLinuxHibernator::Detect ( void )
{
	FILE	*fp;
	char	buf[128];

	// Look in /proc
	memset( buf, 0, sizeof(buf) );
	fp = safe_fopen_wrapper( PROC_POWER_FILE, "r" );
	if ( NULL == fp ) {
		return false;
	}
	if ( fgets( buf, sizeof(buf)-1, fp ) ) {
		char	*token, *save = NULL;

		token = strtok_r( buf, " ", &save );
		while( token ) {
			m_hibernator->addState( token );
			token = strtok_r( NULL, " ", &save );
		}
	}
	fclose( fp );
	return true;
}
コード例 #18
0
bool
CGroupTracker::check_process(procInfo* pi)
{
	// Really, the cgroup name should be part of the procInfo
	// However, it is a string, and would lead to lots of allocation
	// issues in the current code.
	// The majority of this is code from the GroupTracker.

	// prepare the pathname to open: /proc/<pid>/cgroup
	//
	char path[32];
	int ret = snprintf(path, 32, "/proc/%u/cgroup", pi->pid);
	if (ret < 0) {
		dprintf(D_ALWAYS,
			"GroupTracker (pid = %u): snprintf error: %s (%d)\n",
			pi->pid,
			strerror(errno),
			errno);
		return false;
        }
	if (ret >= 32) {
		dprintf(D_ALWAYS,
			"GroupTracker (pid = %u): error: path buffer too small\n",
			pi->pid);
		return false;
	}

	// do the fopen
	//
	FILE* fp = safe_fopen_wrapper(path, "r");
	if (fp == NULL) {
		dprintf(D_ALWAYS,
			"GroupTracker (pid = %u): fopen error: Failed to open file '%s'. Error %s (%d)\n",
			pi->pid,
			path,
			strerror(errno),
			errno);
		return false;
	}

	char buffer[1024];
	bool found_cgroup = false;
	std::map<std::string, ProcFamily*>::const_iterator end = m_cgroup_pool.end();
	while (fgets(buffer, 1024, fp)) {
		// Iterate through all our keys
		for (std::map<std::string, ProcFamily*>::const_iterator it = m_cgroup_pool.begin(); it != end; ++it) {
			if (strstr(buffer, it->first.c_str())) {
				m_monitor->add_member_to_family(it->second, pi, "CGROUP");
				found_cgroup = true;
			}
		}
	}
	if (!found_cgroup) {
		if (!feof(fp)) {
			dprintf(D_ALWAYS,
				"CGroupTracker (pid = %u): "
				"error reading from status file: %s (%d)\n",
				pi->pid,
				strerror(errno),
				errno);
		}
		fclose(fp);
		return false;
	}
	fclose(fp);

	// make sure we didn't get a partial line
	//
	int line_len = strlen(buffer);
	if (buffer[line_len - 1] != '\n') {
		dprintf(D_ALWAYS,
			"GroupTracker (pid = %u): "
			"read partial line from status file\n",
			pi->pid);
		return false;
	}
	return true;
}
コード例 #19
0
ファイル: dump_history.cpp プロジェクト: emaste/htcondor
// Read the history from a single file and print it out. 
static void readHistoryFromFile(char *JobHistoryFileName, char* constraint, ExprTree *constraintExpr)
{
    int EndFlag   = 0;
    int ErrorFlag = 0;
    int EmptyFlag = 0;
    AttrList *ad = NULL;

    long offset = 0;
    bool BOF = false; // Beginning Of File
    MyString buf;
    
    FILE* LogFile=safe_fopen_wrapper(JobHistoryFileName,"r");
    
	if (!LogFile) {
        fprintf(stderr,"History file (%s) not found or empty.\n", JobHistoryFileName);
        exit(1);
    }

	// In case of rotated history files, check if we have already reached the number of 
	// matches specified by the user before reading the next file
	if (specifiedMatch != 0) { 
        if (matchCount == specifiedMatch) { // Already found n number of matches, cleanup  
            fclose(LogFile);
            return;
        }
	}

	if (backwards) {
        offset = findLastDelimiter(LogFile, JobHistoryFileName);	
    }

    while(!EndFlag) {

        if (backwards) { // Read history file backwards
            if (BOF) { // If reached beginning of file
                break;
            }
            
            offset = findPrevDelimiter(LogFile, JobHistoryFileName, offset);
            if (offset == -1) { // Unable to match constraint
                break;
            } else if (offset != 0) {
                fseek(LogFile, offset, SEEK_SET);
                buf.readLine(LogFile); // Read one line to skip delimiter and adjust to actual offset of ad
            } else { // Offset set to 0
                BOF = true;
                fseek(LogFile, offset, SEEK_SET);
            }
        }
      
        if( !( ad=new AttrList(LogFile,"***", EndFlag, ErrorFlag, EmptyFlag) ) ){
            fprintf( stderr, "Error:  Out of memory\n" );
            exit( 1 );
        } 
        if( ErrorFlag ) {
            printf( "\t*** Warning: Bad history file; skipping malformed ad(s)\n" );
            ErrorFlag=0;
            if(ad) {
                delete ad;
                ad = NULL;
            }
            continue;
        } 
        if( EmptyFlag ) {
            EmptyFlag=0;
            if(ad) {
                delete ad;
                ad = NULL;
            }
            continue;
        }
        if (!constraint || EvalBool(ad, constraintExpr)) {
            if (longformat) { 
                ad->fPrint(stdout); printf("\n"); 
            } else {
                if (customFormat) {
                    mask.display(stdout, ad);
                } else {
                    displayJobShort(ad);
                }
            }

            matchCount++; // if control reached here, match has occured

            if (specifiedMatch != 0) { // User specified a match number
                if (matchCount == specifiedMatch) { // Found n number of matches, cleanup  
                    if (ad) {
                        delete ad;
                        ad = NULL;
                    }
                    
                    fclose(LogFile);
                    return;
                }
            }
		}
		
        if(ad) {
            delete ad;
            ad = NULL;
        }
    }
    fclose(LogFile);
    return;
}
コード例 #20
0
ファイル: xen_type.linux.cpp プロジェクト: emaste/htcondor
// This function compares the timestamp of given file with
// that of writable disk files.
// This function should be called after parseVirshDiskParam()
bool
VirshType::checkCkptSuspendFile(const char* file)
{
	if( !file || file[0] == '\0' ) {
		return false;
	}

	// Read timestamp file
	MyString timestampfile(file);
	timestampfile += XEN_CKPT_TIMESTAMP_FILE_SUFFIX;

	FILE *fp = safe_fopen_wrapper(timestampfile.Value(), "r");
	if( !fp ) {
		vmprintf(D_ALWAYS, "Cannot find the timestamp file\n");
		return false;
	}

	char buffer[128];
	if( fgets(buffer, sizeof(buffer), fp) == NULL ) {
		fclose(fp);
		vmprintf(D_ALWAYS, "Invalid timestamp file\n");
		return false;
	}
	fclose(fp);

	MyString tmp_str;
	tmp_str = buffer;
	if( tmp_str.IsEmpty() ) {
		vmprintf(D_ALWAYS, "Invalid timestamp file\n");
		return false;
	}
	tmp_str.trim();

	time_t timestamp;
	timestamp = (time_t)atoi(tmp_str.Value());
	if( timestamp <= 0 ) {
		vmprintf(D_ALWAYS, "Invalid timestamp file\n");
		return false;
	}

	XenDisk *vdisk = NULL;
	m_disk_list.Rewind();
	while( m_disk_list.Next(vdisk) ) {
		if( !strcasecmp(vdisk->permission.Value(), "w") ||
				!strcasecmp(vdisk->permission.Value(), "rw")) {
			// this is a writable disk file
			// get modification time of this disk file
			time_t disk_mtime;
			struct stat disk_stat;
			if( stat(vdisk->filename.Value(), &disk_stat ) < 0 ) {
				vmprintf(D_ALWAYS, "\nERROR: Failed to access \"%s\":%s\n",
						vdisk->filename.Value(), strerror(errno));
				return false;
			}
			disk_mtime = disk_stat.st_mtime;

			// compare
			if( disk_mtime != timestamp ) {
				vmprintf(D_ALWAYS, "Checkpoint timestamp mismatch: "
						"timestamp of suspend file=%d, mtime of disk file=%d\n",
						(int)timestamp, (int)disk_mtime);
				return false;
			}
		}
	}

	return true;
}
コード例 #21
0
ファイル: machdep.LINUX.cpp プロジェクト: AlanDeSmet/htcondor
int num_segments()
{
	FILE	*pfs;
	char	proc[128];
	char	rperm, wperm, xperm, priv;
	int		scm;
	int		num_seg=0;
	int		major, minor, inode;
	int		mem_start, mem_end;
	int		offset;
	char	e, f;


	scm=SetSyscalls(SYS_LOCAL | SYS_UNMAPPED);

	sprintf(proc, "/proc/%d/maps", syscall(SYS_getpid));
	pfs=safe_fopen_wrapper(proc, "r");
	if(!pfs) {
		SetSyscalls(scm);
		return -1;
	}

	// Count the numer of mmapped files in use by the executable
	while(1) {
		int result = fscanf(pfs, "%x-%x %c%c%c%c %x %d:%d %d\n",
			&mem_start, &mem_end, &rperm, &wperm,
			&xperm, &priv, &offset, &major, &minor, &inode);

		if(result!=10) break;

		/*fprintf(stderr, "0x%x 0x%x %c%c%c%c 0x%x %d:%d %d\n", 
			mem_start, mem_end, rperm, wperm, xperm, priv,
			offset, major, minor, inode);*/
		my_map[num_seg].mem_start=mem_start;
		my_map[num_seg].mem_end=mem_end-1;
		/* FIXME - Greger */
		if(my_map[num_seg].mem_end-my_map[num_seg].mem_start==0x34000-1)
			my_map[num_seg].mem_end=my_map[num_seg].mem_start+0x320ff;
		my_map[num_seg].offset=offset;
		my_map[num_seg].prot=(rperm=='r'?PROT_READ:0) |
							 (wperm=='w'?PROT_WRITE:0) |
							 (xperm=='x'?PROT_EXEC:0);
		my_map[num_seg].flags=(priv=='p'?:0);
		my_map[num_seg].inode=inode;
		my_map[num_seg].r=rperm;
		my_map[num_seg].w=wperm;
		my_map[num_seg].x=xperm;
		my_map[num_seg].p=priv;
		num_seg++;
	}
	fclose(pfs);

	map_count=num_seg;
	text_loc=find_map_for_addr((long)num_segments);
	if(StackGrowsDown())
		stack_loc=find_map_for_addr((long)stack_end_addr());
	else
		stack_loc=find_map_for_addr((long)stack_start_addr());
	heap_loc=find_map_for_addr((long)data_start_addr());

	/*fprintf(stderr, "%d segments\n", num_seg);*/
	SetSyscalls(scm);
	return num_seg;
}
コード例 #22
0
int
main( int argc, char **argv ) {

    bool valid_inputs = true;
    FILE* output_file;
    bool diagnostic = false;
    bool upload = false;
    int rval = 0;
    std::string input_filename;
    std::string output_filename;
    std::string transfer_files;

    // Check if this is a -classad request
    if ( argc == 2 ) {
        if ( strcmp( argv[1], "-classad" ) == 0 ) {
            printf( "%s",
                "MultipleFileSupport = true\n"
                "PluginVersion = \"0.2\"\n"
                "PluginType = \"FileTransfer\"\n"
                "SupportedMethods = \"http,https,dav,davs\"\n"
            );
            return 0;
        }
    }
    // If not, iterate over command-line arguments and set variables appropriately
    else {
        for( int i = 1; i < argc; i ++ ) {
            if ( strcmp( argv[i], "-infile" ) == 0 ) {
                if ( i < ( argc - 1 ) ) {
                    input_filename = argv[i+1];
                }
                else {
                    valid_inputs = false;
                }
            }
            if ( strcmp( argv[i], "-outfile" ) == 0 ) {
                if ( i < ( argc - 1 ) ) {
                    output_filename = argv[i+1];
                }
                else {
                    valid_inputs = false;
                }
            }
            if ( strcmp( argv[i], "-diagnostic" ) == 0 ) {
                diagnostic = true;
            }
            if ( strcmp( argv[i], "-upload" ) == 0 ) {
                upload = true;
            }
        }
    }

    if ( !valid_inputs || input_filename.empty() ) {
        fprintf( stderr, "Error: invalid arguments\n" );
        fprintf( stderr, "Usage: %s -infile <input-filename> -outfile <output-filename> [general-opts]\n\n", argv[0] );
        fprintf( stderr, "[general-opts] are:\n" );
        fprintf( stderr, "\t-diagnostic\t\tRun the plugin in diagnostic (verbose) mode\n\n" );
        fprintf( stderr, "\t-upload\t\tRun the plugin in upload mode, copying files to a remote location\n\n" );
        return 1;
    }

    // Instantiate a MultiFileCurlPlugin object and handle the request
    MultiFileCurlPlugin curl_plugin( diagnostic );
    if( curl_plugin.InitializeCurl() != 0 ) {
        fprintf( stderr, "ERROR: curl_plugin failed to initialize. Aborting.\n" );
        return 1;
    }

    // Do the transfer(s)
    rval = upload ?
             curl_plugin.UploadMultipleFiles( input_filename )
           : curl_plugin.DownloadMultipleFiles( input_filename );

    // Now that we've finished all transfers, write statistics to output file
    if( !output_filename.empty() ) {
        output_file = safe_fopen_wrapper( output_filename.c_str(), "w" );
        if( output_file == NULL ) {
            fprintf( stderr, "Unable to open curl_plugin output file: %s\n", output_filename.c_str() );
            return 1;
        }
        fprintf( output_file, "%s", curl_plugin.GetStats().c_str() );
        fclose( output_file );
    }
    else {
        printf( "%s\n", curl_plugin.GetStats().c_str() );
    }

    // 0 on success, error code >= 1 on failure
    return rval;
}