Example #1
0
        static void Main(string[] args)
        {
            CloudAdmin admin = new CloudAdmin();

            admin.SetPrompt("cloudb> ");
            admin.Interrupted += new EventHandler(CloudAdminInterrupted);

            Options options = new Options();

            admin.RegisterOptions(options);
            ICommandLineParser parser      = new GnuParser(options);
            CommandLine        commandLine = null;

            try {
                commandLine = parser.Parse(args);
            } catch (Exception e) {
                System.Console.Error.WriteLine("Error while parsing arguments: {0}", e.Message);
                Environment.Exit(1);
            }

            admin.HandleCommandLine(commandLine);

            try {
                admin.Run();
            } catch (Exception) {
                admin.Shutdown();
            }
        }
Example #2
0
        /// <exception cref="System.Exception"/>
        public static void Main(string[] argv)
        {
            CommandLine cliParser = new GnuParser().Parse(opts, argv);

            if (cliParser.HasOption("put"))
            {
                string path = cliParser.GetOptionValue("put");
                if (path != null && path.Length > 0)
                {
                    if (cliParser.HasOption(EntityDataType))
                    {
                        PutTimelineDataInJSONFile(path, EntityDataType);
                        return;
                    }
                    else
                    {
                        if (cliParser.HasOption(DomainDataType))
                        {
                            PutTimelineDataInJSONFile(path, DomainDataType);
                            return;
                        }
                    }
                }
            }
            PrintUsage();
        }
Example #3
0
        public virtual int Mknode(string[] args)
        {
            Options           mknodeOption = new Options();
            CommandLineParser parser       = new GnuParser();

            try
            {
                CommandLine    line     = parser.Parse(mknodeOption, args);
                IList <string> argsList = line.GetArgList();
                if (argsList.Count != 2)
                {
                    return(UsageError("mknode requires exactly one path argument", MknodeUsage));
                }
                if (!ValidatePath(argsList[1]))
                {
                    return(-1);
                }
                try
                {
                    registry.Mknode(args[1], false);
                    return(0);
                }
                catch (Exception e)
                {
                    syserr.WriteLine(AnalyzeException("mknode", e, argsList));
                }
                return(-1);
            }
            catch (ParseException exp)
            {
                return(UsageError("Invalid syntax " + exp.ToString(), MknodeUsage));
            }
        }
Example #4
0
        /// <exception cref="System.Exception"/>
        public static void Main(string[] args)
        {
            CommandLine cmd = new GnuParser().Parse(opts, args);

            if (cmd.HasOption("help"))
            {
                new HelpFormatter().PrintHelp("Usage: hbgen [OPTIONS]", opts);
                return;
            }
            // defaults
            Type   specClass     = typeof(HamletSpec);
            Type   implClass     = typeof(HamletImpl);
            string outputClass   = "HamletTmp";
            string outputPackage = implClass.Assembly.GetName();

            if (cmd.HasOption("spec-class"))
            {
                specClass = Sharpen.Runtime.GetType(cmd.GetOptionValue("spec-class"));
            }
            if (cmd.HasOption("impl-class"))
            {
                implClass = Sharpen.Runtime.GetType(cmd.GetOptionValue("impl-class"));
            }
            if (cmd.HasOption("output-class"))
            {
                outputClass = cmd.GetOptionValue("output-class");
            }
            if (cmd.HasOption("output-package"))
            {
                outputPackage = cmd.GetOptionValue("output-package");
            }
            new HamletGen().Generate(specClass, implClass, outputClass, outputPackage);
        }
Example #5
0
            internal static IDictionary <URI, IList <Path> > GetNameNodePathsToMove(Configuration
                                                                                    conf, params string[] args)
            {
                Options           opts        = BuildCliOptions();
                CommandLineParser parser      = new GnuParser();
                CommandLine       commandLine = parser.Parse(opts, args, true);

                return(GetNameNodePaths(commandLine, conf));
            }
 public void Parse(string[] args)
 {
     ParseHelp(args);
     Servers = new List<TeamCityServer>();
     var commandLine = new GnuParser().Parse(_options, args);
     ComPort = commandLine.GetOptionValue(Port);
     Console.WriteLine("Using port: " + ComPort);
     RunTimeMinutes = int.Parse(commandLine.GetOptionValue(RunTime));
     Console.WriteLine(String.Format("Running for {0} minutes", RunTimeMinutes));
     ParseServers(args);
 }
Example #7
0
        public void Parse(string[] args)
        {
            ParseHelp(args);
            Servers = new List <TeamCityServer>();
            var commandLine = new GnuParser().Parse(_options, args);

            ComPort = commandLine.GetOptionValue(Port);
            Console.WriteLine("Using port: " + ComPort);
            RunTimeMinutes = int.Parse(commandLine.GetOptionValue(RunTime));
            Console.WriteLine(String.Format("Running for {0} minutes", RunTimeMinutes));
            ParseServers(args);
        }
Example #8
0
        /// <summary>Parses arguments and fills out the member variables.</summary>
        /// <param name="args">Command-line arguments.</param>
        /// <returns>
        /// true on successful parse; false to indicate that the
        /// program should exit.
        /// </returns>
        private bool ParseArguments(string[] args)
        {
            Options     options = MakeOptions();
            CommandLine cli;

            try
            {
                CommandLineParser parser = new GnuParser();
                cli = parser.Parse(options, args);
            }
            catch (ParseException e)
            {
                Log.Warn("options parsing failed:  " + e.Message);
                new HelpFormatter().PrintHelp("...", options);
                return(false);
            }
            if (cli.HasOption("help"))
            {
                new HelpFormatter().PrintHelp("...", options);
                return(false);
            }
            if (cli.GetArgs().Length > 0)
            {
                foreach (string arg in cli.GetArgs())
                {
                    Log.Error("Unrecognized option: " + arg);
                    new HelpFormatter().PrintHelp("...", options);
                    return(false);
                }
            }
            // HDFS
            numDataNodes = IntArgument(cli, "datanodes", 1);
            nameNodePort = IntArgument(cli, "nnport", 0);
            if (cli.HasOption("format"))
            {
                dfsOpts = HdfsServerConstants.StartupOption.Format;
                format  = true;
            }
            else
            {
                dfsOpts = HdfsServerConstants.StartupOption.Regular;
                format  = false;
            }
            // Runner
            writeDetails = cli.GetOptionValue("writeDetails");
            writeConfig  = cli.GetOptionValue("writeConfig");
            // General
            conf = new HdfsConfiguration();
            UpdateConfiguration(conf, cli.GetOptionValues("D"));
            return(true);
        }
