argo_nodeos_config.cpp 24.6 KB
Newer Older
Swann Perarnau's avatar
Swann Perarnau committed
1 2 3 4 5 6 7 8 9 10 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 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
#include "headers.hpp"
#include "common.hpp"
#include "aggregatelogger.hpp"
#include "log_option_parser.hpp"
#include "resource_locker.hpp"
#include "string_parser.hpp"

#include <unistd.h>
#include <getopt.h>
#include <cstdlib>
#include <sstream>


uid_t ruid;
uid_t euid;

#define TESTS__

#ifdef TESTS__
void test_logs()
{
	Syslogger syl(ruid);
	Syslogger syl1(ruid, LOG_TYPE_WARNING|LOG_TYPE_DEBUG);
	Filelogger fil(ruid, "log.log", LOG_TYPE_WARNING|LOG_TYPE_ERROR);
	Stderrlogger stl(ruid, LOG_TYPE_INFO|LOG_TYPE_DEBUG);

	Aggregatelogger agl(ruid);
	agl.add_logger(&syl);
	agl.add_logger(&fil);
	agl.add_logger(&stl);

	agl.log(LOG_TYPE_INFO, "Some Info 0");
	agl.log(LOG_TYPE_WARNING, "Some warning 0");
	agl.log(LOG_TYPE_ERROR, "Some error 0");
	agl.log(LOG_TYPE_DEBUG, "Some debug 0");

	agl.add_logger(&syl1);
	agl.log(LOG_TYPE_INFO, "Some Info 1");
	agl.log(LOG_TYPE_WARNING, "Some warning 1");
	agl.log(LOG_TYPE_ERROR, "Some error 1");
	agl.log(LOG_TYPE_DEBUG, "Some debug 1");
}
#endif //TESTS__


Args args={ON_ERROR_STOP};

ILogger* logger = NULL;
static Filelogger *_filelogger = NULL;
static Syslogger *_syslogger = NULL;
static Stderrlogger* _stderrlogger = NULL;
static Aggregatelogger *_aggregatelogger = NULL;
Acl* acl = NULL;

string error_message="";

typedef uint64_t Help_section;
#define HS_ALL				0xffffffffffffffff
#define HS_MISC				1			//--help misc
#define HS_ERROR_BEHAVIOR	(1LLU<<1)	//--help error_behavior
#define HS_LOGGING			(1LLU<<2)	//--help logging
#define HS_DAEMON_MODE		(1LLU<<3)	//--help daemon_mode
#define HS_CONTAINER_CONFIG	(1LLU<<4)	//--help container_config
#define HS_HELP_SECTION		(1LLU<<5)	//--help help_sections

