utils.cpp 10.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*******************************************************************************
 * Copyright 2019 UChicago Argonne, LLC.
 * (c.f. AUTHORS, LICENSE)
 *
 * This file is part of the Argo containers project.
 * For more info, see https://xgitlab.cels.anl.gov/argo/containers
 *
 * SPDX-License-Identifier: BSD-3-Clause
*******************************************************************************/

Swann Perarnau's avatar
Swann Perarnau committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include "utils.hpp"

#include <vector>
#include <string>
#include <cstdlib>
#include <sstream>
#include <cassert>
#include <fstream>
#include <ctype.h>

#include <unistd.h>
#include <limits.h>
#include <stdio.h>
#include <algorithm>

#include "ilogger.hpp"
#include "syslogger.hpp"
#include "filelogger.hpp"
#include "stderrlogger.hpp"
#include "aggregatelogger.hpp"

#define MIN(a,b) ((a)<(b)?(a):(b))

vector<string> &split(const string &str_in, char delim, vector<string> &tokens)
{
Kamil Iskra's avatar
Kamil Iskra committed
36
#if 0
Swann Perarnau's avatar
Swann Perarnau committed
37 38 39 40 41 42 43 44 45
	std::stringstream ss(str_in);
	string token;
	tokens.clear();
	while(getline(ss, token, delim))
	{
		if(!token.empty())
			tokens.push_back(token);
	}
	return tokens;
Kamil Iskra's avatar
Kamil Iskra committed
46 47 48
#endif
	string delims(1, delim);
	return split(str_in, delims, tokens);
Swann Perarnau's avatar
Swann Perarnau committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
}

vector<string> &split(const string &str_in, const string &delims,
        vector<string> &tokens)
{
    int start = 0, next_delim_pos;
    int length = str_in.size();
    bool found = false;
	tokens.clear();

    while(true)
    {   
        found = false;
        next_delim_pos = INT_MAX;
        for(int i=0; i<(int)delims.size(); i++)
        {
            for(int j=start; j<length; j++)
Kamil Iskra's avatar
Kamil Iskra committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
	    {
		if(str_in[j] == '\\')
		{
		    j++;
		    continue;
		}
		if(str_in[j] == '\'')
		{
		    for (j++; j<length; j++)
		    {
			if(str_in[j] == '\\')
			{
			    j++;
			    continue;
			}
			if (str_in[j] == '\'')
			    break;
		    }
		    if (j == length) /* Parse error */
		    {
			tokens.clear();
			return tokens;
		    }
		}
Swann Perarnau's avatar
Swann Perarnau committed
90 91 92 93 94
                if(str_in[j] == delims[i])
                {   
                    next_delim_pos = MIN(j,next_delim_pos);
                    found = true;
                    break;
Kamil Iskra's avatar
Kamil Iskra committed
95 96
                }
	    }
Swann Perarnau's avatar
Swann Perarnau committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        }
        if(found)
        {
            string token = str_in.substr(start, next_delim_pos-start);
            if(!token.empty())
                tokens.push_back(token);
            start = next_delim_pos + 1;
        }   
        else
        {
            string token = str_in.substr(start);
            if(!token.empty())
                tokens.push_back(token);
            break;
        }   
    }   
    return tokens;
}

#define IS_BLANK(c) ((c) == ' ' || (c) == '\t')

bool str_start_with(const string& base_str, const string& key)
{
	return base_str.find(key) == 0;
}


bool str_contains(const string& base_str, const string& key)
{
	return base_str.find(key) != string::npos;
}

string& str_trim_left(string &in)
{
    int i;
    for(i=0; i<(int)in.size(); i++)
    {   
        if(!IS_BLANK(in[i]))
            break;
    }   
    if(i != 0)
        in = in.substr(i);
    return in; 
}

string& str_trim_right(string &in)
{
    for(int i= in.size()-1; i>=0; i--)
    {   
        if(!IS_BLANK(in[i]))
        {
            if(i<(int)in.size()-1)
                in = in.substr(0, i+1);
            break;
        }
    }   
    return in; 
}

string& str_trim(string &in)
{
    return str_trim_right(str_trim_left(in));
}

bool str_extract_delimiter_content(const string& base_str, const string& delim0,
		const string& delim1, string &token)
{
	size_t start = base_str.find(delim0);
	size_t end = base_str.find(delim1, start+delim0.size());
	if(start == string::npos || end == string::npos)
		return false;
	token = base_str.substr(start + 1, end - start - 1);
	return true;
}


bool str_extract_before(const string& base_str, const string& delim,
		string &token, bool empty_token_if_delim_not_found)
{
	string base_copy = base_str;
	return str_chop_before(base_copy, delim, token, false, 
			empty_token_if_delim_not_found);
}