Example #9
0
        /// <summary>Parses arguments and fills out the member variables.</summary>
        /// <param name="args">Command-line arguments.</param>
        /// <returns>
        /// true on successful parse; false to indicate that the program should
        /// exit.
        /// </returns>
        private bool ParseArguments(string[] args)
        {
            Options     options = MakeOptions();
            CommandLine cli;

            try
            {
                CommandLineParser parser = new GnuParser();
                cli = parser.Parse(options, args);
            }
            catch (ParseException e)
            {
                Log.Warn("options parsing failed:  " + e.Message);
                new HelpFormatter().PrintHelp("...", options);
                return(false);
            }
            if (cli.HasOption("help"))
            {
                new HelpFormatter().PrintHelp("...", options);
                return(false);
            }
            if (cli.GetArgs().Length > 0)
            {
                foreach (string arg in cli.GetArgs())
                {
                    System.Console.Error.WriteLine("Unrecognized option: " + arg);
                    new HelpFormatter().PrintHelp("...", options);
                    return(false);
                }
            }
            // MR
            noMR            = cli.HasOption("nomr");
            numNodeManagers = IntArgument(cli, "nodemanagers", 1);
            rmPort          = IntArgument(cli, "rmport", 0);
            jhsPort         = IntArgument(cli, "jhsport", 0);
            fs = cli.GetOptionValue("namenode");
            // HDFS
            noDFS        = cli.HasOption("nodfs");
            numDataNodes = IntArgument(cli, "datanodes", 1);
            nnPort       = IntArgument(cli, "nnport", 0);
            dfsOpts      = cli.HasOption("format") ? HdfsServerConstants.StartupOption.Format : HdfsServerConstants.StartupOption
                           .Regular;
            // Runner
            writeDetails = cli.GetOptionValue("writeDetails");
            writeConfig  = cli.GetOptionValue("writeConfig");
            // General
            conf = new JobConf();
            UpdateConfiguration(conf, cli.GetOptionValues("D"));
            return(true);
        }
Example #10
0
        /// <exception cref="System.Exception"/>
        public override int Run(string[] args)
        {
            Options opts = new Options();

            opts.AddOption("lnl", ListLabelsCmd, false, "List cluster node-label collection");
            opts.AddOption("h", HelpCmd, false, "Displays help for all commands.");
            opts.AddOption("dnl", DirectlyAccessNodeLabelStore, false, "Directly access node label store, "
                           + "with this option, all node label related operations" + " will NOT connect RM. Instead, they will"
                           + " access/modify stored node labels directly." + " By default, it is false (access via RM)."
                           + " AND PLEASE NOTE: if you configured " + YarnConfiguration.FsNodeLabelsStoreRootDir
                           + " to a local directory" + " (instead of NFS or HDFS), this option will only work"
                           + " when the command run on the machine where RM is running." + " Also, this option is UNSTABLE, could be removed in future"
                           + " releases.");
            int         exitCode  = -1;
            CommandLine parsedCli = null;

            try
            {
                parsedCli = new GnuParser().Parse(opts, args);
            }
            catch (MissingArgumentException)
            {
                sysout.WriteLine("Missing argument for options");
                PrintUsage(opts);
                return(exitCode);
            }
            if (parsedCli.HasOption(DirectlyAccessNodeLabelStore))
            {
                accessLocal = true;
            }
            if (parsedCli.HasOption(ListLabelsCmd))
            {
                PrintClusterNodeLabels();
            }
            else
            {
                if (parsedCli.HasOption(HelpCmd))
                {
                    PrintUsage(opts);
                    return(0);
                }
                else
                {
                    syserr.WriteLine("Invalid Command Usage : ");
                    PrintUsage(opts);
                }
            }
            return(0);
        }
Example #11
0
        private void ParseHelp(string[] args)
        {
            var options = new Options();

            options.AddOption(_helpOption);
            options.AddOption(OptionBuilder.Factory.Create(Port));
            options.AddOption(OptionBuilder.Factory.Create(RunTime));
            options.AddOption(OptionBuilder.Factory.Create(Server));
            var commandLine = new GnuParser().Parse(options, args);

            if (commandLine.HasOption(Help) || args.Length == 0)
            {
                ShowHelp();
            }
        }
Example #12
0
        public virtual int Resolve(string[] args)
        {
            Options           resolveOption = new Options();
            CommandLineParser parser        = new GnuParser();

            try
            {
                CommandLine    line     = parser.Parse(resolveOption, args);
                IList <string> argsList = line.GetArgList();
                if (argsList.Count != 2)
                {
                    return(UsageError("resolve requires exactly one path argument", ResolveUsage));
                }
                if (!ValidatePath(argsList[1]))
                {
                    return(-1);
                }
                try
                {
                    ServiceRecord record = registry.Resolve(argsList[1]);
                    foreach (Endpoint endpoint in record.external)
                    {
                        sysout.WriteLine(" Endpoint(ProtocolType=" + endpoint.protocolType + ", Api=" + endpoint
                                         .api + ");" + " Addresses(AddressType=" + endpoint.addressType + ") are: ");
                        foreach (IDictionary <string, string> address in endpoint.addresses)
                        {
                            sysout.WriteLine("[ ");
                            foreach (KeyValuePair <string, string> entry in address)
                            {
                                sysout.Write("\t" + entry.Key + ":" + entry.Value);
                            }
                            sysout.WriteLine("\n]");
                        }
                        sysout.WriteLine();
                    }
                    return(0);
                }
                catch (Exception e)
                {
                    syserr.WriteLine(AnalyzeException("resolve", e, argsList));
                }
                return(-1);
            }
            catch (ParseException exp)
            {
                return(UsageError("Invalid syntax " + exp, ResolveUsage));
            }
        }
Example #13
0
        private void ParseServers(string[] args)
        {
            var parser        = new GnuParser();
            var serverOptions = new Options();

            serverOptions.AddOption(_serverOption);
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] != "-" + Server || i + 1 >= args.Length)
                {
                    continue;
                }
                var currentLine = parser.Parse(serverOptions, new[] { args[i], args[i + 1] });
                AddServer(currentLine.GetOptionValues(Server));
            }
        }
        /// <summary>
        /// Parse the user-specified options, get the generic options, and modify
        /// configuration accordingly
        /// </summary>
        /// <param name="opts">Options to use for parsing args.</param>
        /// <param name="conf">Configuration to be modified</param>
        /// <param name="args">User-specified arguments</param>
        /// <exception cref="System.IO.IOException"/>
        private void ParseGeneralOptions(Options opts, Configuration conf, string[] args)
        {
            opts = BuildGeneralOptions(opts);
            CommandLineParser parser = new GnuParser();

            try
            {
                commandLine = parser.Parse(opts, PreProcessForWindows(args), true);
                ProcessGeneralOptions(conf, commandLine);
            }
            catch (ParseException e)
            {
                Log.Warn("options parsing failed: " + e.Message);
                HelpFormatter formatter = new HelpFormatter();
                formatter.PrintHelp("general options are: ", opts);
            }
        }