void print_usage(const char* app_name, string help_sections)
{
	if(help_sections == "")
		printf("\n"
			//"\t<----CONVENTIONS---->\n"
			//"\t</----CONVENTIONS---->\n"
			"\n"
			"\t<----DESCRIPTION---->\n"
			"%s is the local node setup command for Argo NodeOs. It is used for compute\n"
			"container creation, management and destruction as well their associated \n"
			"resource allocation and partitioning\n"
			"\t</----DESCRIPTION---->\n"
			, APP_NAME);

	if(help_sections == "" || str_contains(help_sections, "help_sections"))
		printf("\n"
			"\t<----HELP SECTIONS---->\n"
			"Use the \"--help\" command to display the help message and exit.\n"
			"\nInstead of displaying the whole help message, specific help sections\n"
			"can be displayed with --help=\"section_name [section_name ...]\"\n"
			"The available help section names are:\n"
			"\t#) help_section: displays the help about help sections\n"
			"\t#) error_behavior: displays the error behavior command help\n" 
			"\t#) logging: the options to manipulate what and where to log \n"
			"\t   trace and error messages\n"
			"\t#) daemon_mode: the option for executing %s in daemon mode\n"
			RED_TEXT "\t\tNOT IMPLEMENTED YET\n" NEUTRAL_TEXT
			"\t#) container_config: manipulate container configuration \n"
			"\t#) service_os_config: manipulate service_os configuration \n"
			"\t#) misc: options for various other things\n"
			"\t</----HELP SECTIONS---->\n"
			,
			APP_NAME);

	if(help_sections == "" || str_contains(help_sections, "error_behavior"))
		printf("\n"
			"\t<----ERROR BEHAVIOR---->\n"
			"The error behavior describes what happens when an error is encountered\n"
			"during the processing. The two possible behaviours are:\n"
			"\t-STOP: Stop and exit (with possible cleanup) when an error is encountered.\n"
			"\t\tThis is the default behavior!\n"
			"\t-CONTINUE: Skip the erroneous operation but continue with the subsequent ones."
			"\n"
			"\nOption:\n"
			"\t--on_error=STOP|CONTINUE\n"
			"\t</----ERROR BEHAVIOR---->\n"
			);
	
	if(help_sections == "" || str_contains(help_sections, "logging"))
		printf("\n"
			"\t<----LOGGING---->\n"
			"%s LOGGING is used for journaling and diagnostics. \n"
			"There are 3 log channels:\n"
			"\t-syslog\n\t-stderr\n\t-user-supplied file\n"
			"Syslog is enabled by default; and can be disabled only with the right ACL.\n"
			"The other channels can be enabled or disabled on will.\n"
			"Multiple channels can be enabled simultaeously.\n"
			"\n"
			"There are 4 log levels:\n"
			"\tINFO\n"
			"\tWARNING\n"
			"\tERROR\n"
			"\tDEBUG\n"
			"\n"
			"INFO, WARNING and ERROR are enabled by default on syslog. The right ACL\n"
			"is required to modify the log levels of syslog. Any log level can be \n"
			"activated on stderr and file channels without any ACL right.\n"
			"\n"
			"The logging command options have the pattern \n"
			"--log=\"log_channel:[+]|-log_levels[,log_channel:[+]|-log_levels[,log_channel:[+]|-log_levels]]\"\n"
			"\tMultiple log channels can be enabled simultaneously; and for each of them, multiple\n"
			"log levels can be activated(+) or deactivated(-).\n"
			"The + sign for log level activation is optional and assumed by default; but the - sign\n"
			"for log level deactivation is mandatory\n"
			"\tLog channels are named \"syslog\", \"stderr\" and \"file\"\n"
			"\tLog levels are named I, W, E, D, respectively for INFO, WARNING, ERROR and DEBUG.\n"
			"\tIf the log channel is \"file\", the filename is required as a third argument\n"
			"e.g. --log=\"file:+E+D:log_file_name.log\"\n"
			"The log file for the file channel is always appended to if the file had a previous content.\n"
			"\tExamples of options:\n"
			"\t--log=\"syslog:+D\" to enable the debug channel on syslog\n"
			"\t--log=\"syslog:+D-I-W,stderr:+I+W,file:+D:out.log\" to enable DEBUG on syslog, \n"
			"disable INFO and WARNING on syslog; enable INFO and WARNING on stderr; and enable\n"
			"DEBUG on file with an output file named out.log\n"
			"\t</----LOGGING---->\n"
			,
		APP_NAME);

	if(help_sections == "" || str_contains(help_sections, "daemon_mode"))
		printf("\n"
			"\t<----DAEMON MODE----> " RED_TEXT "NOT IMPLEMENTED YET " NEUTRAL_TEXT "\n"
			"In daemon mode, %s runs in  background and receives commands from a client\n"
			"(client is comming soon). In daemon mode, the stderr log channel is not available.\n"
			"Daemon mode is triggered by the option \"--daemon\".\n"
			"\t</----DAEMON---->\n",
			APP_NAME);

	if(help_sections == "" || str_contains(help_sections,"container_config"))
	   printf("\n"
		   "\t<-----CONTAINER CONFIGURATION---->\n"
			"The following configuration \"verbs\" are supported:\n"
			"	#) create_container: create a container\n"
			"	#) delete_container: delete a container\n"
			"	#) show_config: display the current configuration of the node\n"
			"	#) clean_config: Delete all the containers of a node. The ServiceOS remains if it existed\n"
			"	#) alter_container: Modifies an existing container\n"
			"	#) attach_to_container: attach a process or list of processes to a container; so they \n"
			"		would run inside it from there on\n"
			"	#) detach_from_container: detach a process or list of processes from a container. \n"
			"		The detached processes run outside any container (in the ServiceOS if any)\n"
			"	#) migrate_to_container: migrate processes from a given container to another one\n"
			"	#) show_available_resources: Show the resources available for subsequent comntainer creation.\n"
			"\n"
			"\tThe verbs are issued with a list of argument in key-value form. Each set of key-value\n"
			"pair is separated by space. An example of verb command is:\n"
			"	 --verb_name=\"key0:value0 key1:value1 key2:value2 .....\"\n"
			"\nThe values are typed. They can be:\n"
			"	#) String: Any string of alphanumerical character or - or _ (E.g., name:container_0)\n"
			"	#) Boolean: Only the values \"true\" or \"false\" (E.g. load_balancing:false)\n"
			"	#) Array: Array values are comma-separated values of the same type enclosed in square brackets.\n"
			"			Arrays are int by default (E.g., pids:[234,9487,1000] OR pids:<int>[...])\n"
			"			Arrays could be double (E.g., times:<double>[234.12,3.14,2.736])\n"
			"			Arrays could be provided to:"
		    "				overwrite an existing list(E.g., cpus:[1,2...n])\n"
		    "				add to an existing list(E.g., +cpus:[1,2...n])\n"
		    "				remove from an existing list(E.g., -cpus:[1,2...n])\n"
			"\nLong lists of integer values (in arrays) can be compactly specified by resorting to:\n"
			 "	#) Range notation: E.g., cpus:[0-15] would expand to 0,1,2,...,15\n"
			 "	#) Range notation with strides: E.g. cpus:[0-100s5] would expand to 0,5,10,15,...,100\n"
			 "	#) A mix of any of the supported notations: E.g. cpus:[1,2,6,9,10-100s5,235-240] \n"
			 "		would expand to 1,2,6,9,10,15,20,25,...,100,235,236,237,...,240\n"
			"\n"
			"Each verb supports a given sets of key:value pairs. Not all supported key:value pairs\n"
			"are expected for each invocation fo a verb.\n"

			"Here is a listing of verbs-key:value pair associations along with an example:\n"
			"	#) create_container:\n"
			"		##) name (string); mandatory; must be unique\n"
			"		##) cpus (array<int>)\n"
			"		##) mems (array<int>). These are the memory nodes\n"
			"		##) cpu_exclusive (boolean); defaults to true\n"
			"		##) mem_exclusive (boolean); defaluts to false\n"
			"		##) load_balancing (boolean); defaults to false\n"
			"		##) mem_migrate (boolean); defaults to true\n"
			"	E.g., --create_container=\"name:c0 cpus:<int>[0,1] mems:[0] load_balancing:false cpu_exclusive:true mem_exclusive:false\"\n"
			"Comment: Will fail if the name is already taken or if the CPU cores or memory nodes \n"
			"are not available due to exclusivity."
			"\n"
			"\n"
			"	#) delete_container:\n"
			"		##) name (string); mandatory\n"
			"		##) kill_content (boolean).\n"
			"	E.g. --delete_container=\"name:container_name\"\n"
			"Comment: Will fail if the container contains tasks or if it is owned by someone else.\n"
		    "If kill_content:true is specified, a container hosting tasks can still be deleted by its owner.\n"
			"In that case though, all the hosted tasks are first killed. If any of the tasks is not owned \n"
			"by the issuer of the command, the command fails, unless the issuer is root.\n"
			"This command tries as much as possible to be transactional. \n"
			"Either all containers meet the requirements top be deleted or none is\n" 
			"\n"
			"	#) alter_container:\n"
			"		##) name (string); mandatory\n"
			"		##) [+|-]cpus (array<int>)\n"
			"		##) [+|-]mems (array<int>). These are the memory nodes\n"
			"		##) cpu_exclusive (boolean)\n"
			"		##) mem_exclusive (boolean)\n"
			"		##) load_balancing (boolean)\n"
			"		##) mem_migrate (boolean)\n"
			"	E.g., --alter_container=\"name:c0 +mems:[1] -mems[0] cpus:[1-3] load_balancing:true\"\n"
			"\n"
			"show_config accepts no key:value pair. E.g., --show_config\n"
			"\n"
			"	#) clean_config:\n"
			"		##) kill_content (boolean).\n"
			"	E.g. --clean_config\n"
			"Comment: Will fail if any container is not owned by the requester or if any of them contains\n"
			"a task.\n"
		    "If kill_content:true is specified, a container hosting tasks can still be deleted by its owner.\n"
			"In that case though, all the hosted tasks are first killed. If any of the tasks is not owned \n"
			"by the issuer of the command, the command fails, unless the issuer is root.\n"
			"This command tries as much as possible to be transactional. \n"
			"Either all containers meet the requirements top be deleted or none is\n" 
			"\n"
			"	#) attach_to_container:\n"
			"		##) name (string); mandatory\n"
			"		##) pids (array<int>); mandatory\n"
			"	E.g. --attach_to_container=\"name:container_name pids:[list_of_pids]\"\n"
			"Comment: This is transactional. Either all tasks can be attached or none is.\n"
			"The requester must own the container and all the tasks or be root\n"
			"\n"
			"	#) detach_from_container:\n"
			"		##) name (string); mandatory\n"
			"		##) pids (array<int>); mandatory\n"
			"	E.g. --detach_from_container=\"name:container_name pids:[list_of_pids]\"\n"
			"Comment: This is transactional. Either all tasks can be detached or none is.\n"
			"The requester must own the container or be root\n"
			"\n"
			"	#) migrate_to_container:\n"
			"		##) name (string); mandatory\n"
			"		##) pids (array<int>); mandatory\n"
			"	E.g. --migrate_to_container=\"name:container_name pids:[list_of_pids]\"\n"
			"Comment: This is transactional. Either all tasks can be migrated or none is.\n"
			"The requester must own the destination container and all of the implicit source container or be root\n"
			"\n"
			"	#) show_available_resources:\n"
			"		##) shared (bool)\n"
			"	E.g. --show_available_resources  OR  --show_available_resources=\"shared:false\"\n"
			"Comment: By default, the optional argument \"shared\" is true. If it is false, only the resources\n"
			"that can be requested exclusively are shown\n"
		   "\t</-----CONTAINER CONFIGURATION---->\n"
		   );
	
	if(help_sections == "" || str_contains(help_sections, "service_os_config"))
		printf("\n"
		   "\t<-----SERVICE_OS CONFIGURATION---->\n"
			"	#) create_service_os:\n"
			"		##) cpus (array<int>)\n"
			"		##) mems (array<int>). These are the memory nodes\n"
			"		##) mem_migrate (boolean); defaults to true\n"
			"	E.g., --create_service_os=\"mems:[1] cpus:[1-3]\"\n"
			"Comment: Root privileges required.\n"
			"Only one service_os can exist. The command will fail if a service_os already exists.\n"
			"\n"

			"	#) alter_service_os: " RED_TEXT "NOT IMPLEMENTED YET " NEUTRAL_TEXT "\n"
			"		##) [+|-]cpus (array<int>)\n"
			"		##) [+|-]mems (array<int>). These are the memory nodes\n"
			"		##) mem_migrate (boolean)\n"
			"	E.g., --alter_service_os=\"+mems:[1] -mems[0] cpus:[1-3]\"\n"
			"Comment: Root privileges required.\n"
			"\n"

			"	#) delete_service_os:\n"
			"	E.g., --delete_service_os\n"
			"Comment: Root privileges required.\n"
			"\n"
		   "\t</-----SERVICE_OS CONFIGURATION---->\n");

	if(help_sections == "" || str_contains(help_sections, "misc"))
		printf("\n"
			"\t<----MISC---->\n"
			"1-) The binary of %s must be owned by root\n"
			"2-) The exit message of the last execution is appended to the file %s\n"
			"\tThe exit message is also written in syslog, regarless of the specified logging\n"
			"\tstatus of the syslog channel. \n"
			"\tType %s --help=\"logging\" for info about logging.\n"
			"3-) \"--version\" displays the version\n"
			"4-) reset: resets the node config\n"
			"	E.g., --reset\n"
			"Comment: Root privileges required.\n"
			"\n"
			"\t</----MISC---->\n"
			,
			app_name, EXIT_MESSAGE_FILE_NAME, app_name);

	printf("\n");
}