bool str_extract_after(const string& base_str, const string& delim,
		string &token, bool empty_token_if_delim_not_found)
{
	string base_copy = base_str;
	return str_chop_after(base_copy, delim, token, false, 
			empty_token_if_delim_not_found);
}


bool str_chop_before(string& base_str, const string& delim,
		string &token, bool throw_delim_away,
		bool empty_token_if_delim_not_found)
{
	token = "";
	size_t end = base_str.find(delim);
	if(end != string::npos)
	{
		token = base_str.substr(0, end);
		if(throw_delim_away)
			base_str = base_str.substr(end+delim.size());
		else
			base_str = base_str.substr(end);
		return token != "";
	}
	if(!empty_token_if_delim_not_found)
	{
		token = base_str;
		base_str = "";
	}
	return token != "";
}


bool str_chop_after(string& base_str, const string& delim,
		string &token, bool throw_delim_away, 
		bool empty_token_if_delim_not_found)
{
	token = "";
	size_t start = base_str.find(delim);
	if(start != string::npos)
	{
		token = base_str.substr(start + delim.size());
		if(throw_delim_away)
			base_str = base_str.substr(0, start);
		else
			base_str = base_str.substr(0, start + delim.size());
		return token != "";
	}
	if(!empty_token_if_delim_not_found)
	{
		token = base_str;
		base_str = "";
	}
	return token != "";
}


bool is_int(const string& in)
{
	if(in.size() == 0)
		return false;
	for(int i=0; i<(int)in.size(); i++)
		if(!isdigit(in[i]))
			return false;
	return true;
}

bool is_double(const string& in)
{
	if(in.size() == 0)
		return false;
	if(!isdigit(in[0]))
		return false;
	int nb_dots = 0;
	for(int i=1; i<(int)in.size(); i++)
	{
		if(!isdigit(in[i]) && in[i] != '.')
			return false;
		if(in[i] == '.')
			nb_dots++;
	}
	return nb_dots <= 1;
}

string& make_debug_message(string& initial_message, 
		string& out,
		const char* filename, int lineno)
{
	std::ostringstream oss;
	oss<<"[DEBUG - "<<filename<<':'<<lineno<<"]|"<<initial_message;
	out = oss.str();
	return out;
}

void elevate_privileges()
{
	return;
	if(geteuid() == 0)
		return;
	if(setreuid(geteuid(), getuid()) != 0)
		ASSERT_ERRNO("");

}

void lower_privileges()
{
	return;
	if(geteuid() != 0)
		return;
	if(setreuid(geteuid(), getuid()) != 0)
		ASSERT_ERRNO("");
}

#define MAX_ARGS	100

#if 0
void argo_popen(string command, string mode, 
		string& outstream, string &errstream);
{
	pid_t pid = 0;
	int pipefd[2];
	FILE* out;
	FILE* err;
	char line[256];
	int status;

	const char* argv[MAX_ARGS];
	vector<string> tokens;
	split(command, ' ', tokens);
	assert((int)tokens.size() < MAX_ARGS);
	int i;
	for(i=0; i<(int)tokens.size(); i++)
		argv[i] = tokens[i].c_str();
	argv[i] = NULL;

	pipe(pipefd);
	pid = fork(); 
	if(pid == 0)
	{
		dup2(pipefd[0], STDOUT_FILENO);
		dup2(pipefd[1], STDERR_FILENO);
		execl("/usr/bin/tail", "/usr/bin/tail", "-f", "path/to/your/file", (char*) NULL);
	}

	//Only parent gets here. Listen to what the tail says
	close(pipefd[1]);
	output = fdopen(pipefd[0], "r");

	while(fgets(line, sizeof(line), output)) //listen to what tail writes to its standard output
	{
		//if you need to kill the tail application, just kill it:
		if(something_goes_wrong)
			kill(pid, SIGKILL);
	}

	//or wait for the child process to terminate
	waitpid(pid, &status, 0);
}
#endif

/*MISC*/
char _hostname[1025];
string hostname = "";
const string* const get_hostname()
{
	if(hostname == "")
	{
		if(gethostname(_hostname, 1024))
			ASSERT_ERRNO("gethostname failed");
		hostname = _hostname;
	}
	return &hostname;
}
/*MISC*/


/* STRINGIFY*/
string log_dest_to_str(Log_dest dest)
{
	switch(dest)
	{
		case LOG_DEST_DEV_NULL: return "LOG_DEST_DEV_NULL";
		case LOG_DEST_SYSLOG: return "LOG_DEST_SYSLOG"; 
		case LOG_DEST_STDERR: return "LOG_DEST_STDERR";
		case LOG_DEST_FILE: return "LOG_DEST_FILE";
	}
	assert(false);
	return "WTH! INVALID_LOG_DEST";
}