Example #15
0
        /// <summary>parse args</summary>
        /// <exception cref="System.ArgumentException"/>
        private static CommandLine ParseArgs(Options opts, params string[] args)
        {
            OptionBuilder.WithArgName("NameNode|DataNode");
            OptionBuilder.HasArg();
            OptionBuilder.WithDescription("specify jmx service (NameNode by default)");
            Option jmx_service = OptionBuilder.Create("service");

            OptionBuilder.WithArgName("mbean server");
            OptionBuilder.HasArg();
            OptionBuilder.WithDescription("specify mbean server (localhost by default)");
            Option jmx_server = OptionBuilder.Create("server");

            OptionBuilder.WithDescription("print help");
            Option jmx_help = OptionBuilder.Create("help");

            OptionBuilder.WithArgName("mbean server port");
            OptionBuilder.HasArg();
            OptionBuilder.WithDescription("specify mbean server port, " + "if missing - it will try to connect to MBean Server in the same VM"
                                          );
            Option jmx_port = OptionBuilder.Create("port");

            OptionBuilder.WithArgName("VM's connector url");
            OptionBuilder.HasArg();
            OptionBuilder.WithDescription("connect to the VM on the same machine;" + "\n use:\n jstat -J-Djstat.showUnsupported=true -snap <vmpid> | "
                                          + "grep sun.management.JMXConnectorServer.address\n " + "to find the url");
            Option jmx_localVM = OptionBuilder.Create("localVM");

            opts.AddOption(jmx_server);
            opts.AddOption(jmx_help);
            opts.AddOption(jmx_service);
            opts.AddOption(jmx_port);
            opts.AddOption(jmx_localVM);
            CommandLine       commandLine = null;
            CommandLineParser parser      = new GnuParser();

            try
            {
                commandLine = parser.Parse(opts, args, true);
            }
            catch (ParseException e)
            {
                PrintUsage(opts);
                throw new ArgumentException("invalid args: " + e.Message);
            }
            return(commandLine);
        }
Example #16
0
 private MyOptions(string[] args)
 {
     try
     {
         Options           opts   = BuildOptions();
         CommandLineParser parser = new GnuParser();
         CommandLine       line   = parser.Parse(opts, args, true);
         ProcessOptions(line, opts);
         ValidateOptions();
     }
     catch (ParseException e)
     {
         System.Console.Error.WriteLine(e.Message);
         System.Console.Error.WriteLine("Try \"--help\" option for details.");
         failed = true;
     }
 }
Example #17
0
        /// <exception cref="System.Exception"/>
        public override int Run(string[] args)
        {
            Options opts = new Options();

            opts.AddOption(StatusCmd, true, "List queue information about given queue.");
            opts.AddOption(HelpCmd, false, "Displays help for all commands.");
            opts.GetOption(StatusCmd).SetArgName("Queue Name");
            CommandLine cliParser = null;

            try
            {
                cliParser = new GnuParser().Parse(opts, args);
            }
            catch (MissingArgumentException)
            {
                sysout.WriteLine("Missing argument for options");
                PrintUsage(opts);
                return(-1);
            }
            if (cliParser.HasOption(StatusCmd))
            {
                if (args.Length != 2)
                {
                    PrintUsage(opts);
                    return(-1);
                }
                return(ListQueue(cliParser.GetOptionValue(StatusCmd)));
            }
            else
            {
                if (cliParser.HasOption(HelpCmd))
                {
                    PrintUsage(opts);
                    return(0);
                }
                else
                {
                    syserr.WriteLine("Invalid Command Usage : ");
                    PrintUsage(opts);
                    return(-1);
                }
            }
        }
Example #18
0
 public MyOptions(string[] args)
 {
     // hard coded constants
     seed = Runtime.NanoTime();
     try
     {
         Options           opts   = BuildOptions();
         CommandLineParser parser = new GnuParser();
         CommandLine       line   = parser.Parse(opts, args, true);
         ProcessOptions(line, opts);
         ValidateOptions();
     }
     catch (ParseException e)
     {
         System.Console.Out.WriteLine(e.Message);
         System.Console.Out.WriteLine("Try \"--help\" option for details.");
         SetStopProceed();
     }
 }
Example #19
0
 public MyOptions(string[] args)
 {
     // special variable only for unit testing.
     // un-exposed parameters.
     seed = Runtime.NanoTime();
     try
     {
         Options           opts   = BuildOptions();
         CommandLineParser parser = new GnuParser();
         CommandLine       line   = parser.Parse(opts, args, true);
         ProcessOptions(line, opts);
         ValidateOptions();
     }
     catch (ParseException e)
     {
         System.Console.Out.WriteLine(e.Message);
         System.Console.Out.WriteLine("Try \"--help\" option for details.");
         SetStopProceed();
     }
 }
Example #20
0
        /// <exception cref="Org.Apache.Commons.Cli.ParseException"/>
        public virtual bool Init(string[] args)
        {
            Options opts = new Options();

            opts.AddOption("appname", true, "Application Name. Default value - UnmanagedAM");
            opts.AddOption("priority", true, "Application Priority. Default 0");
            opts.AddOption("queue", true, "RM Queue in which this application is to be submitted"
                           );
            opts.AddOption("master_memory", true, "Amount of memory in MB to be requested to run the application master"
                           );
            opts.AddOption("cmd", true, "command to start unmanaged AM (required)");
            opts.AddOption("classpath", true, "additional classpath");
            opts.AddOption("help", false, "Print usage");
            CommandLine cliParser = new GnuParser().Parse(opts, args);

            if (args.Length == 0)
            {
                PrintUsage(opts);
                throw new ArgumentException("No args specified for client to initialize");
            }
            if (cliParser.HasOption("help"))
            {
                PrintUsage(opts);
                return(false);
            }
            appName    = cliParser.GetOptionValue("appname", "UnmanagedAM");
            amPriority = System.Convert.ToInt32(cliParser.GetOptionValue("priority", "0"));
            amQueue    = cliParser.GetOptionValue("queue", "default");
            classpath  = cliParser.GetOptionValue("classpath", null);
            amCmd      = cliParser.GetOptionValue("cmd");
            if (amCmd == null)
            {
                PrintUsage(opts);
                throw new ArgumentException("No cmd specified for application master");
            }
            YarnConfiguration yarnConf = new YarnConfiguration(conf);

            rmClient = YarnClient.CreateYarnClient();
            rmClient.Init(yarnConf);
            return(true);
        }
Example #21
0
        public virtual int Rm(string[] args)
        {
            Option  recursive = OptionBuilder.Create("r");
            Options rmOption  = new Options();

            rmOption.AddOption(recursive);
            bool recursiveOpt        = false;
            CommandLineParser parser = new GnuParser();

            try
            {
                CommandLine    line     = parser.Parse(rmOption, args);
                IList <string> argsList = line.GetArgList();
                if (argsList.Count != 2)
                {
                    return(UsageError("RM requires exactly one path argument", RmUsage));
                }
                if (!ValidatePath(argsList[1]))
                {
                    return(-1);
                }
                try
                {
                    if (line.HasOption("r"))
                    {
                        recursiveOpt = true;
                    }
                    registry.Delete(argsList[1], recursiveOpt);
                    return(0);
                }
                catch (Exception e)
                {
                    syserr.WriteLine(AnalyzeException("rm", e, argsList));
                }
                return(-1);
            }
            catch (ParseException exp)
            {
                return(UsageError("Invalid syntax " + exp.ToString(), RmUsage));
            }
        }