void init()
{
	elevate_privileges();
	_aggregatelogger = new Aggregatelogger(ruid);
	logger = _aggregatelogger;

	int ret = mkdir_p(DEFAULT_ACL_CONFIG_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	THROW_IF(ret != 0 && errno != EEXIST, "Failed to create DEFAULT_ACL_CONFIG_PATH");

	ret = mkdir_p(OWNERSHIP_MAP_FOLDER, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	THROW_IF(ret != 0 && errno != EEXIST, "Failed to create OWNERSHIP_MAP_FOLDER");

	acl = new Acl();
	lower_privileges();
}

void release()
{
	logger = NULL;
	delete _aggregatelogger;
	if(_filelogger)
	{
		delete _filelogger;
		_filelogger = NULL;
	}
	if(_syslogger)
	{
		delete _syslogger;
		_syslogger = NULL;
	}
	if(_stderrlogger)
	{
		delete _stderrlogger;
		_stderrlogger = NULL;
	}
}

bool create_logger(string options, string& err_out)
{
	Log_option_parser lop(options);	
	if(lop.has_error())
	{
		err_out = lop.get_error_message();
		return false;
	}

	Log_dest dest;
	vector< pair<Log_type, Activation> > levels;
	pair<Log_type, Activation> single_level;

	Log_type log_type = LOG_TYPE_INVALID;
	while((dest = lop.get_next_log_dest()) != LOG_DEST_DEV_NULL)
	{
		levels.clear();
		do
		{
			single_level = lop.get_next_level_activation();
			if(single_level.first == LOG_TYPE_INVALID)
				break;
			levels.push_back(single_level);
		}	
		while(true);
		switch(dest)
		{
			log_type = LOG_TYPE_INVALID;
			case LOG_DEST_SYSLOG:
				log_type = SUBSTRACT_LOG_TYPE(LOG_TYPE_ALL, LOG_TYPE_DEBUG); //default for syslog
				for(int i=0; i<(int)levels.size(); i++)
				{
					if(levels[i].second == ACTIVATION_DISABLED)
					{
						if(levels[i].first == LOG_TYPE_INFO)
						{
							if(!acl->is_allowed(ACL_DISABLE_SYSLOG_INFO))
							{
								std::ostringstream oss;
								oss<<"Permission denied! User "<<acl->get_uid()
									<<" is not allowed to deactivate INFO messages in syslog\n";
								err_out = oss.str();
								return false;
							}
							log_type = SUBSTRACT_LOG_TYPE(log_type, LOG_TYPE_INFO);
						}
						if(levels[i].first == LOG_TYPE_WARNING)
						{
							if(!acl->is_allowed(ACL_DISABLE_SYSLOG_WARNING))
							{
								std::ostringstream oss;
								oss<<"Permission denied! User "<<acl->get_uid()
									<<" is not allowed to deactivate WARNING messages in syslog\n";
								err_out = oss.str();
								return false;
							}
							log_type = SUBSTRACT_LOG_TYPE(log_type, LOG_TYPE_WARNING);
						}
						if(levels[i].first == LOG_TYPE_ERROR)
						{
							if(!acl->is_allowed(ACL_DISABLE_SYSLOG_ERROR))
							{
								std::ostringstream oss;
								oss<<"Permission denied! User "<<acl->get_uid()
									<<" is not allowed to deactivate ERROR messages in syslog\n";
								err_out = oss.str();
								return false;
							}
							log_type = SUBSTRACT_LOG_TYPE(log_type, LOG_TYPE_ERROR);
						}
					}
					else
					{
						if(levels[i].first == LOG_TYPE_DEBUG)
							log_type = ADD_LOG_TYPE(log_type, LOG_TYPE_DEBUG);
					}
				}
				_syslogger = new Syslogger(ruid, log_type);
				_aggregatelogger->add_logger(_syslogger);
				break;
			case LOG_DEST_STDERR:
			case LOG_DEST_FILE:
				log_type = LOG_TYPE_INVALID;
			   for(int i=0; i<(int)levels.size(); i++)
			   {
				   if(levels[i].second == ACTIVATION_ENABLED)
					   log_type = ADD_LOG_TYPE(log_type, levels[i].first);
			   }	   
			   if(log_type == LOG_TYPE_INVALID)
				   break;
			   if(dest == LOG_DEST_STDERR)
			   {
				   _stderrlogger = new Stderrlogger(ruid, log_type);
				   _aggregatelogger->add_logger(_stderrlogger);
			   }
			   else
			   {
				   _filelogger = new Filelogger(ruid, lop.get_filename(), log_type);
				   _aggregatelogger->add_logger(_filelogger);
			   }
			   break;
			default:
			   err_out = "Invalid log destination";
			   return false;
		}
	}
	return true;	
}	

enum Option_val
{
	/*--help*/
	OV_HELP = 'h',
	OV_ON_ERROR = 0xff+1,
	OV_LOG,

	/* --version*/
	OV_VERSION,

	/* --show_available_resources*/
	OV_SHOW_AVAILABLE_RESOURCES,

	/*--create_container="name:'c0' cpus:<int>[0,2,4,5,10-100s5,400] mems:[0-3]
	 * load_balancing:true cpu_exclusive:true mem_exclusive:false"
	*--create_container="name:c0 cpus:<int>[0,1] mems:[0]
	 * load_balancing:false cpu_exclusive:true mem_exclusive:false"
	 */
	OV_CREATE_CONTAINER,

	/*--delete_container="name:c0"*/
	OV_DELETE_CONTAINER,

	/*--show_config
	 * */
	OV_SHOW_CONFIG,

	/*--clean-config //This removes all the configs; leaving only the ServiceOS if applciable
	*/
	OV_CLEAN_CONFIG,

	/*--alter_container="name:'c0' cpus:<int>[0,2,4,5,10-100s5,400] mem:[0-3]
	 * load_balancing:true cpu_exclusive:true mem_exclusive:false"
	 * The name here must be an existing container
	 */
	OV_ALTER_CONTAINER,

	/*--attach_to_container="name:c0 pids:[pid list]"
	 * */
	OV_ATTACH_TO_CONTAINER,


	/*--detach_from_container="name:c0 pids:[pid list]"
	 * */
	OV_DETACH_FROM_CONTAINER,

	/*--migrate_to_container="name:c0 pids:[pid list]"
	 */
	OV_MIGRATE_TO_CONTAINER,

	OV_CREATE_SERVICE_OS, //need to be root


	OV_ALTER_SERVICE_OS,  //need to be root

	OV_DELETE_SERVICE_OS,

Kamil Iskra's avatar
Kamil Iskra committed
527 528
	OV_RESET,

529
	/*--exec="name:'c0' argv='argv0 argv1'" env='env1=val1 env2=val2'*/
Kamil Iskra's avatar
Kamil Iskra committed
530
	OV_EXEC
Swann Perarnau's avatar
Swann Perarnau committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
};


struct option long_options[] = {
	{"help", optional_argument, NULL, OV_HELP}, 
	{"on_error", required_argument, NULL, OV_ON_ERROR},
	{"log", required_argument, NULL, OV_LOG},
	{"version", no_argument, NULL, OV_VERSION},
	{"show_available_resources", optional_argument, NULL, OV_SHOW_AVAILABLE_RESOURCES},
	{"create_container", required_argument, NULL, OV_CREATE_CONTAINER},
	{"delete_container", required_argument, NULL, OV_DELETE_CONTAINER},
	{"alter_container", required_argument, NULL, OV_ALTER_CONTAINER},
	{"create_service_os", required_argument, NULL, OV_CREATE_SERVICE_OS},
	{"alter_service_os", required_argument, NULL, OV_ALTER_SERVICE_OS},
	{"delete_service_os", no_argument, NULL, OV_DELETE_SERVICE_OS},
	{"show_config", no_argument, NULL, OV_SHOW_CONFIG},
	{"clean_config", optional_argument, NULL, OV_CLEAN_CONFIG},
	{"attach_to_container", required_argument, NULL, OV_ATTACH_TO_CONTAINER},
	{"detach_from_container", required_argument, NULL, OV_DETACH_FROM_CONTAINER},
	{"migrate_to_container", required_argument, NULL, OV_MIGRATE_TO_CONTAINER},
	{"reset", no_argument, NULL, OV_RESET},
Kamil Iskra's avatar
Kamil Iskra committed
552
	{"exec", required_argument, NULL, OV_EXEC},
Swann Perarnau's avatar
Swann Perarnau committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649

		{0, 0, 0, 0}
};

bool cmd_error = false;

/*
 * If a help or version request is found, it is processed and then true is returned
 * */
bool parse_for_help_or_version(int argc, char** argv)
{
	int c;
	int index;
	optind = 1;
	while((c = getopt_long(argc, argv, "h", long_options, 
					&index)) != -1)
	{
		if(c == OV_HELP)
		{
			print_usage(argv[0], optarg ? optarg : "");
			return true;
		}
		else if(c == OV_VERSION)
		{
			printf("%s version %s\n\n", APP_NAME, VERSION);
			return true;
		}
		else if(c == '?' || c == ':')
		{
			cmd_error = true;
			return false;
		}
	}
	return false;
}


bool parse_for_environment(int argc, char** argv)
{
	int c;
	int index;

	optind = 1;
	while((c = getopt_long(argc, argv, "h", long_options, 
					&index)) != -1)
	{
		switch(c)
		{
			case OV_ON_ERROR:
				if(strcmp(optarg, "STOP") == 0)
					args.error_behavior = ON_ERROR_STOP;
				else if(strcmp(optarg, "CONTINUE") == 0)
					args.error_behavior = ON_ERROR_CONTINUE;
				else
				{
					error_message = 
						"Unsupported error behavior (weird \"--on_error\" argument)\n";
					goto __END_PARSING;
				}
				break;
			case OV_LOG:
				if(!create_logger(optarg, error_message))
					goto __END_PARSING;
				break;
			case '?':
			case ':':
				cmd_error = true;
				error_message = "Invalid command line option";
		}
	}

__END_PARSING:
	if(error_message != "")
	{
		std::cerr<<std::endl<<error_message<<std::endl;
		fprintf(stderr, "Execute %s -h for help\n\n", APP_NAME);
		return false;
	}

	return true;
}

bool parse_for_node_config(int argc, char** argv, Container_manager& cm)
{

	int c;
	int index;

	optind = 1;

	while((c = getopt_long(argc, argv, "h", long_options, 
					&index)) != -1)
	{
		switch(c)
		{
			case OV_HELP:
			case OV_ON_ERROR:
Kamil Iskra's avatar
Kamil Iskra committed
650
			case OV_LOG:
Swann Perarnau's avatar
Swann Perarnau committed
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
				break;  //handled elsewhere
			case OV_SHOW_AVAILABLE_RESOURCES:
				cm.show_available_resources(optarg ? optarg : "");
				break;
			case OV_CREATE_CONTAINER:
				cm.create_container(optarg);
				break;
			case OV_DELETE_CONTAINER:
				cm.delete_container(optarg);
				break;
			case OV_ALTER_CONTAINER:
				cm.alter_container(optarg);
				break;
			case OV_CREATE_SERVICE_OS:
				cm.create_service_os(optarg);
				break;
			case OV_ALTER_SERVICE_OS:
				cm.alter_service_os(optarg);
				break;
			case OV_DELETE_SERVICE_OS:
				cm.delete_service_os();
				break;
			case OV_SHOW_CONFIG:
				cm.show_config();
				break;
			case OV_CLEAN_CONFIG:
				cm.clean_config(optarg ? optarg : "");
				break;
			case OV_ATTACH_TO_CONTAINER:
				cm.attach_to_container(optarg);
				break;
			case OV_DETACH_FROM_CONTAINER:
				cm.detach_from_container(optarg);
				break;
			case OV_MIGRATE_TO_CONTAINER:
				cm.migrate_to_container(optarg);
				break;
			case OV_RESET:
				cm.reset();
				break;
Kamil Iskra's avatar
Kamil Iskra committed
691 692 693
			case OV_EXEC:
				cm.exec(optarg);
				break;
Swann Perarnau's avatar
Swann Perarnau committed
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
			case '?':
			case ':':
				cmd_error = true;
			default:
				return false;
		}
	}

	if(error_message != "")
	{
		std::cerr<<std::endl<<error_message<<std::endl;
		fprintf(stderr, "Execute %s -h for help\n\n", APP_NAME);
		return false;
	}

	return true;
}

int main(int argc, char** argv)
{
	ruid = getuid();
	euid = geteuid();
	//test_logs();
	lower_privileges();
	try
	{
		init();
	}
	catch(const std::runtime_error& e)
	{
		release();
		argo_exit(EXIT_FAILURE, e.what());
	}

	if(parse_for_help_or_version(argc, argv) || cmd_error)
	{
		release();
		if(cmd_error)
			argo_exit(EXIT_FAILURE, "Invalid command line");
		argo_exit(EXIT_SUCCESS, "Help invoked");
	}

	if(!parse_for_environment(argc, argv) || cmd_error)
	{
		release();
		argo_exit(EXIT_FAILURE, error_message);
	}

	Resource_locker rlock(LOCK_FILE_NAME, LOCK_FILE_FOLDER);
	while(!rlock.trylock());

	Container_manager *cm = NULL;

	try
	{
		cm = new Container_manager(logger, args.error_behavior);

		if(!parse_for_node_config(argc, argv, *cm))
		{
			delete cm;
			rlock.unlock();
			release();
			argo_exit(EXIT_FAILURE, error_message);
		}
	}
	catch(const std::runtime_error& e)
	{
		if(cm)
			delete cm;
		rlock.unlock();
		release();
		argo_exit(EXIT_FAILURE, e.what());
	}

Kamil Iskra's avatar
Kamil Iskra committed
768
	char** exec_argv = cm->get_exec_argv();
769
	char** exec_env = cm->get_exec_env();
Swann Perarnau's avatar
Swann Perarnau committed
770 771 772 773
	delete cm;

	rlock.unlock();
	release();
Kamil Iskra's avatar
Kamil Iskra committed
774 775 776 777

	/* We perform the execve(2) after all the cleanup is done.  */
	if (exec_argv)
	{
778 779
	    if (setuid(getuid()) == -1)
		argo_exit(EXIT_FAILURE, "Dropping privileges failed", errno);
780
	    execvpe(exec_argv[0], exec_argv, exec_env);
Kamil Iskra's avatar
Kamil Iskra committed
781 782 783
	    argo_exit(EXIT_FAILURE, "Command execution failed", errno);
	}

Swann Perarnau's avatar
Swann Perarnau committed
784 785 786
	argo_exit(EXIT_SUCCESS);
	return 0;
}