string non_composite_log_type_to_str(Log_type type, bool empty_on_invalid = true)
{
	switch(type)
	{
		case LOG_TYPE_INVALID: return empty_on_invalid? "": "LOG_TYPE_INVALID";
		case LOG_TYPE_INFO: return "INFO";
		case LOG_TYPE_WARNING: return "WARNING";
		case LOG_TYPE_ERROR: return "ERROR";
		case LOG_TYPE_DEBUG: return "DEBUG";
	}
	assert(false);
	return "WTH! INVALID LOG TYPE";
}

string log_type_to_str(Log_type type)
{
	if(type == LOG_TYPE_INVALID)
		return "LOG_TYPE_INVALID";
	string ret = "";
	string temp;
	Log_type lts[] =
	{LOG_TYPE_INFO, LOG_TYPE_WARNING, LOG_TYPE_ERROR, LOG_TYPE_DEBUG};
	int nb = sizeof(lts)/sizeof(Log_type);
	for(int i=0; i< nb; i++)
	{
		temp = non_composite_log_type_to_str( type & lts[i]);
		if(temp != "")
		{
			if(ret != "")
				ret += ("|"+temp);
			else 
				ret = temp;
		}
	}		
	return ret;
}

void stringify_int_list(const vector<int>& list, char separator, string &out)
{
	if(list.size() == 0)
	{
		out = "";
		return;
	}
	std::ostringstream ss;
	ss<<list[0];
	for(int i=1; i<(int)list.size(); i++)
		ss<<separator<<list[i];
	out = ss.str();
}

string& format_int_list_for_display(
		const vector<int>& vect, string& str, const string& header)
{
	string offset="";
	for(int i=0; i<(int)header.size(); i++)
		offset += ' ';
	int max_per_line = 10;
	int i, j;
	std::ostringstream ss;	
	for(i=0, j=0; i<(int)vect.size(); i++, j++)
	{
		if(j == max_per_line)
		{
			ss<<std::endl<<offset;
			j = 0;
		}
		ss<<vect[i]<<' ';
	}
	str = ss.str();
	return str;
}

	
/*END STRINGIFY*/

/*ERRORS*/
void argo_exit(int exit_status, string exit_message, int errnum)
{
	Syslogger syl(ruid);
	Stderrlogger stdl(ruid, LOG_TYPE_ERROR|LOG_TYPE_WARNING|LOG_TYPE_DEBUG);
	Filelogger fl(ruid, EXIT_MESSAGE_FILE_NAME, LOG_TYPE_ERROR|LOG_TYPE_INFO,
			false);
	Aggregatelogger al(ruid);
	al.add_logger(&syl);
	al.add_logger(&stdl);
	al.add_logger(&fl);
	Log_type log_type = exit_status == EXIT_SUCCESS ? LOG_TYPE_INFO : LOG_TYPE_ERROR;
	if(errnum != -1)
		al.log(log_type, exit_message, errnum);
	else
		al.log(log_type, exit_message);

	exit(exit_status);
}

/*END ERRORS*/

/*SOME FILE I/O*/

void retrieve_from_file(const string& filename, string& out)
{
	std::ifstream file;
	file.open(filename.c_str());
	THROW_WITH_ERRNO_IF(file.fail(), 
			"Retriving container content from " + filename + " failed");
	out = "";
	getline(file, out);
	file.close();
}

uid_t get_task_owner(int pid)
{
	char buf[101];
	sprintf(buf, "/proc/%d/status", pid);
	std::ifstream file;
	file.open(buf);
	if(file.fail() and errno == ENOENT)
		return (uid_t)(-1);
	string str;
	while(getline(file, str))
	{
		if(str_start_with(str, "Uid"))
		{
			file.close();
			vector<string> tokens;
			split(str, " \t", tokens);
			return atoi(tokens[1].c_str());
		}
	}
	file.close();
	return UID_INVALID;
}
/*END SOME FILE I/O*/

/*FILESYSTEM*/
int mkdir_p(string path, mode_t mode)
{
	int ret = mkdir(path.c_str(), mode);
	if(ret == 0 || errno == EEXIST)
		return ret;
	if(errno != ENOENT)
		return ret;

	vector<string> tokens;
	split(path, '/', tokens);
	string cur = "";
	if(path[0] == '/')
		cur="/";
	for(int i=0; i<(int)tokens.size(); i++)
	{
		cur += tokens[i];
		cur += '/';
		ret = mkdir(cur.c_str(), mode);
		if(ret != 0 && errno != EEXIST)
			return ret;
	}
	return ret;
}
/*END FILESYSTEM*/
/*END SOME FILE I/O*/