Example #22
0
        public virtual int Ls(string[] args)
        {
            Options           lsOption = new Options();
            CommandLineParser parser   = new GnuParser();

            try
            {
                CommandLine    line     = parser.Parse(lsOption, args);
                IList <string> argsList = line.GetArgList();
                if (argsList.Count != 2)
                {
                    return(UsageError("ls requires exactly one path argument", LsUsage));
                }
                if (!ValidatePath(argsList[1]))
                {
                    return(-1);
                }
                try
                {
                    IList <string> children = registry.List(argsList[1]);
                    foreach (string child in children)
                    {
                        sysout.WriteLine(child);
                    }
                    return(0);
                }
                catch (Exception e)
                {
                    syserr.WriteLine(AnalyzeException("ls", e, argsList));
                }
                return(-1);
            }
            catch (ParseException exp)
            {
                return(UsageError("Invalid syntax " + exp, LsUsage));
            }
        }
Example #23
0
        private static int Main(string[] args)
        {
            string nodeConfig = null, netConfig = null;
            string hostArg = null, portArg = null;

            StringWriter wout    = new StringWriter();
            Options      options = GetOptions();

            CommandLine commandLine = null;

            bool failed    = false;
            bool isService = false;

            try {
                ICommandLineParser parser = new GnuParser(options);
                commandLine = parser.Parse(args);

                nodeConfig = commandLine.GetOptionValue("nodeconfig", "./node.conf");
                netConfig  = commandLine.GetOptionValue("netconfig", "./network.conf");
                hostArg    = commandLine.GetOptionValue("host");
                portArg    = commandLine.GetOptionValue("port");
            } catch (ParseException) {
                wout.WriteLine("Error parsing arguments.");
                failed = true;
            }

            if (commandLine != null)
            {
                if (commandLine.HasOption("install"))
                {
                    try {
                        Install(commandLine);
                        Console.Out.WriteLine("Service installed succesfully.");
                        return(0);
                    } catch (Exception e) {
                        Console.Error.WriteLine("Error installing service: " + e.Message);
#if DEBUG
                        Console.Error.WriteLine(e.StackTrace);
#endif
                        return(1);
                    }
                }
                if (commandLine.HasOption("uninstall"))
                {
                    try {
                        Uninstall();
                        Console.Out.WriteLine("Service uninstalled succesfully.");
                        return(0);
                    } catch (Exception e) {
                        Console.Error.WriteLine("Error uninstalling service: " + e.Message);
#if DEBUG
                        Console.Error.WriteLine(e.StackTrace);
#endif
                        return(1);
                    }
                }

                isService = commandLine.HasOption("service");
            }

            if (isService)
            {
                MachineNodeService mnodeService = new MachineNodeService(commandLine);

                try {
                    if (Environment.UserInteractive)
                    {
                        mnodeService.Start(args);
                        Console.Out.WriteLine("Press any key to stop...");
                        Console.Read();
                        mnodeService.Stop();
                    }
                    else
                    {
                        ServiceBase.Run(mnodeService);
                    }
                } catch (Exception) {
                    return(1);
                }

                return(0);
            }

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
            SetEventHandlers();

            ProductInfo libInfo  = ProductInfo.GetProductInfo(typeof(TcpAdminService));
            ProductInfo nodeInfo = ProductInfo.GetProductInfo(typeof(MachineNode));

            Console.Out.WriteLine("{0} {1} ( {2} )", nodeInfo.Title, nodeInfo.Version, nodeInfo.Copyright);
            Console.Out.WriteLine(nodeInfo.Description);
            Console.Out.WriteLine();
            Console.Out.WriteLine("{0} {1} ( {2} )", libInfo.Title, libInfo.Version, libInfo.Copyright);

            // Check arguments that can be null,
            if (netConfig == null)
            {
                wout.WriteLine("Error, no network configuration given.");
                failed = true;
            }
            else if (nodeConfig == null)
            {
                wout.WriteLine("Error, no node configuration file given.");
                failed = true;
            }
            //if (portArg == null) {
            //    wout.WriteLine("Error, no port address given.");
            //    failed = true;
            //}

            if (!failed)
            {
                //TODO: support for remote (eg. HTTP, FTP, TCP/IP) configurations)

                nodeConfig = NormalizeFilePath(nodeConfig);
                netConfig  = NormalizeFilePath(netConfig);

                if (!File.Exists(nodeConfig))
                {
                    wout.WriteLine("Error, node configuration file not found ({0}).", nodeConfig);
                    failed = true;
                }
                else if (!File.Exists(netConfig))
                {
                    wout.WriteLine("Error, node configuration file not found ({0}).", netConfig);
                    failed = true;
                }
            }

            wout.Flush();

            // If failed,
            if (failed)
            {
                HelpFormatter formatter = new HelpFormatter();
                if (!IsConsoleRedirected())
                {
                    formatter.Width = Console.WindowWidth;
                }
                formatter.CommandLineSyntax = "mnode";
                formatter.Options           = options;
                formatter.PrintHelp();
                Console.Out.WriteLine();
                Console.Out.WriteLine(wout.ToString());
                return(1);
            }

            try {
#if DEBUG
                Console.Out.WriteLine("Retrieving node configuration from {0}", nodeConfig);
#endif

                // Get the node configuration file,
                ConfigSource nodeConfigSource = new ConfigSource();
                using (FileStream fin = new FileStream(nodeConfig, FileMode.Open, FileAccess.Read, FileShare.None)) {
                    //TODO: make it configurable ...
                    nodeConfigSource.LoadProperties(new BufferedStream(fin));
                }

#if DEBUG
                Console.Out.WriteLine("Retrieving network configuration from {0}", netConfig);
#endif

                // Parse the network configuration string,
                NetworkConfigSource netConfigSource;
                using (FileStream stream = new FileStream(netConfig, FileMode.Open, FileAccess.Read, FileShare.None)) {
                    netConfigSource = new NetworkConfigSource();
                    //TODO: make it configurable ...
                    netConfigSource.LoadProperties(stream);
                }

                string password = nodeConfigSource.GetString("network_password", null);
                if (password == null)
                {
                    Console.Out.WriteLine("Error: couldn't determine the network password.");
                    return(1);
                }

                // configure the loggers
                Logger.Init(nodeConfigSource);

                //TODO: support also IPv6

                // The base path,
                IPAddress host = null;
                if (hostArg != null)
                {
                    IPAddress[] addresses = Dns.GetHostAddresses(hostArg);
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        IPAddress address = addresses[i];
                        if (address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            host = address;
                            break;
                        }
                    }
                }
                else
                {
                    host = IPAddress.Loopback;
                }

                if (host == null)
                {
                    Console.Out.WriteLine("Error: couldn't determine the host address.");
                    return(1);
                }

                int port = DefaultPort;
                if (!String.IsNullOrEmpty(portArg))
                {
                    if (!Int32.TryParse(portArg, out port))
                    {
                        Console.Out.WriteLine("Error: couldn't parse port argument: " + portArg);
                        return(1);
                    }
                }

                string          storage        = commandLine.GetOptionValue("storage", null);
                IServiceFactory serviceFactory = GetServiceFactory(storage, nodeConfigSource);

                Console.Out.WriteLine("Machine Node, " + host + " : " + port);
                service        = new TcpAdminService(serviceFactory, host, port, password);
                service.Config = netConfigSource;
                service.Start();

                Console.Out.WriteLine();
                Console.Out.WriteLine();
                Console.Out.WriteLine("Press CTRL+C to quit...");

                waitHandle = new AutoResetEvent(false);
                waitHandle.WaitOne();
            } catch (Exception e) {
                Console.Out.WriteLine(e.Message);
                Console.Out.WriteLine(e.StackTrace);
                return(1);
            } finally {
                if (service != null)
                {
                    service.Dispose();
                }
            }

            return(0);
        }
 private void ParseServers(string[] args)
 {
     var parser = new GnuParser();
     var serverOptions = new Options();
     serverOptions.AddOption(_serverOption);
     for (int i = 0; i < args.Length; i++)
     {
         if (args[i] != "-" + Server || i + 1 >= args.Length) continue;
         var currentLine = parser.Parse(serverOptions, new[] {args[i], args[i + 1]});
         AddServer(currentLine.GetOptionValues(Server));
     }
 }
 private void ParseHelp(string[] args)
 {
     var options = new Options();
     options.AddOption(_helpOption);
     options.AddOption(OptionBuilder.Factory.Create(Port));
     options.AddOption(OptionBuilder.Factory.Create(RunTime));
     options.AddOption(OptionBuilder.Factory.Create(Server));
     var commandLine = new GnuParser().Parse(options, args);
     if (commandLine.HasOption(Help) || args.Length == 0)
     {
         ShowHelp();
     }
 }
Example #26
0
        /// <exception cref="System.Exception"/>
        public virtual int Run(string[] args)
        {
            Options opts = new Options();

            opts.AddOption(HelpCmd, false, "Displays help for all commands.");
            Option appIdOpt = new Option(ApplicationIdOption, true, "ApplicationId (required)"
                                         );

            appIdOpt.SetRequired(true);
            opts.AddOption(appIdOpt);
            opts.AddOption(ContainerIdOption, true, "ContainerId (must be specified if node address is specified)"
                           );
            opts.AddOption(NodeAddressOption, true, "NodeAddress in the format " + "nodename:port (must be specified if container id is specified)"
                           );
            opts.AddOption(AppOwnerOption, true, "AppOwner (assumed to be current user if not specified)"
                           );
            opts.GetOption(ApplicationIdOption).SetArgName("Application ID");
            opts.GetOption(ContainerIdOption).SetArgName("Container ID");
            opts.GetOption(NodeAddressOption).SetArgName("Node Address");
            opts.GetOption(AppOwnerOption).SetArgName("Application Owner");
            Options printOpts = new Options();

            printOpts.AddOption(opts.GetOption(HelpCmd));
            printOpts.AddOption(opts.GetOption(ContainerIdOption));
            printOpts.AddOption(opts.GetOption(NodeAddressOption));
            printOpts.AddOption(opts.GetOption(AppOwnerOption));
            if (args.Length < 1)
            {
                PrintHelpMessage(printOpts);
                return(-1);
            }
            if (args[0].Equals("-help"))
            {
                PrintHelpMessage(printOpts);
                return(0);
            }
            CommandLineParser parser         = new GnuParser();
            string            appIdStr       = null;
            string            containerIdStr = null;
            string            nodeAddress    = null;
            string            appOwner       = null;

            try
            {
                CommandLine commandLine = parser.Parse(opts, args, true);
                appIdStr       = commandLine.GetOptionValue(ApplicationIdOption);
                containerIdStr = commandLine.GetOptionValue(ContainerIdOption);
                nodeAddress    = commandLine.GetOptionValue(NodeAddressOption);
                appOwner       = commandLine.GetOptionValue(AppOwnerOption);
            }
            catch (ParseException e)
            {
                System.Console.Error.WriteLine("options parsing failed: " + e.Message);
                PrintHelpMessage(printOpts);
                return(-1);
            }
            if (appIdStr == null)
            {
                System.Console.Error.WriteLine("ApplicationId cannot be null!");
                PrintHelpMessage(printOpts);
                return(-1);
            }
            ApplicationId appId = null;

            try
            {
                appId = ConverterUtils.ToApplicationId(appIdStr);
            }
            catch (Exception)
            {
                System.Console.Error.WriteLine("Invalid ApplicationId specified");
                return(-1);
            }
            try
            {
                int resultCode = VerifyApplicationState(appId);
                if (resultCode != 0)
                {
                    System.Console.Out.WriteLine("Logs are not avaiable right now.");
                    return(resultCode);
                }
            }
            catch (Exception)
            {
                System.Console.Error.WriteLine("Unable to get ApplicationState." + " Attempting to fetch logs directly from the filesystem."
                                               );
            }
            LogCLIHelpers logCliHelper = new LogCLIHelpers();

            logCliHelper.SetConf(GetConf());
            if (appOwner == null || appOwner.IsEmpty())
            {
                appOwner = UserGroupInformation.GetCurrentUser().GetShortUserName();
            }
            int resultCode_1 = 0;

            if (containerIdStr == null && nodeAddress == null)
            {
                resultCode_1 = logCliHelper.DumpAllContainersLogs(appId, appOwner, System.Console.Out
                                                                  );
            }
            else
            {
                if ((containerIdStr == null && nodeAddress != null) || (containerIdStr != null &&
                                                                        nodeAddress == null))
                {
                    System.Console.Out.WriteLine("ContainerId or NodeAddress cannot be null!");
                    PrintHelpMessage(printOpts);
                    resultCode_1 = -1;
                }
                else
                {
                    resultCode_1 = logCliHelper.DumpAContainersLogs(appIdStr, containerIdStr, nodeAddress
                                                                    , appOwner);
                }
            }
            return(resultCode_1);
        }
Example #27
0
        public virtual int Bind(string[] args)
        {
            Option  rest       = OptionBuilder.Create("rest");
            Option  webui      = OptionBuilder.Create("webui");
            Option  inet       = OptionBuilder.Create("inet");
            Option  port       = OptionBuilder.Create("p");
            Option  host       = OptionBuilder.Create("h");
            Option  apiOpt     = OptionBuilder.Create("api");
            Options inetOption = new Options();

            inetOption.AddOption(inet);
            inetOption.AddOption(port);
            inetOption.AddOption(host);
            inetOption.AddOption(apiOpt);
            Options webuiOpt = new Options();

            webuiOpt.AddOption(webui);
            webuiOpt.AddOption(apiOpt);
            Options restOpt = new Options();

            restOpt.AddOption(rest);
            restOpt.AddOption(apiOpt);
            CommandLineParser parser = new GnuParser();
            ServiceRecord     sr     = new ServiceRecord();
            CommandLine       line;

            if (args.Length <= 1)
            {
                return(UsageError("Invalid syntax ", BindUsage));
            }
            if (args[1].Equals("-inet"))
            {
                int    portNum;
                string hostName;
                string api;
                try
                {
                    line = parser.Parse(inetOption, args);
                }
                catch (ParseException exp)
                {
                    return(UsageError("Invalid syntax " + exp.Message, BindUsage));
                }
                if (line.HasOption("inet") && line.HasOption("p") && line.HasOption("h") && line.
                    HasOption("api"))
                {
                    try
                    {
                        portNum = System.Convert.ToInt32(line.GetOptionValue("p"));
                    }
                    catch (FormatException exp)
                    {
                        return(UsageError("Invalid Port - int required" + exp.Message, BindUsage));
                    }
                    hostName = line.GetOptionValue("h");
                    api      = line.GetOptionValue("api");
                    sr.AddExternalEndpoint(RegistryTypeUtils.InetAddrEndpoint(api, ProtocolTypes.ProtocolHadoopIpc
                                                                              , hostName, portNum));
                }
                else
                {
                    return(UsageError("Missing options: must have host, port and api", BindUsage));
                }
            }
            else
            {
                if (args[1].Equals("-webui"))
                {
                    try
                    {
                        line = parser.Parse(webuiOpt, args);
                    }
                    catch (ParseException exp)
                    {
                        return(UsageError("Invalid syntax " + exp.Message, BindUsage));
                    }
                    if (line.HasOption("webui") && line.HasOption("api"))
                    {
                        URI theUri;
                        try
                        {
                            theUri = new URI(line.GetOptionValue("webui"));
                        }
                        catch (URISyntaxException e)
                        {
                            return(UsageError("Invalid URI: " + e.Message, BindUsage));
                        }
                        sr.AddExternalEndpoint(RegistryTypeUtils.WebEndpoint(line.GetOptionValue("api"),
                                                                             theUri));
                    }
                    else
                    {
                        return(UsageError("Missing options: must have value for uri and api", BindUsage));
                    }
                }
                else
                {
                    if (args[1].Equals("-rest"))
                    {
                        try
                        {
                            line = parser.Parse(restOpt, args);
                        }
                        catch (ParseException exp)
                        {
                            return(UsageError("Invalid syntax " + exp.Message, BindUsage));
                        }
                        if (line.HasOption("rest") && line.HasOption("api"))
                        {
                            URI theUri = null;
                            try
                            {
                                theUri = new URI(line.GetOptionValue("rest"));
                            }
                            catch (URISyntaxException e)
                            {
                                return(UsageError("Invalid URI: " + e.Message, BindUsage));
                            }
                            sr.AddExternalEndpoint(RegistryTypeUtils.RestEndpoint(line.GetOptionValue("api"),
                                                                                  theUri));
                        }
                        else
                        {
                            return(UsageError("Missing options: must have value for uri and api", BindUsage));
                        }
                    }
                    else
                    {
                        return(UsageError("Invalid syntax", BindUsage));
                    }
                }
            }
            IList <string> argsList = line.GetArgList();

            if (argsList.Count != 2)
            {
                return(UsageError("bind requires exactly one path argument", BindUsage));
            }
            if (!ValidatePath(argsList[1]))
            {
                return(-1);
            }
            try
            {
                registry.Bind(argsList[1], sr, BindFlags.Overwrite);
                return(0);
            }
            catch (Exception e)
            {
                syserr.WriteLine(AnalyzeException("bind", e, argsList));
            }
            return(-1);
        }
Example #28
0
        public ArgumentParser(string[] arguments)
        {
            _Parser = new GnuParser();

            var options = new Options();

            options.AddOption(OptionBuilder.Factory
                              .IsRequired()
                              .WithLongOpt("database")
                              .HasArg()
                              .Create(OptionDatabase));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("scriptCreate")
                              .WithArgName(OptionScriptCreate)
                              .Create(OptionScriptCreate));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("scriptIndividual")
                              .Create(OptionScriptIndividual));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("schemaVersion")
                              .Create(OptionSchemaVersion));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("createDatabase")
                              .Create(OptionCreateDatabase));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("resetDatabase")
                              .Create(OptionResetDatabase));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("noWait")
                              .Create(OptionNoWait));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("setDirectoryBase")
                              .HasArg()
                              .Create(OptionSetDirectoryBase));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("setConnectionString")
                              .HasArg()
                              .Create(OptionSetConnectionString));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("tableData")
                              .HasArgs(2)
                              .Create(OptionTableData));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt(OptionCreateSchemaLogTable)
                              .Create(OptionCreateSchemaLogTable));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("update")
                              .HasOptionalArg()
                              .Create(OptionUpdateDatabase));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("runScript")
                              .HasArg()
                              .Create(OptionRunScript));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("backup")
                              .HasArg()
                              .Create(OptionBackup));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("restore")
                              .HasArg()
                              .Create(OptionRestore));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("generateUpdate")
                              .HasArg()
                              .Create(OptionGenerateUpdate));
            options.AddOption(OptionBuilder.Factory
                              .WithLongOpt("markSchemaChangesWithLatestVersion")
                              .Create(OptionMarkSchemaChangesWithLatestVersion));
            _Line = _Parser.Parse(options, arguments);
        }
Example #29
0
        /// <exception cref="System.Exception"/>
        public override int Run(string[] args)
        {
            Options opts  = new Options();
            string  title = null;

            if (args.Length > 0 && Sharpen.Runtime.EqualsIgnoreCase(args[0], Application))
            {
                title = Application;
                opts.AddOption(StatusCmd, true, "Prints the status of the application.");
                opts.AddOption(ListCmd, false, "List applications. " + "Supports optional use of -appTypes to filter applications "
                               + "based on application type, " + "and -appStates to filter applications based on application state."
                               );
                opts.AddOption(KillCmd, true, "Kills the application.");
                opts.AddOption(MoveToQueueCmd, true, "Moves the application to a " + "different queue."
                               );
                opts.AddOption(QueueCmd, true, "Works with the movetoqueue command to" + " specify which queue to move an application to."
                               );
                opts.AddOption(HelpCmd, false, "Displays help for all commands.");
                Option appTypeOpt = new Option(AppTypeCmd, true, "Works with -list to " + "filter applications based on "
                                               + "input comma-separated list of application types.");
                appTypeOpt.SetValueSeparator(',');
                appTypeOpt.SetArgs(Option.UnlimitedValues);
                appTypeOpt.SetArgName("Types");
                opts.AddOption(appTypeOpt);
                Option appStateOpt = new Option(AppStateCmd, true, "Works with -list " + "to filter applications based on input comma-separated list of "
                                                + "application states. " + GetAllValidApplicationStates());
                appStateOpt.SetValueSeparator(',');
                appStateOpt.SetArgs(Option.UnlimitedValues);
                appStateOpt.SetArgName("States");
                opts.AddOption(appStateOpt);
                opts.GetOption(KillCmd).SetArgName("Application ID");
                opts.GetOption(MoveToQueueCmd).SetArgName("Application ID");
                opts.GetOption(QueueCmd).SetArgName("Queue Name");
                opts.GetOption(StatusCmd).SetArgName("Application ID");
            }
            else
            {
                if (args.Length > 0 && Sharpen.Runtime.EqualsIgnoreCase(args[0], ApplicationAttempt
                                                                        ))
                {
                    title = ApplicationAttempt;
                    opts.AddOption(StatusCmd, true, "Prints the status of the application attempt.");
                    opts.AddOption(ListCmd, true, "List application attempts for aplication.");
                    opts.AddOption(HelpCmd, false, "Displays help for all commands.");
                    opts.GetOption(StatusCmd).SetArgName("Application Attempt ID");
                    opts.GetOption(ListCmd).SetArgName("Application ID");
                }
                else
                {
                    if (args.Length > 0 && Sharpen.Runtime.EqualsIgnoreCase(args[0], Container))
                    {
                        title = Container;
                        opts.AddOption(StatusCmd, true, "Prints the status of the container.");
                        opts.AddOption(ListCmd, true, "List containers for application attempt.");
                        opts.AddOption(HelpCmd, false, "Displays help for all commands.");
                        opts.GetOption(StatusCmd).SetArgName("Container ID");
                        opts.GetOption(ListCmd).SetArgName("Application Attempt ID");
                    }
                }
            }
            int         exitCode  = -1;
            CommandLine cliParser = null;

            try
            {
                cliParser = new GnuParser().Parse(opts, args);
            }
            catch (MissingArgumentException)
            {
                sysout.WriteLine("Missing argument for options");
                PrintUsage(title, opts);
                return(exitCode);
            }
            if (cliParser.HasOption(StatusCmd))
            {
                if (args.Length != 3)
                {
                    PrintUsage(title, opts);
                    return(exitCode);
                }
                if (Sharpen.Runtime.EqualsIgnoreCase(args[0], Application))
                {
                    exitCode = PrintApplicationReport(cliParser.GetOptionValue(StatusCmd));
                }
                else
                {
                    if (Sharpen.Runtime.EqualsIgnoreCase(args[0], ApplicationAttempt))
                    {
                        exitCode = PrintApplicationAttemptReport(cliParser.GetOptionValue(StatusCmd));
                    }
                    else
                    {
                        if (Sharpen.Runtime.EqualsIgnoreCase(args[0], Container))
                        {
                            exitCode = PrintContainerReport(cliParser.GetOptionValue(StatusCmd));
                        }
                    }
                }
                return(exitCode);
            }
            else
            {
                if (cliParser.HasOption(ListCmd))
                {
                    if (Sharpen.Runtime.EqualsIgnoreCase(args[0], Application))
                    {
                        allAppStates = false;
                        ICollection <string> appTypes = new HashSet <string>();
                        if (cliParser.HasOption(AppTypeCmd))
                        {
                            string[] types = cliParser.GetOptionValues(AppTypeCmd);
                            if (types != null)
                            {
                                foreach (string type in types)
                                {
                                    if (!type.Trim().IsEmpty())
                                    {
                                        appTypes.AddItem(StringUtils.ToUpperCase(type).Trim());
                                    }
                                }
                            }
                        }
                        EnumSet <YarnApplicationState> appStates = EnumSet.NoneOf <YarnApplicationState>();
                        if (cliParser.HasOption(AppStateCmd))
                        {
                            string[] states = cliParser.GetOptionValues(AppStateCmd);
                            if (states != null)
                            {
                                foreach (string state in states)
                                {
                                    if (!state.Trim().IsEmpty())
                                    {
                                        if (Sharpen.Runtime.EqualsIgnoreCase(state.Trim(), AllstatesOption))
                                        {
                                            allAppStates = true;
                                            break;
                                        }
                                        try
                                        {
                                            appStates.AddItem(YarnApplicationState.ValueOf(StringUtils.ToUpperCase(state).Trim
                                                                                               ()));
                                        }
                                        catch (ArgumentException)
                                        {
                                            sysout.WriteLine("The application state " + state + " is invalid.");
                                            sysout.WriteLine(GetAllValidApplicationStates());
                                            return(exitCode);
                                        }
                                    }
                                }
                            }
                        }
                        ListApplications(appTypes, appStates);
                    }
                    else
                    {
                        if (Sharpen.Runtime.EqualsIgnoreCase(args[0], ApplicationAttempt))
                        {
                            if (args.Length != 3)
                            {
                                PrintUsage(title, opts);
                                return(exitCode);
                            }
                            ListApplicationAttempts(cliParser.GetOptionValue(ListCmd));
                        }
                        else
                        {
                            if (Sharpen.Runtime.EqualsIgnoreCase(args[0], Container))
                            {
                                if (args.Length != 3)
                                {
                                    PrintUsage(title, opts);
                                    return(exitCode);
                                }
                                ListContainers(cliParser.GetOptionValue(ListCmd));
                            }
                        }
                    }
                }
                else
                {
                    if (cliParser.HasOption(KillCmd))
                    {
                        if (args.Length != 3)
                        {
                            PrintUsage(title, opts);
                            return(exitCode);
                        }
                        try
                        {
                            KillApplication(cliParser.GetOptionValue(KillCmd));
                        }
                        catch (ApplicationNotFoundException)
                        {
                            return(exitCode);
                        }
                    }
                    else
                    {
                        if (cliParser.HasOption(MoveToQueueCmd))
                        {
                            if (!cliParser.HasOption(QueueCmd))
                            {
                                PrintUsage(title, opts);
                                return(exitCode);
                            }
                            MoveApplicationAcrossQueues(cliParser.GetOptionValue(MoveToQueueCmd), cliParser.GetOptionValue
                                                            (QueueCmd));
                        }
                        else
                        {
                            if (cliParser.HasOption(HelpCmd))
                            {
                                PrintUsage(title, opts);
                                return(0);
                            }
                            else
                            {
                                syserr.WriteLine("Invalid Command Usage : ");
                                PrintUsage(title, opts);
                            }
                        }
                    }
                }
            }
            return(0);
        }
Example #30
0
        /// <exception cref="System.Exception"/>
        public override int Run(string[] args)
        {
            Options opts = new Options();

            opts.AddOption(HelpCmd, false, "Displays help for all commands.");
            opts.AddOption(StatusCmd, true, "Prints the status report of the node.");
            opts.AddOption(ListCmd, false, "List all running nodes. " + "Supports optional use of -states to filter nodes "
                           + "based on node state, all -all to list all nodes.");
            Option nodeStateOpt = new Option(NodeStateCmd, true, "Works with -list to filter nodes based on input comma-separated list of node states."
                                             );

            nodeStateOpt.SetValueSeparator(',');
            nodeStateOpt.SetArgs(Option.UnlimitedValues);
            nodeStateOpt.SetArgName("States");
            opts.AddOption(nodeStateOpt);
            Option allOpt = new Option(NodeAll, false, "Works with -list to list all nodes.");

            opts.AddOption(allOpt);
            opts.GetOption(StatusCmd).SetArgName("NodeId");
            int         exitCode  = -1;
            CommandLine cliParser = null;

            try
            {
                cliParser = new GnuParser().Parse(opts, args);
            }
            catch (MissingArgumentException)
            {
                sysout.WriteLine("Missing argument for options");
                PrintUsage(opts);
                return(exitCode);
            }
            if (cliParser.HasOption("status"))
            {
                if (args.Length != 2)
                {
                    PrintUsage(opts);
                    return(exitCode);
                }
                PrintNodeStatus(cliParser.GetOptionValue("status"));
            }
            else
            {
                if (cliParser.HasOption("list"))
                {
                    ICollection <NodeState> nodeStates = new HashSet <NodeState>();
                    if (cliParser.HasOption(NodeAll))
                    {
                        foreach (NodeState state in NodeState.Values())
                        {
                            nodeStates.AddItem(state);
                        }
                    }
                    else
                    {
                        if (cliParser.HasOption(NodeStateCmd))
                        {
                            string[] types = cliParser.GetOptionValues(NodeStateCmd);
                            if (types != null)
                            {
                                foreach (string type in types)
                                {
                                    if (!type.Trim().IsEmpty())
                                    {
                                        nodeStates.AddItem(NodeState.ValueOf(StringUtils.ToUpperCase(type.Trim())));
                                    }
                                }
                            }
                        }
                        else
                        {
                            nodeStates.AddItem(NodeState.Running);
                        }
                    }
                    ListClusterNodes(nodeStates);
                }
                else
                {
                    if (cliParser.HasOption(HelpCmd))
                    {
                        PrintUsage(opts);
                        return(0);
                    }
                    else
                    {
                        syserr.WriteLine("Invalid Command Usage : ");
                        PrintUsage(opts);
                    }
                }
            }
            return(0);
        }
Example #31
0
        /// <summary>Parse command line options</summary>
        /// <param name="args">Parsed command line options</param>
        /// <returns>Whether the init was successful to run the client</returns>
        /// <exception cref="Org.Apache.Commons.Cli.ParseException"/>
        public virtual bool Init(string[] args)
        {
            CommandLine cliParser = new GnuParser().Parse(opts, args);

            if (args.Length == 0)
            {
                throw new ArgumentException("No args specified for client to initialize");
            }
            if (cliParser.HasOption("log_properties"))
            {
                string log4jPath = cliParser.GetOptionValue("log_properties");
                try
                {
                    Log4jPropertyHelper.UpdateLog4jConfiguration(typeof(Org.Apache.Hadoop.Yarn.Applications.Distributedshell.Client
                                                                        ), log4jPath);
                }
                catch (Exception e)
                {
                    Log.Warn("Can not set up custom log4j properties. " + e);
                }
            }
            if (cliParser.HasOption("help"))
            {
                PrintUsage();
                return(false);
            }
            if (cliParser.HasOption("debug"))
            {
                debugFlag = true;
            }
            if (cliParser.HasOption("keep_containers_across_application_attempts"))
            {
                Log.Info("keep_containers_across_application_attempts");
                keepContainers = true;
            }
            appName    = cliParser.GetOptionValue("appname", "DistributedShell");
            amPriority = System.Convert.ToInt32(cliParser.GetOptionValue("priority", "0"));
            amQueue    = cliParser.GetOptionValue("queue", "default");
            amMemory   = System.Convert.ToInt32(cliParser.GetOptionValue("master_memory", "10")
                                                );
            amVCores = System.Convert.ToInt32(cliParser.GetOptionValue("master_vcores", "1"));
            if (amMemory < 0)
            {
                throw new ArgumentException("Invalid memory specified for application master, exiting."
                                            + " Specified memory=" + amMemory);
            }
            if (amVCores < 0)
            {
                throw new ArgumentException("Invalid virtual cores specified for application master, exiting."
                                            + " Specified virtual cores=" + amVCores);
            }
            if (!cliParser.HasOption("jar"))
            {
                throw new ArgumentException("No jar file specified for application master");
            }
            appMasterJar = cliParser.GetOptionValue("jar");
            if (!cliParser.HasOption("shell_command") && !cliParser.HasOption("shell_script"))
            {
                throw new ArgumentException("No shell command or shell script specified to be executed by application master"
                                            );
            }
            else
            {
                if (cliParser.HasOption("shell_command") && cliParser.HasOption("shell_script"))
                {
                    throw new ArgumentException("Can not specify shell_command option " + "and shell_script option at the same time"
                                                );
                }
                else
                {
                    if (cliParser.HasOption("shell_command"))
                    {
                        shellCommand = cliParser.GetOptionValue("shell_command");
                    }
                    else
                    {
                        shellScriptPath = cliParser.GetOptionValue("shell_script");
                    }
                }
            }
            if (cliParser.HasOption("shell_args"))
            {
                shellArgs = cliParser.GetOptionValues("shell_args");
            }
            if (cliParser.HasOption("shell_env"))
            {
                string[] envs = cliParser.GetOptionValues("shell_env");
                foreach (string env in envs)
                {
                    env = env.Trim();
                    int index = env.IndexOf('=');
                    if (index == -1)
                    {
                        shellEnv[env] = string.Empty;
                        continue;
                    }
                    string key = Sharpen.Runtime.Substring(env, 0, index);
                    string val = string.Empty;
                    if (index < (env.Length - 1))
                    {
                        val = Sharpen.Runtime.Substring(env, index + 1);
                    }
                    shellEnv[key] = val;
                }
            }
            shellCmdPriority = System.Convert.ToInt32(cliParser.GetOptionValue("shell_cmd_priority"
                                                                               , "0"));
            containerMemory = System.Convert.ToInt32(cliParser.GetOptionValue("container_memory"
                                                                              , "10"));
            containerVirtualCores = System.Convert.ToInt32(cliParser.GetOptionValue("container_vcores"
                                                                                    , "1"));
            numContainers = System.Convert.ToInt32(cliParser.GetOptionValue("num_containers",
                                                                            "1"));
            if (containerMemory < 0 || containerVirtualCores < 0 || numContainers < 1)
            {
                throw new ArgumentException("Invalid no. of containers or container memory/vcores specified,"
                                            + " exiting." + " Specified containerMemory=" + containerMemory + ", containerVirtualCores="
                                            + containerVirtualCores + ", numContainer=" + numContainers);
            }
            nodeLabelExpression = cliParser.GetOptionValue("node_label_expression", null);
            clientTimeout       = System.Convert.ToInt32(cliParser.GetOptionValue("timeout", "600000"
                                                                                  ));
            attemptFailuresValidityInterval = long.Parse(cliParser.GetOptionValue("attempt_failures_validity_interval"
                                                                                  , "-1"));
            log4jPropFile = cliParser.GetOptionValue("log_properties", string.Empty);
            // Get timeline domain options
            if (cliParser.HasOption("domain"))
            {
                domainId       = cliParser.GetOptionValue("domain");
                toCreateDomain = cliParser.HasOption("create");
                if (cliParser.HasOption("view_acls"))
                {
                    viewACLs = cliParser.GetOptionValue("view_acls");
                }
                if (cliParser.HasOption("modify_acls"))
                {
                    modifyACLs = cliParser.GetOptionValue("modify_acls");
                }
            }
            return(true);
        }