Beispiel #1
0
PaintInfo * TreeFuncPtr::getPaintInfo( void )
//-------------------------------------------
{
    OptionManager * mgr = WBRWinBase::optManager();

    return new PaintInfo( mgr->getFunctionOpts().numCalls( _numRefs ) );
}
Beispiel #2
0
PaintInfo * TreeFuncNode::getPaintInfo( void )
//--------------------------------------------
{
    OptionManager * mgr = WBRWinBase::optManager();

    return new PaintInfo( mgr->getFunctionOpts().repeated( hasReference() ) );
}
Beispiel #3
0
bool BVHRefine::refine(const char* filename)
{
	OptionManager *opt = OptionManager::getSingletonPtr();
	unsigned int maxDepth = opt->getOptionAsInt("raytracing", "maxBSPTreeDepth", 100);
	char nodeNameO[MAX_PATH];
	char nodeNameD[MAX_PATH];
	sprintf(nodeNameO, "%s.node", filename);
	sprintf(nodeNameD, "%s.rfd", filename);
	fpo = fopen(nodeNameO, "rb");
	fpd = fopen(nodeNameD, "wb");

	BSPArrayTreeNode root;
	fseek(fpo, 0, SEEK_SET);
	fread(&root, sizeof(BSPArrayTreeNode), 1, fpo);

	float *bb_min_f = root.min.e;
	float *bb_max_f = root.max.e;

	int nbits = 16;

	pq = new PositionQuantizerNew();
	pq->SetMinMax(bb_min_f, bb_max_f);
	pq->SetPrecision(nbits);
	pq->SetupQuantizer();

	Vector3 min, max;
	refineRecursive(0, min, max);

	delete pq;

	fclose(fpo);
	fclose(fpd);
	return true;
}
Beispiel #4
0
void getOptions(
    OptionManager &om,
    int &argc,
    char **argv)
{
    static struct OptionRow optionTable[] =
    {
        {"repositoryPath", "", true,
            Option::STRING, 0, 0, "r", "Repository path"},
        {"parent", "", false,
            Option::STRING, 0, 0, "p", "Parent namespace (optional)."
                "Parent namespace will be modified to be shareable if"
                " it was not already shareable"},
        {"namespaceName", "", true,
            Option::STRING, 0, 0, "n", "Namespace name"},
        {"location", "", true,
            Option::STRING, 0, 0, "l", "Remote location"},
        {"shareable", "true", false,
            Option::STRING, 0, 0, "s", "Specifies whether the"
                " namespace can shareable or not"},
        {"updatesAllowed", "false", false,
            Option::STRING, 0, 0, "u", "Specifies whether the "
                "updates to the namespace are allowed or not"}
    };
    const Uint32 NUM_OPTIONS = sizeof(optionTable)/ sizeof(optionTable[0]);
    om.registerOptions(optionTable, NUM_OPTIONS);
    om.mergeCommandLine(argc, argv);
    om.checkRequiredOptions();
}
/** GetOptions function - This function defines the Options Table
    and sets up the options from that table using the option manager.
    const char* optionName;
    const char* defaultValue;
    int required;
    Option::Type type;
    char** domain;
    Uint32 domainSize;
    const char* commandLineOptionName;
    const char* optionHelpMessage;

*/
void GetOptions(
    OptionManager& om,
    int& argc,
    char** argv,
    const String& pegasusHome)
{
    static struct OptionRow optionsTable[] =
    // optionname defaultvalue rqd  type domain domainsize clname hlpmsg
    {
        {"active", "false", false, Option::BOOLEAN, 0, 0, "a",
            "If set allows test that modify the repository"},

        {"repeat", "1", false, Option::WHOLE_NUMBER, 0, 0, "r",
            "Specifies a Repeat Count Entire test repeated this many times"},

        {"namespace", "root/cimv2", false, Option::STRING, 0, 0, "-n",
            "specifies namespace to use for test"},

        {"version", "false", false, Option::BOOLEAN, 0, 0, "v",
            "Displays TestClient Version "},

        {"verbose", "false", false, Option::BOOLEAN, 0, 0, "verbose",
            "If set, outputs extra information "},

        {"help", "false", false, Option::BOOLEAN, 0, 0, "h",
            "Prints help message with command line options "},
        {"debug", "false", false, Option::BOOLEAN, 0, 0, "d",
            "Not Used "},
#ifdef PEGASUS_HAS_SSL
        {"ssl", "false", false, Option::BOOLEAN, 0, 0, "ssl",
            "use SSL"},
#endif
        {"local", "false", false, Option::BOOLEAN, 0, 0, "local",
            "Use local connection mechanism"},
        {"user", "", false, Option::STRING, 0, 0, "user",
            "Specifies user name"},

        {"password", "", false, Option::STRING, 0, 0, "password",
            "Specifies password"}

    };
    const Uint32 NUM_OPTIONS = sizeof(optionsTable) / sizeof(optionsTable[0]);

    om.registerOptions(optionsTable, NUM_OPTIONS);

#if defined (PEGASUS_OS_VMS)
    String configFile = "cimserver.conf";
#else
    String configFile = pegasusHome + "/cimserver.conf";
#endif

    cout << "Config file from " << configFile << endl;

    if (FileSystem::exists(configFile))
        om.mergeFile(configFile);

    om.mergeCommandLine(argc, argv);

    om.checkRequiredOptions();
}
Beispiel #6
0
void GetOptions(
    OptionManager& om,
    int& argc,
    char** argv,
    const String& testHome)
{
    static const char* outputFormats[] = { "xml", "mof", "txt"};
    static const Uint32 NUM_OUTPUTFORMATS = sizeof(outputFormats) /
                                            sizeof(outputFormats[0]);

    static struct OptionRow optionsTable[] =
        //optionname defaultvalue rqd  type domain domainsize clname hlpmsg
    {
    {"location", "localhost:5988", false, Option::STRING, 0, 0, "-n",
                                        "specifies system and port" },

    {"namespace", "root/cimv2", false, Option::STRING, 0, 0, "-n",
                                        "specifies namespace to use for operation" },

        //{"outputformats", "mof", false, Option::STRING, outputFormats,
        //                                 NUM_OUTPUTFORMATS, "o",
        //                                "Output in xml, mof, txt"},

        {"deepinheritance", "false", false, Option::BOOLEAN, 0, 0, "d",
                                        "If set does deep enum "},

        {"version", "false", false, Option::BOOLEAN, 0, 0, "v",
                                        "Displays software Version "},

        {"help", "false", false, Option::BOOLEAN, 0, 0, "h",
                            "Prints help message with command line options "},

        {"debug", "false", false, Option::BOOLEAN, 0, 0, "d",
                     "Not Used "},
    };
    const Uint32 NUM_OPTIONS = sizeof(optionsTable) / sizeof(optionsTable[0]);

    om.registerOptions(optionsTable, NUM_OPTIONS);

    //We want to make this code common to all of the commands

    String configFile = "/CLTest.conf";

    cout << "Config file from " << configFile << endl;

    if (FileSystem::exists(configFile))
             om.mergeFile(configFile);

    om.mergeCommandLine(argc, argv);

    om.checkRequiredOptions();

}
Beispiel #7
0
// ######################################################################
V4Lgrabber::V4Lgrabber(OptionManager& mgr, const std::string& descrName,
                       const std::string& tagName,
                       const ParamFlag flags) :
  FrameIstream(mgr, descrName, tagName),
  // NOTE that contrary to the common case, we may give (by default
  // value of 'flags') USE_MY_VAL here when we construct the
  // OModelParam objects; that means that we push our values into the
  // ModelManager as the new default values, rather than having our
  // param take its value from the ModelManager's default
  itsDevName(&OPT_FrameGrabberDevice, this, "/dev/video0", flags), // V4l device
  itsChannel(&OPT_FrameGrabberChannel, this, 1, flags),  // composite input
  itsDims(&OPT_FrameGrabberDims, this, Dims(320, 240), flags),
  itsGrabMode(&OPT_FrameGrabberMode, this, VIDFMT_RGB24, flags), // 24-bit rgb grabbing
  itsByteSwap(&OPT_FrameGrabberByteSwap, this, true, flags), // use byte-swapping
  itsBrightness(&OPT_FrameGrabberBrightness, this, 32768, flags | ALLOW_ONLINE_CHANGES),
  itsHue(&OPT_FrameGrabberHue, this, 32768, flags | ALLOW_ONLINE_CHANGES),
  itsColour(&OPT_FrameGrabberColour, this, 32768, flags | ALLOW_ONLINE_CHANGES),
  itsContrast(&OPT_FrameGrabberContrast, this, 32768, flags | ALLOW_ONLINE_CHANGES),
  itsWhiteness(&OPT_FrameGrabberWhiteness, this, 32768, flags | ALLOW_ONLINE_CHANGES),
  itsStreamingMode(&OPT_FrameGrabberStreaming, this),
  itsFd(-1),
  itsMmapBuf(NULL),
  itsReadBuf(),
  itsTotalBufSize(0),
  itsNumBufFrames(0),
  itsCurrentFrame(0),
  itsGrabbing(NULL),
  itsFrameTime(SimTime::ZERO()),
  itsListener(),
  itsStreamStarted(false)
{
  // request a bunch of camera aliases which work with V4L:
  mgr.requestOptionAlias(&OPT_ALIAScamBttv);
}
Beispiel #8
0
void QueryConfig::initialize()
//----------------------------
{
    int i;
    OptionManager * optMgr = WBRWinBase::optManager();

    setSystemFont( FALSE );
    rescale();
    move( frame().r );
    centre();

    _symText =      new WText( this, _symTextR.r, _symTextR.t );
    _symName =      new WCommandList( this, _symNameR.r, NULL );

    _symText->show();
    _symName->show();

    _matchCase =    new WCheckBox( this, _matchCaseR.r, _matchCaseR.t );
    _wholeWord =    new WCheckBox( this, _anchoredR.r, _anchoredR.t );
    _useRX =        new WCheckBox( this, _useRXR.r, _useRXR.t );
    _cfgRegexp =    new WPushButton( this, _cfgRegexpR.r, _cfgRegexpR.t );

    _matchCase->show();
    _wholeWord->show();
    _useRX->show();

    _matchCase->setCheck( !optMgr->getIgnoreCase() );
    _wholeWord->setCheck( optMgr->getWholeWord() );
    _useRX->setCheck( optMgr->getUseRX() );
    _useRX->onClick( this, (cbw) &QueryConfig::useRXClicked );
    _wholeWord->enable( !optMgr->getUseRX() );

    _ok =           new WDefPushButton( this, _searchR.r, _searchR.t );
    _cancel =       new WPushButton( this, _cancelR.r, _cancelR.t );
    _filters =      new WPushButton( this, _filtersR.r, _filtersR.t );
    _help =         new WPushButton( this, _helpR.r, _helpR.t );

    _ok->show();
    _cancel->show();
    _filters->show();
    _cfgRegexp->show();
    _help->show();

    _cfgRegexp->enable( optMgr->getUseRX() );

    _ok->onClick(           this, (cbw) &QueryConfig::okButton );
    _cancel->onClick(       this, (cbw) &WDialog::cancelButton );
    _filters->onClick(      this, (cbw) &QueryConfig::filtersButton );
    _cfgRegexp->onClick(    this, (cbw) &QueryConfig::cfgRXButton );
    _help->onClick(         this, (cbw) &QueryConfig::helpButton );

    for( i = 0; i < _searchStrings->count(); i +=1 ) {
        _symName->insertString( ((WString *)(*_searchStrings)[ i ] )->gets(),
                                0 );
    }

    _symName->setFocus();

    show();
}
Beispiel #9
0
/**
    EnumerateClassRelatedInfo
    This method enumerates classes and instances (by way of subrotine)  
*/
static void enumerateClassRelatedInfo(
    TestModelWalkStressClient &tmsc,
    CIMClient* client,
    OptionManager &om,
    Array<CIMNamespaceName> nameSpacesArray,
    pid_t clientPid,
    String& clientLog,
    String &clientId,
    int status,
    String &pidFile)
{
    Array<CIMName> classNames;
    String tmpClassName;

    om.lookupValue("classname",tmpClassName);
    if (tmpClassName != String::EMPTY)
    {
        classNames.append(CIMName(tmpClassName));
        enumerateInstanceRelatedInfo(tmsc, client, classNames,
            *nameSpacesArray.getData(), clientPid, clientLog, clientId,
            status, pidFile);
    }
    else
    {
        Boolean deepInheritance = true;
        CIMName className;
        for (Uint32 i=0; i < nameSpacesArray.size();i++)
        {
            classNames = client->enumerateClassNames(nameSpacesArray[i],
                className, deepInheritance);

            if (status != CLIENT_PASS)
            {
                status = CLIENT_PASS;
                tmsc.logInfo(clientId, clientPid, status, pidFile);
            }
            enumerateInstanceRelatedInfo(tmsc, client, classNames,
                nameSpacesArray[i], clientPid, clientLog, clientId, status,
                pidFile );
        }
    }
      if (verboseTest)
    {
        errorInfo.clear();
        errorInfo.append("+++++ Successfully Enumerated classes ");
        errorInfo.append("in Namespaces +++++");
        tmsc.errorLog(clientPid, clientLog, errorInfo);
        errorInfo.clear();
    }
}
Beispiel #10
0
BOOL CMDToggle::Execute(const std::string &verb, Player* mobile,std::vector<std::string> &args,int subcmd)
{
    World* world  = World::GetPtr();
    OptionManager* omanager = world->GetOptionManager();
    OptionMeta* gopt = nullptr;
    std::vector<Option*> *poptions = nullptr;
    std::vector<OptionMeta*> goptions;
    std::vector<std::string> cols;
    std::vector<std::string> headers;

//if no args were given, print out a list of options:
    if (!args.size())
        {
            headers.push_back("option");
            headers.push_back("value");

            poptions=mobile->GetOptions();
            for (auto pit: *poptions)
                {
                    if (pit->GetMeta()->CanToggle())
                        {
                            cols.push_back(pit->GetMeta()->GetName());
                            cols.push_back(pit->GetValue().GetInt()==0?"off: ":"on ");
                        }
                }

            omanager->ListOptions(&goptions);
            for (OptionMeta* opt: goptions)
                {
                    if (mobile->OptionExists(opt->GetName()))
                        {
                            continue;
                        }
                    if (opt->CanToggle())
                        {
                            cols.push_back(opt->GetName());
                            cols.push_back(opt->GetValue().GetInt()==0?"off: ":"on ");
                        }
                }

            mobile->Message(MSG_LIST, Columnize(&cols, 2, &headers));
            mobile->Message(MSG_INFO, "Note: You can use toggle help <option> to get more help on a specific option.");
            return true;
        }

//see if they want help on a specific option.
    if (args[0] == "help" && args.size() == 2)
        {
            gopt = omanager->GetOption(args[1]);
            if (!gopt)
                {
                    mobile->Message(MSG_ERROR, "That option does not exist.");
                    return false;
                }

            mobile->Message(MSG_INFO, gopt->GetHelp());
            return true;
        }

    mobile->ToggleOption(args[0]);
    return true;
}
/**
    MAIN
*/
int main(int argc, char** argv)
{
    OptionManager om;
    TestWrapperStressClient wc;
    pid_t clientPid = getpid();
    Uint32 validArg = 0;
    Boolean verboseTest;

    //
    // Varriables needed for loging and status checking.
    //
    String clientId;
    String pidFile;
    String clientLog, stopClient;
    char pid_str[15];
    int status = CLIENT_UNKNOWN;

    //
    // Number of times the client command succeeded.
    //
    Uint32 successCount = 0;

    //
    // Number of iterations after which logErrorPercentage() is called.
    //
    Uint32 iteration = 0;

    //
    // Total number of times the client command was executed.
    //
    Uint32 totalCount = 0;

    //
    // Variables needed for Command operation.
    //
    String command;

    String options;
    String help;

    try
    {
        struct OptionRow *newOptionsTable = 0;
        Uint32 newOptionsCount;

        struct OptionRow cOptionTable[] =
        {
            {"clientname", "", true, Option::STRING, 0, 0, "clientname",
                "Client name" },

            {"options", "", true, Option::STRING, 0, 0, "options",
                "Corresponding Client program's options" }
        };

        Uint32 cOptionCount = sizeof(cOptionTable) / sizeof(cOptionTable[0]);
        newOptionsCount = cOptionCount;

        try
        {
            //
            // Generate new option table for this client using OptionManager
            //
            newOptionsTable = wc.generateClientOptions(
                                  cOptionTable,
                                  cOptionCount,
                                  newOptionsCount);
            validArg = wc.GetOptions(
                           om,
                           argc,
                           argv,
                           newOptionsTable,
                           newOptionsCount);
        }
        catch (Exception& e)
        {
            cerr << argv[0] << ": " << e.getMessage() << endl;
            exit(1);
        }
        catch (...)
        {
            cerr << argv[0] << ": Error in Options operations "<< endl;
            exit(1);
        }

        verboseTest = om.isTrue("verbose");

        om.lookupValue("clientid", clientId);

        om.lookupValue("pidfile", pidFile);

        om.lookupValue("clientlog", clientLog);

        om.lookupValue("clientname", command);

        om.lookupValue("options", options);

        om.lookupValue("help", help);
    } /** end of option Try block. */
    catch (Exception& e)
    {
        cerr << argv[0] << ": " << e.getMessage() <<endl;
        exit(1);
    }
    catch (...)
    {
        cerr << argv[0] << ": Unknown Error gathering options "
             << "in Wrapper Client " << endl;
        exit(1);
    }

    /** Checking whether the user asked for HELP Info...
    if (om.valueEquals("help", "true"))
    {
        String header = "Usage ";
        header.append(argv[0]);
        header.append(" -parameters -clientName [clientName]
        header.append(" -options [options] -clientid [clientId] ");
        header.append(" -pidfile [pidFile] -clientlog [clientLog]");
        String trailer = "Assumes localhost:5988 if host not specified";
        trailer.append("\nHost may be of the form name or name:port");
        trailer.append("\nPort 5988 assumed if port number missing.");
        om.printOptionsHelpTxt(header, trailer);
        exit(0);
    }
    */

    try
    {
        if (options.getCString())
        {
            command.append(" " + options);
        }
        if (verboseTest)
        {
            errorInfo.append("client command :  ");
            errorInfo.append(command);
            wc.errorLog(clientPid, clientLog, errorInfo);
            errorInfo.clear();
        }

        //
        // Signal Handling - SIGINT.
        //
        signal(SIGINT, endTest);

        //
        // Timer Start.
        //
        wc.startTime();

        wc.logInfo(clientId, clientPid, status, pidFile);
        sprintf(pid_str, "%d", clientPid);

        stopClient = String::EMPTY;
        stopClient.append(FileSystem::extractFilePath(pidFile));
        stopClient.append("STOP_");
        stopClient.append(pid_str);

        //
        // This loop executes till the client gets stop signal from
        // controller.
        //
        while (!quit)
        {
            if (FileSystem::exists(stopClient))
            {
                if (verboseTest)
                {
                    String mes("Ending client. ");
                    wc.errorLog(clientPid, clientLog, mes);
                }
                break;
            }

                if (!verboseTest)
                {
#ifdef PEGASUS_OS_TYPE_WINDOWS
                    freopen("nul","w",stdout);
#else
                    FILE * file = freopen("/dev/null","w",stdout);
                    if (0 == file)
                    {
                        // ignore possible error, not having stdout redirected
                        // to /dev/null doesn't hurt the test
                        continue;
                    }
#endif
                }

            int i = system(command.getCString());

            iteration++;
            totalCount++;
            switch (i)
            {
                case 0:
                    if (status != CLIENT_PASS)
                    {
                        status = CLIENT_PASS;
                        wc.logInfo(clientId, clientPid, status, pidFile);
                    }
                    successCount++;
                    break;

                case 1:
                    status = CLIENT_UNKNOWN;
                    wc.logInfo(clientId, clientPid, status, pidFile);
                    break;

                default:
                    status = CLIENT_FAIL;
                    wc.logInfo(clientId, clientPid, status, pidFile);
                    break;
            }

            nextCheck = wc.checkTime();
            if (nextCheck)
            {
                wc.logInfo(clientId, clientPid, status, pidFile);
                nextCheck = false;
            }

            //
            // If verbose is set, log success percentage for every 100
            // iterations.  If verbose is not set, log success percentage
            // for every 1000 iterations.
            //
            if (verboseTest)
            {
                if (iteration == 100)
                {
                    wc.logErrorPercentage(
                        successCount,
                        totalCount,
                        clientPid,
                        clientLog,
                        thisClient);
                    iteration = 0;
                }
            }
            else
            {
                if (iteration == 1000)
                {
                    wc.logErrorPercentage(
                        successCount,
                        totalCount,
                        clientPid,
                        clientLog,
                        thisClient);
                    iteration = 0;
                }
            }
        } /** end of while(!quit). */
    } /** end of command execution try block. */
    catch (Exception &exp)
    {
        String expStr("Exception in WrapperClient causing it to exit: ");
        expStr.append(exp.getMessage());
        wc.errorLog(clientPid, clientLog, expStr);

        if (verboseTest)
        {
            cerr << expStr.getCString() << endl;
        }
    }
    catch (...)
    {
        String expStr("General Exception in WrapperClient causing it to exit");
        wc.errorLog(clientPid, clientLog, expStr);

        if (verboseTest)
        {
            cerr << expStr.getCString() << endl;
        }
    }

//
// second delay before shutdown.
//
#ifndef PEGASUS_OS_TYPE_WINDOWS
    sleep(1);
#else
    Sleep(1000);
#endif

    if(FileSystem::exists(stopClient))
    {
        //
        // Remove STOP file here.
        //
        FileSystem::removeFile(stopClient);
    }
    if (verboseTest)
    {
        errorInfo.append(
            "++++ TestWrapperStressClient Terminated Normally +++++");
        wc.errorLog(clientPid, clientLog, errorInfo);
        errorInfo.clear();
    }
    return 0;
}
Beispiel #12
0
int main(int argc, char* argv[])
{
    try
    {
        OptionManager om;
        try
        {
            getOptions(om, argc, argv);
        }
        catch(Exception &e)
        {
            cerr << argv[0] << ":" << e.getMessage() << endl;
            String header = "Usage ";
            String trailer ="";
            om.printOptionsHelpTxt(header, trailer);
            exit(1);
        }
        String parent;
        String repositoryPath;
        String namespaceName;
        String location;
        String shareable;
        String updatesAllowed;

        om.lookupValue("parent", parent);
        om.lookupValue("repositoryPath", repositoryPath);
        om.lookupValue("namespaceName", namespaceName);
        om.lookupValue("location", location);
        om.lookupValue("shareable", shareable);
        om.lookupValue("updatesAllowed", updatesAllowed);

        CIMRepository repository(repositoryPath);
        CIMRepository::NameSpaceAttributes attributes;
        if (parent.size())
        {
            // Check if parent namespace is shareable else modify to be
            // shareable.
            repository.getNameSpaceAttributes(parent, attributes);
            for (CIMRepository::NameSpaceAttributes::Iterator
                i = attributes.start(); i; i++)
            {
                String key = i.key();
                String value = i.value();
                if (String::equalNoCase(key, "shareable"))
                {
                    if (String::equalNoCase(value, "false"))
                    {
                        CIMRepository::NameSpaceAttributes attr;
                        attr.insert("shareable", "true");
                        repository.modifyNameSpace(
                            parent,
                            attr);
                        break;
                    }
                }
            }
            attributes.clear();
            attributes.insert("parent", parent);
        }
        attributes.insert("remoteInfo", location);
        attributes.insert("shareable", shareable);
        attributes.insert("updatesAllowed", updatesAllowed);
        repository.createNameSpace(namespaceName, attributes);
    }
    catch(Exception &e)
    {
        cerr << argv[0] << ":" << e.getMessage() << endl;
        exit(1);
    }
    catch(...)
    {
        cerr << argv[0] << ":" << "Unknown error" << endl;
        exit(1);
    }
    cout << "Namespace created successfully." << endl;

    return 0;
}
Beispiel #13
0
int main(int argc, char** argv)
{

    // Get options (from command line and from configuration file); this
    // removes corresponding options and their arguments fromt he command
    // line.

    // Get options (from command line and from configuration file); this
    // removes corresponding options and their arguments fromt he command
    // line.

    OptionManager om;

    try
    {
         String testHome = ".";
                 GetOptions(om, argc, argv, testHome);
         // om.print();
    }
    catch (Exception& e)
    {
         cerr << argv[0] << ": " << e.getMessage() << endl;
         exit(1);
    }


    // Check to see if user asked for help (-h otpion):
    if (om.valueEquals("verbose", "true"))
    {
                printHelpMsg(argv[0], usage, extra, om);
        exit(0);
    }

    // Establish the namespace from the input parameters
    String nameSpace;
    if(om.lookupValue("namespace", nameSpace))
    {
       cout << "Namespace = " << nameSpace << endl;

    }

    Boolean verboseTest = (om.valueEquals("verbose", "true")) ? true :false;
    /*
    Boolean activeTest = false;
    if (om.valueEquals("active", "true"))
         activeTest = true;
    */
    // Now develop the target instname from the arglist
    // For this one, at least one arguement is required
    // Not sure if this is true.
    // Think we should be able to get by with no argument.
    if (om.valueEquals("help", "true"))
    {
        String header = "Usage ";
        String trailer = "";
        om.printOptionsHelpTxt(header, trailer);
        exit(0);
    }

    String location =   "localhost:5988";
    if(om.lookupValue("location", location))
    {
       cout << "Location = " << location << endl;

    }

    // here we assume class name = null if none specified.
    String className = "";
    if (argc > 1)
    {
    className = argv[1];
    }

    CIMClient client;

    try
    {
        client.connect(location, String::EMPTY, String::EMPTY);
    }

    catch(Exception &e)
    {
      cerr << "Internal Error:" << e.getMessage() << endl;
    }


    Array<CIMObjectPath> instanceNames =
        client.enumerateInstanceNames(nameSpace, className);
    try
    {

        //simply output the list one per line for the moment.
    for (Uint32 i = 0; i < instanceNames.size(); i++)
        cout << instanceNames[i] << endl;
    }
    catch(Exception& e)
    {
    PEGASUS_STD(cerr) << "Error: " << e.getMessage() << PEGASUS_STD(endl);
    exit(1);
    }

    PEGASUS_STD(cout) << "+++++ passed all tests" << PEGASUS_STD(endl);

    return 0;
}
int main(int argc, char** argv)
{
    const char* arg0 = System::findBaseName(argv[0]);

#ifdef PEGASUS_OS_ZOS
    // for z/OS set stdout and stderr to EBCDIC
    setEBCDICEncoding(STDOUT_FILENO);
    setEBCDICEncoding(STDERR_FILENO);
#endif
 
#ifdef PEGASUS_OS_PASE
    // Allow user group name larger than 8 chars in PASE environemnt
    setenv("PASE_USRGRP_LIMITED","N",1);
#endif
    // If no arguments, simply print usage message and terminate.
    MessageLoader::_useProcessLocale = true;

    if (argc == 1)
    {
        showUsage();
        exit(0);
    }

    //****** Show the args diagnostic display
    if (strcmp(argv[1],"displayargs") == 0)
    {
        cout << "argc = " << argc << endl;
        for (int i = 0; i < argc; i++)
            cout << "argv[" << i << "] = " << argv[i] << endl;
    }

    // Get options (from command line and from configuration file); this
    // removes corresponding options and their arguments from the command
    // line.
    OptionManager om;
    Options opts;
    try
    {
        // assume that the config file is local to directory where called.
        String testHome = ".";
        om.setMessagePath("pegasus/pegasusCLI");
        GetOptions(om, argc, argv, testHome);

        // Initialize all of the function input parameters.
        opts.location =  String::EMPTY;
#ifdef PEGASUS_HAS_SSL
        opts.ssl = false;
        opts.clientCert = String::EMPTY;
        opts.clientKey = String::EMPTY;
#endif
        opts.nameSpace = "root/cimv2";
        opts.cimCmd = "unknown";
        opts.className = CIMName();
        opts.objectName = "unknown";

        opts.isXmlOutput = false;
        opts.outputFormatType = OUTPUT_MOF;
        opts.user = String::EMPTY;
        opts.password = String::EMPTY;
        opts.verboseTest = false;

        opts.localOnly = true;
        opts.deepInheritance = false;
        opts.includeQualifiers = true;
        opts.includeClassOrigin = false;
        opts.assocClassName = String::EMPTY;
        opts.assocClass = CIMName();
        opts.resultClassName = String::EMPTY;
        opts.resultClass = CIMName();
        opts.role = String::EMPTY;
        opts.resultRole = String::EMPTY;
        opts.propertyListText = String::EMPTY;
        opts.propertyList.clear();
        opts.propertyName = String::EMPTY;
        opts.methodName = CIMName("unknown");
        opts.delay = 0;
        opts.trace = 0;
        opts.count= 97832;
        opts.repeat = 0;
        opts.time = false;
        opts.termCondition = 0;
        opts.debug = false;
        opts.queryLanguage = "WQL";

        // move any other input parameters left to the extraParams List
        CheckCommonOptionValues(om, argv, opts);

        /* note that this is in error since it assumes a fixed
           number of parameters will be used for all of the commands
           It needs to be expanded to allow for a variable minimum
           number of commands before it picks up any extras
        */
        if (argc > 2)
        {
            for (int i = 2 ; i < argc ; i++ )
                opts.extraParams.append(argv[i]);
        }
    }

    catch(CIMException& e)
    {
        cerr << argv[0] << " Caught CIMException during init: "
             << "\n" << e.getMessage()
             << endl;
        exit(1);
    }

    catch (Exception& e)
    {
        cerr << argv[0] << ": " << e.getMessage() << endl;
        exit(1);
    }
    catch(...)
    {
        cerr << argv[0] << " Caught General Exception During Init:" << endl;
        exit(1);
    }

    // if there is still an arg1, assume it is the command name.
    if (argc > 1)
    {
        opts.cimCmd = argv[1];
    }
    else
    {
        cout << " Command name must be first parameter or --c parameter."
            << " \n  ex. " << argv[0] <<  " enumerateclasses\n"
            << "Enter " << argv[0] << " -h for help."
            << endl;
        exit(1);
    }

    // if the trace option was set initialize the trace function.
    if (opts.trace != 0)
    {
        const char* tmpDir = getenv ("PEGASUS_TMP");
            if (tmpDir == NULL)
            {
                tmpDir = ".";
            }
            String traceFile (tmpDir);
            traceFile.append("/cliTrace.trc");
            Tracer::setTraceFile (traceFile.getCString());
            Tracer::setTraceComponents("ALL");
            Tracer::setTraceLevel(opts.trace);
    }

    // Find the command and save index in cmdIndex
    Uint32 cmdIndex = 0;
    
    if (opts.verboseTest && opts.debug)
        cout << "TEST Command = " << opts.cimCmd << endl;

    // Find the command or the short cut name
    for( ; cmdIndex < NUM_COMMANDS; cmdIndex++ )
    {
        if ((String::equalNoCase(opts.cimCmd, 
                CommandTable[cmdIndex].CommandName)) 
                ||
                (opts.cimCmd == CommandTable[cmdIndex].ShortCut))
            // Break if found
                    break;
    }

    Stopwatch totalElapsedExecutionTime;

    totalElapsedExecutionTime.start();

    // Now try to open the connection to the cim server
    CIMClient client;
    try
    {
        if (CommandTable[cmdIndex].ID_Command != ID_ShowOptions)
        {
            String host;
            HostLocator addr;
            if (opts.location != String::EMPTY)
            { 
                addr.setHostLocator(opts.location);
                if (!addr.isValid())
                {
                    throw InvalidLocatorException(opts.location);
                }
                host = addr.getHost();
            } 

            Uint32 portNumber = System::lookupPort( WBEM_HTTP_SERVICE_NAME,
                              WBEM_DEFAULT_HTTP_PORT );

            // Set up SSL port and flag for verbose display
            // if SSL included in build
            String useSSL;
#ifdef PEGASUS_HAS_SSL
            if (opts.ssl)
            {
                portNumber = System::lookupPort( WBEM_HTTPS_SERVICE_NAME,
                              WBEM_DEFAULT_HTTPS_PORT );
            }
            useSSL = " ssl=";
            useSSL.append((opts.ssl)? "true" : "false");
#endif

            if (host != String::EMPTY && addr.isPortSpecified())
            {
                portNumber = addr.getPort();
            }

            //check whether we should use connect() or connectLocal()
            //an empty location option indicates to use connectLocal()
            if (String::equal(host, String::EMPTY))
            {
                if (opts.verboseTest)
                {
                    cout << "Connect with connectLocal" << endl;
                }
                client.connectLocal();

            }
            else
            {
                if (opts.verboseTest)
                {
                    cout << "Connect to " << host
                        << " port=" << portNumber
                        << useSSL
                         << " for User="******"SSL options " 
                                << "Cert = " << opts.clientCert
                                << "clientKey = "  << opts.clientKey << endl;
                        }
                        client.connect(host,
                                       portNumber,
                                       SSLContext("", 
                                           opts.clientCert, 
                                           opts.clientKey,
                                           NULL, "ssl.rnd"),
                                       opts.user,
                                       opts.password);
                    } else
                    {
                        client.connect(host,
                                       portNumber,
                                       SSLContext("", NULL, "ssl.rnd"),
                                       opts.user,
                                       opts.password);
                    }
                } else //connect over HTTP
                {
                    client.connect(host, portNumber, opts.user, opts.password);
                }
#else
                client.connect(host, portNumber, opts.user, opts.password);
#endif
            }
        }
    }    
    catch(Exception &e)
    {
        cerr << "Pegasus Exception: " << e.getMessage() <<
              " Trying to connect to " << opts.location << endl;
        exit(1);
    }

    // Register for Client statistics.
    ClientStatistics statistics = ClientStatistics();
    client.registerClientOpPerformanceDataHandler(statistics);

    if (opts.delay != 0)
    {
        // This was a test because of some delay caused problems.
        Threads::sleep(opts.delay * 1000);
    }

    // If the timeout is not zero, set the timeout for this connection.
    if (opts.connectionTimeout != 0)
    {
        client.setTimeout(opts.connectionTimeout * 1000);
    }

    // Save the total connect time.
    double totalConnectTime = opts.elapsedTime.getElapsed();

    double totalTime = 0;
    Uint32 repeatCount = opts.repeat;
    double maxTime = 0;
    double minTime = 10000000;

    Uint64 serverTotalTime = 0;
    Uint64 maxServerTime = 0;
    Uint64 minServerTime = 10000000;

    Uint64 rtTotalTime = 0;
    Uint64 maxRtTime = 0;
    Uint64 minRtTime = 10000000;

    // Process the input command within a try block.
    try
    {
        // Loop to repeat the command a number of times.
        do
        {
            // or exit with error through default of case logic
            switch(CommandTable[cmdIndex].ID_Command)
                {
                case ID_EnumerateInstanceNames :
                    if (!_getClassNameInput(argc, argv, opts, true))
                        exit(1);
                    enumerateInstanceNames(client, opts);
                    break;

                case ID_EnumerateAllInstanceNames :
                    if (!_getClassNameInput(argc, argv, opts, false))
                        exit(1);
                    enumerateAllInstanceNames(client, opts);
                    break;

                case ID_EnumerateInstances :
                    if (!_getClassNameInput(argc, argv, opts, true))
                        exit(1);
                    enumerateInstances(client, opts);
                    break;
                case ID_GetInstance :
                    if (!_getObjectNameInput(argc, argv, opts, true))
                        exit(1);
                    getInstance(client, opts);
                    break;

                case ID_EnumerateClassNames :
                    if (!_getClassNameInput(argc, argv, opts, false))
                        exit(1);
                    enumerateClassNames(client, opts);
                    break;

                case ID_EnumerateClasses :
                    if (!_getClassNameInput(argc, argv, opts, false))
                        exit(1);
                    enumerateClasses(client, opts);
                    break;

                case ID_GetClass :
                    if (!_getClassNameInput(argc, argv, opts, true))
                        exit(1);
                    getClass(client, opts);
                    break;

                case ID_CreateInstance :
                    if (!_getClassNameInput(argc, argv, opts, true))
                        exit(1);
                    createInstance(client, opts);
                    break;

                case ID_DeleteInstance :
                    if (!_getObjectNameInput(argc, argv, opts, true))
                        exit(1);
                    deleteInstance(client, opts);
                    break;

                case ID_CreateClass :
                    cerr << "CreateClass not implemented" << endl;
                    break;

                case ID_DeleteClass :
                    if (!_getClassNameInput(argc, argv, opts, true))
                        exit(1);
                    deleteClass(client, opts);
                    break;

                case ID_GetProperty :
                    if (argc != 4)
                    {
                        cout << "Usage: " << arg0 <<
                            " getproperty <instancename> <propertyname>" << 
                            endl;
                        exit(1);
                    }

                    opts.instanceName = argv[2];
                    opts.inputObjectName = argv[2];
                    opts.propertyName = argv[3];

                    getProperty(client, opts);
                    break;

                case ID_SetProperty :
                    if (argc != 5)
                        cout <<"Usage: " << arg0 << 
                          " setproperty instancename propertyname value "
                           << endl;
                    setProperty(client, opts);
                    break;

                case ID_EnumerateQualifiers :
                    enumerateQualifiers(client, opts);
                    break;

                case ID_SetQualifier :
                    cerr << "SetQualifer not implemented" << endl;
                        exit(1);
                    break;

                case ID_GetQualifier :
                    if (!_getQualifierNameInput(argc, argv, opts))
                        exit(1);
                    getQualifier(client, opts);
                    break;

                case ID_DeleteQualifier :
                    if (!_getQualifierNameInput(argc, argv, opts))
                        exit(1);
                    deleteQualifier(client, opts);
                    break;

                /* Reference params are
                    [IN] <objectName> ObjectName,
                    [IN,OPTIONAL,NULL] <className> ResultClass = NULL,
                    [IN,OPTIONAL,NULL] string Role = NULL,
                    [IN,OPTIONAL] boolean IncludeQualifiers = false,
                    [IN,OPTIONAL] boolean IncludeClassOrigin = false,
                    [IN,OPTIONAL,NULL] string PropertyList [] = NULL
                */
                case ID_References  :
                    if (!_getObjectNameInput(argc, argv, opts, true))
                        exit(1);
                    references(client, opts);
                    break;

                case ID_ReferenceNames :
                    if (!_getObjectNameInput(argc, argv, opts, true))
                        exit(1);
                    referenceNames(client, opts);
                    break;

                case ID_Associators :
                    if (!_getObjectNameInput(argc, argv, opts, true))
                        exit(1);
                    associators(client, opts);
                    break;

                case ID_AssociatorNames :
                    if (!_getObjectNameInput(argc, argv, opts, true))
                        exit(1);
                    associatorNames(client,opts);
                    break;

                case ID_EnumerateNamespaces :
                    // Note that the following constants are fixed here.  We
                    // should be getting them from the environment to assure
                    // that others know that we are using them.
                    opts.className = CIMName("CIM_Namespace");
                    if (argc > 2)
                    {
                        opts.nameSpace = argv[2];
                        opts.inputObjectName = argv[2];
                    }
                    else
                        // set nameSpace to interop namespace name
                        opts.nameSpace = 
                            PEGASUS_NAMESPACENAME_INTEROP.getString();

                    enumerateNamespaces_Namespace(client,opts);
                    break;

                    /*
                        CIMValue invokeMethod(
                            const CIMNamespaceName& nameSpace,
                            const CIMObjectPath& instanceName,
                            const CIMName& methodName,
                            const Array<CIMParamValue>& inParameters,

                    Array<CIMParamValue>& outParameters
                    */
                case ID_InvokeMethod :
                    if (argc < 4)
                    {
                        cout << "Usage: InvokeMethod requires that object and"
                            " method names be specified.\n"
                            "Input parameters are optional and can be"
                            " specified with the -ip option or as"
                            " additional parameters to this call. "
                            "Enter each input parameter as name=value"
                            " (no spaces around equal sign)."
                            << endl;
                        exit(1);
                    }
                    opts.objectName = argv[2];
                    opts.inputObjectName = argv[2];
                    opts.methodName = CIMName(argv[3]);

                    // If there are any extra arguments they must be parameters
                    // These parameters  can be used in addtion to parameters
                    // ifrom the -ip option setting. Parameters found here must
                    // be key=value pairs or they will generate an exception.
                    if (argc > 4)
                    {
                        // get input params from command line
                        for (Sint32 i = 4 ; i < argc; i++)
                        {
                            CIMParamValue pv;
                            String s = argv[i];
                            pv = _createMethodParamValue(s, opts);
                            opts.inParams.append(pv);
                        }
                    }
                    invokeMethod(client, opts);
                    break;

                case ID_ShowOptions :
                    showUsage();
                    break;

                case ID_ExecQuery:
                    opts.query = argv[2];
                    if (argc==4)
                        opts.queryLanguage = argv[3];
                    executeQuery(client, opts);
                    break;

                case ID_StatisticsOn:
                    setObjectManagerStatistics(client, true);
                    break;

                case ID_StatisticsOff:
                    setObjectManagerStatistics(client, false);
                    break;

                //case ID_Unknown :
                default:
                    cout << "Invalid Command. Command name must be first parm"
                            " or --c parameter."
                        << " \n  ex. " << arg0 << " enumerateclasses\n"
                        << "Enter " << argv[0] << " -h for help."
                        << endl;
                    exit(1);
                    break;
            }
            if (opts.repeat > 0)
            {
                if (opts.verboseTest)
                {
                    cout << "Repetitition " << opts.repeat << endl;
                }
                opts.repeat--;
                if (opts.time)
                {
                    totalTime += opts.saveElapsedTime;
                    maxTime = LOCAL_MAX(maxTime, opts.saveElapsedTime);
                    minTime = LOCAL_MIN(minTime, opts.saveElapsedTime);
                    rtTotalTime += (returnedPerformanceData.roundTripTime);
                    maxRtTime = LOCAL_MAX(maxRtTime,
                            returnedPerformanceData.roundTripTime);
                    minRtTime = LOCAL_MIN(minRtTime,
                            returnedPerformanceData.roundTripTime);

                    if (returnedPerformanceData.serverTimeKnown)
                    {
                        serverTotalTime += (returnedPerformanceData.serverTime);
                        maxServerTime = LOCAL_MAX(maxServerTime,
                                returnedPerformanceData.serverTime);
                        minServerTime = LOCAL_MIN(minServerTime,
                                returnedPerformanceData.serverTime);
                    }
                }
            }
        } while (opts.repeat > 0  );

        if (opts.time)
        {
            if (repeatCount == 0)
            {
                cout << CommandTable[cmdIndex].CommandName
                    << " "
                    << opts.inputObjectName
                    << " Time= "
                    << opts.saveElapsedTime
                    << " Sec "
                    << " SvrTime= "
                    << CIMValue(returnedPerformanceData.serverTime).toString()
                    << " us "
                    << " RtTime= "
                    << CIMValue(returnedPerformanceData.roundTripTime).
                           toString()
                    << " us "
                    << "Req size= "
                    << CIMValue(returnedPerformanceData.requestSize).toString()
                    << " b Resp size= "
                    << CIMValue(returnedPerformanceData.responseSize).toString()
                    << " b"
                    << endl;
            }
            else
            {
                cout << CommandTable[cmdIndex].CommandName
                    << " "
                    << opts.inputObjectName
                    << " Total Time "
                    << totalTime
                    << " for "
                    << repeatCount
                    << " ops. Avg= "
                    << (totalTime * 1000000)/repeatCount
                    << " us min= "
                    << minTime * 1000000
                    << " us max= "
                    << (maxTime * 1000000) 
                    << " us SvrTime avg= "
                    << CIMValue(serverTotalTime/repeatCount).toString()
                    << " us SvrTime min= "
                    << CIMValue(minServerTime).toString()
                    << " us SvrTime max= "
                    << CIMValue(maxServerTime).toString()
                    << " us"
                    << " RtTime avg= "
                    << CIMValue(rtTotalTime/repeatCount).toString()
                    << " us RtTime min= "
                    << CIMValue(minRtTime).toString()
                    << " us RtTime max= "
                    << CIMValue(maxRtTime).toString()
                    << " us"
                    << endl;
            }
        }
    }
    catch(CIMException& e)
    {
        cerr << argv[0] << " CIMException: "<<" Cmd= " << opts.cimCmd
            << " Object= " << opts.inputObjectName
             << "\n" << e.getMessage()
             << endl;
        opts.termCondition = 1;
    }
    catch(Exception& e)
    {
        PEGASUS_STD(cerr) << argv[0] << " Pegasus Exception: " << e.getMessage()
                <<  ". Cmd = " << opts.cimCmd 
                << " Object = " << opts.inputObjectName
                << PEGASUS_STD(endl);
            opts.termCondition = 1;
    }
    catch(...)
    {
        cerr << argv[0] << " Caught General Exception:" << endl;
        opts.termCondition = 1;
    }

    totalElapsedExecutionTime.stop();

    if (opts.time)
    {
        // if abnormal term, dump all times
        if (opts.termCondition == 1)
        {
            cout << "Exception" << endl;
            cout << "Prev Time " << opts.saveElapsedTime << " Sec" << endl;
            opts.saveElapsedTime = opts.elapsedTime.getElapsed();
            cout << "Last Time " << opts.saveElapsedTime << " Sec" << endl;
            cout << "Total Time " << totalTime << " for "
                << repeatCount << " operations. Avg.= " << totalTime/repeatCount
                << " min= " << minTime << " max= " << maxTime << endl;
        }

        cout << "Total Elapsed Time= " << totalElapsedExecutionTime.getElapsed()
             << " Sec. Terminated at " << System::getCurrentASCIITime() << endl;
    }
    if (opts.delay != 0)
    {
        Threads::sleep(opts.delay * 1000);
    }
    return(opts.termCondition);
}
Beispiel #15
0
int main(int argc, char** argv)
{
    OptionManager om;
    TestModelWalkStressClient tmsc;
    Uint32 validArg = 0;
    struct OptionRow *newOptionsTable = 0;
    Uint32 newOptionsCount = 0;
    Uint32 cOptionCount =  0;

    //
    // Variables need to connect to server. 
    //
    Boolean useSSL;
    String host;
    Uint32 portNumber = 0;
    String portStr;
    String userName;
    String password;
    String help;
    Boolean connectedToHost = false;

    //
    // Variables needed to do loging and status checking.
    //
    String pidFile;
    String clientId;
    pid_t clientPid;
    String clientLog, stopClient;
    char pid_str[15];

    //
    // Number of times the command succeeded. 
    //
    Uint32 successCount=0;

    //
    // Number of iterations after which logErrorPercentage() is called.
    //
    Uint32 iteration=0;

    //
    // Total number of times the command was executed.
    //
    Uint32 totalCount=0;

    //
    // timeout.
    //
    Uint32 timeout = 30000;

    //
    // This try block includes all the options gathering function.
    //
    try
    {
        //
        // client specific options if any.
        //
        struct OptionRow *cOptionTable = 0; 
        newOptionsCount = cOptionCount;

        try
        {
            //
            // Generate new option table for this client using
            // the OptionManager.
            //
            
            newOptionsTable = tmsc.generateClientOptions(cOptionTable,
                cOptionCount,newOptionsCount);
            validArg = tmsc.GetOptions(om, argc, argv, newOptionsTable,
                newOptionsCount);
        }
        catch (Exception& e)
        {
            PEGASUS_STD(cerr) << argv[0] << ": " << e.getMessage()
                              << PEGASUS_STD(endl);
            exit(1);
        }
        catch (...)
        {
            PEGASUS_STD(cerr) << argv[0] << ": Error in Options operation "
                              << PEGASUS_STD(endl);
            exit(1);
        }

        verboseTest = om.isTrue("verbose");

        om.lookupValue("username", userName);

        om.lookupValue("password", password);

        om.lookupIntegerValue("timeout",timeout);

        useSSL =  om.isTrue("ssl");

        om.lookupValue("hostname",host);
        om.lookupValue("port",portStr);

        if (portStr.getCString())
        {
            sscanf (portStr.getCString (), "%u", &portNumber);
        }
        
        //
        // Setting default ports.
        //
        if (!portNumber)
        {
            if (useSSL)
            {
                portNumber = 5989;
            }
            else
            {
                portNumber = 5988;
            }
        }

        //
        // default host is localhost.
        //
        if (host == String::EMPTY)
        {
            host = String("localhost");
        }

        //
        // Signal Handling - SIGINT
        //
        signal(SIGINT, endTest);

        om.lookupValue("clientid", clientId);

        om.lookupValue("pidfile", pidFile);

        clientPid = getpid();

        om.lookupValue("clientlog", clientLog);

        om.lookupValue("help", help);

    }// end of option Try block
    catch (Exception& e)
    {
        PEGASUS_STD(cerr) << argv[0] << ": " << e.getMessage()
                          << PEGASUS_STD(endl);
        exit(1);
    }
    catch (...)
    {
        PEGASUS_STD(cerr) << argv[0] << ": Unknown Error gathering options "
                          << PEGASUS_STD(endl);
        exit(1);
    }

    /* Checking whether the user asked for HELP Info...
    if (om.valueEquals("help", "true"))
    {
        String header = "Usage ";
        header.append(argv[0]);
        header.append(" -parameters -n [namespace] -c [classname] ");
        header.append(" -clientId [clientId] -pidFile [pidFile] ");
        header.append(" -clientLog [clientLog]");
        String trailer = "Assumes localhost:5988 if host not specified";
        trailer.append("\nHost may be of the form name or name:port");
        trailer.append("\nPort 5988 assumed if port number missing.");
        om.printOptionsHelpTxt(header, trailer);
        exit(0);
    } */

    try
    {
        //
        // Timer Start.
        //
        tmsc.startTime();

        tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);

        //
        // connect the client.
        //
        CIMClient* client = new CIMClient();

        sprintf(pid_str, "%d", clientPid);

        stopClient = String::EMPTY;
        stopClient.append(FileSystem::extractFilePath(pidFile));
        stopClient.append("STOP_");
        stopClient.append(pid_str);

        //
        // This loop executes till the client gets stop signal from
        // controller.
        //
        while (!quit)
        {
            if (FileSystem::exists(stopClient))
            {
                if (verboseTest)
                {
                    String mes("Ending client. ");
                    tmsc.errorLog(clientPid, clientLog, mes); 
                }
                break;
            }

                if (!verboseTest)
                {
#ifdef PEGASUS_OS_TYPE_WINDOWS
                    freopen("nul","w",stdout);
#else 
                    freopen("/dev/null","w",stdout);
#endif
                }

            if (!connectedToHost)
            {
                try
                {
                    tmsc.connectClient( client, host, portNumber, userName,
                        password, useSSL, timeout, verboseTest);
                    connectedToHost = true;
                    
                   //
                   // Client has successfully connected to server.
                   // update status if previously not Success.
                   //
                   if (globalStatus != CLIENT_PASS)
                   {
                       globalStatus = CLIENT_PASS;
                       tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                   }
                }
                catch (CannotConnectException)
                {
                    globalStatus = CLIENT_UNKNOWN;
                    tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                    connectedToHost = false;
                }
                catch (CIMException &e)
                {
                    globalStatus = CLIENT_UNKNOWN;
                    tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                    connectedToHost = false;
                    String mes(e.getMessage());
                    tmsc.errorLog(clientPid, clientLog, mes);
                }
                catch (Exception &e)
                {
                    globalStatus = CLIENT_UNKNOWN;
                    tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                    connectedToHost = false;
                    String mes(e.getMessage());
                    tmsc.errorLog(clientPid, clientLog, mes);
                }
                catch (...)
                {
                    globalStatus = CLIENT_UNKNOWN;
                    tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                    connectedToHost = false;
                    String mes("Error connencting to server in ModleWalk");
                    mes.append(" client ");
                    tmsc.errorLog(clientPid, clientLog,mes);
                }
            }/* end of if (!connectedToHost). */
            iteration++;
            totalCount++;
            if (connectedToHost)
            {
                try
                {
                    Array<CIMNamespaceName> nameSpacesArray;

                    //
                    // Enumerate all the namespaces here.
                    //
                    nameSpacesArray = getNameSpaces(
                                          tmsc,
                                          client,
                                          om,
                                          clientPid,
                                          clientLog,
                                          clientId,
                                          globalStatus,
                                          pidFile);

                    //
                    // Enumerate all qualifiers in the namespaces.
                    //
                    enumerateAllQualifiers(
                        tmsc,
                        client, 
                        nameSpacesArray,
                        clientPid,
                        clientLog,
                        clientId,
                        globalStatus,
                        pidFile);

                    //
                    // Enumerate all the class related info here.
                    //
                    enumerateClassRelatedInfo(
                        tmsc,
                        client,
                        om,
                        nameSpacesArray,
                        clientPid,
                        clientLog,
                        clientId,
                        globalStatus,
                        pidFile);

                    successCount++;
                }
                //
                // This specail catch block in needed so that we will know if
                // the connenction was lost. We then connect on the next time
                // through the loop.
                //
                
                catch (CannotConnectException)
                {
                    globalStatus = CLIENT_UNKNOWN;
                    tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                    connectedToHost = false;
                }
                catch (CIMException &cimE)
                {
                    globalStatus = CLIENT_FAIL;
                    tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                    String mes(cimE.getMessage());
                    tmsc.errorLog(clientPid, clientLog, mes);
                }
                catch (Exception &exp)
                {
                    globalStatus = CLIENT_FAIL;
                    tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                    String mes(exp.getMessage());
                    tmsc.errorLog(clientPid, clientLog, mes);
                }
                catch (...)
                {
                    globalStatus = CLIENT_FAIL;
                    tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                    String mes("Unknown Error during ModelWalk Execution");
                    tmsc.errorLog(clientPid, clientLog, mes);
                }

                nextCheck = tmsc.checkTime();
                if (nextCheck)
                {
                    tmsc.logInfo(clientId, clientPid, globalStatus, pidFile);
                    nextCheck = false;
                }

                //
                // If verbose is set, log success percentage for every 100
                // iterations. If verbose is not set, log success percentage
                // for every 10000 iterations.
                //
                if (verboseTest)
                {
                    if (iteration == 100)
                    {
                        tmsc.logErrorPercentage(
                            successCount, 
                            totalCount, 
                            clientPid,
                            clientLog,
                            clientName);
                        iteration = 0;
                    }
                }
                else
                {
                    if (iteration == 1000)
                    {
                        tmsc.logErrorPercentage(
                            successCount,
                            totalCount,
                            clientPid,
                            clientLog,
                            clientName);
                        iteration = 0;
                    }
                }
            }
        } // end of while (!quit).
    }
    catch (Exception &exp)
    {
        String expStr("Exception in ModelWalk client, causing it to exit: ");
        expStr.append(exp.getMessage());
        tmsc.errorLog(clientPid, clientLog, expStr);

        if (verboseTest)
        {
            PEGASUS_STD(cerr) << expStr.getCString() << PEGASUS_STD(endl);
        }
    }
    catch (...)
    {
        String expStr("General Exception in ModelWalk, causing it to exit");
        tmsc.errorLog(clientPid, clientLog, expStr);

        if (verboseTest)
        {
            PEGASUS_STD(cerr) << expStr.getCString() << PEGASUS_STD(endl);
        }
    }

//
// One second delay before shutdown.
//
#ifndef PEGASUS_OS_TYPE_WINDOWS
    sleep(1);
#else
    Sleep(1000);
#endif
    if (FileSystem::exists(stopClient))
    {
        //
        // Remove STOP file here. 
        //
        FileSystem::removeFile(stopClient);
    }
   
    if (verboseTest)
    {
        errorInfo.clear();
        errorInfo.append("+++++ TestModelWalkStressClient Terminated ");
        errorInfo.append("Normally +++++");
        tmsc.errorLog(clientPid, clientLog, errorInfo);
        errorInfo.clear();
    }
    return 0;
}
Beispiel #16
0
/**
    GetNameSpaces
    If no nameSpace is supplied on the command line, this method looks into
    the root and test nameSpaces for the _Namespace class. The names of the 
    instances of that class are retrued by this method.
*/
Array<CIMNamespaceName> getNameSpaces(
    TestModelWalkStressClient &tmsc,
    CIMClient* client,
    OptionManager &om,
    pid_t clientPid,
    String& clientLog,
    String &clientId,
    int status,
    String &pidFile)
{
    Array<CIMNamespaceName> topNamespaceNames;
    Array<CIMNamespaceName> returnNamespaces;
    String tmpNamespace;

    om.lookupValue("namespace",tmpNamespace);
    if (tmpNamespace != String::EMPTY)
    {
        returnNamespaces.append(CIMNamespaceName (tmpNamespace));
    }
    else
    {
        //
        // Get all namespaces for display using the __Namespaces function.
        //
        CIMName className = "__NameSpace";

        //
        // We have to append any new top level root namespace if created in
        // repository.
        //
        topNamespaceNames.append("root");
        topNamespaceNames.append("test");

        Uint32 start = 0;
        Uint32 end = topNamespaceNames.size();

        //
        // for all new elements in the output array. 
        //
        for (Uint32 range = start; range < end; range ++)
        {
            //
            // Get the next increment in naming for all name element in
            // the array.
            //
            Array<CIMInstance> instances = client->enumerateInstances(
                topNamespaceNames[range], className);

            if (status != CLIENT_PASS)
            {
                status = CLIENT_PASS;
                tmsc.logInfo(clientId, clientPid, status, pidFile);
            }
            for (Uint32 i = 0 ; i < instances.size(); i++)
            {
                Uint32 pos;
                //
                // if we find the property and it is a string, use it.
                //
                if ((pos = instances[i].findProperty("name")) != PEG_NOT_FOUND)
                {
                    CIMValue value;
                    String namespaceComponent;
                    value = instances[i].getProperty(pos).getValue();
                    if (value.getType() == CIMTYPE_STRING)
                    {
                        value.get(namespaceComponent);
                        String ns = topNamespaceNames[range].getString();
                        ns.append("/");
                        ns.append(namespaceComponent);
                        returnNamespaces.append(ns);
                    }
                }
            }
        }
    }//else block ends here...

    if (verboseTest)
    {
        errorInfo.clear();
        errorInfo.append("+++++ Successfully Enumerated all Namespaces that ");
        errorInfo.append("have a _NameSpace instance defined for them in the");
        errorInfo.append(" root of test namespaces +++++");
        tmsc.errorLog(clientPid, clientLog, errorInfo);
        errorInfo.clear();
    }
    return returnNamespaces;
}
Beispiel #17
0
int main(int argc, char** argv)
{

  // char connection[50] = "localhost:5988";
  char *address_string = NULL;

    Uint32 repetitions = 1;

    // Get environment variables:

    String pegasusHome;
    pegasusHome = "/";

    // GetEnvironmentVariables(argv[0], pegasusHome);

    // Get options (from command line and from configuration file); this
    // removes corresponding options and their arguments fromt he command
    // line.

    // Get options (from command line and from configuration file); this
    // removes corresponding options and their arguments fromt he command
    // line.

    OptionManager om;

    try
    {
         GetOptions(om, argc, argv, pegasusHome);
    }
    catch (Exception& e)
    {
         cerr << argv[0] << ": " << e.getMessage() << endl;
         exit(1);
    }

    // Check to see if user asked for help (-h otpion):
    if (om.valueEquals("help", "true"))
    {
                String header = "Usage ";
                header.append(argv[0]);
                header.append(" -parameters host [host]");

                String trailer = "Assumes localhost:5988 if host not specified";
                trailer.append("\nHost may be of the form name or name:port");
                trailer.append("\nPort 5988 assumed if port number missing.");
                om.printOptionsHelpTxt(header, trailer);

         exit(0);
    }

    String localNameSpace;
    om.lookupValue("namespace", localNameSpace);
    globalNamespace = localNameSpace;
    cout << "Namespace = " << localNameSpace << endl;

    String userName;
    om.lookupValue("user", userName);
    if (userName != String::EMPTY)
    {
       cout << "Username = "******"verbose");

    String password;
    om.lookupValue("password", password);
    if (password != String::EMPTY)
    {
       cout << "password = "******"repeat", repeatTestCount))
        repeatTestCount = 1;
    /*
    if (om.lookupValue("repeat", repeats))
        {
        repeatTestCount = atol(repeats.getCString());
        }
    else
        repeatTestCount = 1;
    */
    if(verboseTest)
        cout << "Test repeat count " << repeatTestCount << endl;

    // Setup the active test flag.  Determines if we change repository.
    Boolean activeTest = false;
    if (om.valueEquals("active", "true"))
         activeTest = true;

    // here we determine the list of systems to test.
    // All arguments remaining in argv go into list.

    Boolean localConnection = (om.valueEquals("local", "true"))? true: false;
    cout << "localConnection " << (localConnection ? "true" : "false") << endl;

    Array<String> connectionList;
    if (argc > 1 && !localConnection)
         for (Sint32 i = 1; i < argc; i++)
             connectionList.append(argv[i]);

    // substitute the default if no params
    if(argc < 2)
      connectionList.append("localhost:5988");

    // Expand host to add port if not defined

    Boolean useSSL =  om.isTrue("ssl");

    // Show the connectionlist
    cout << "Connection List size " << connectionList.size() << endl;
    for (Uint32 i = 0; i < connectionList.size(); i++)
    cout << "Connection " << i << " address " << connectionList[i] << endl;

    for(Uint32 numTests = 1; numTests <= repeatTestCount; numTests++)
    {
        cout << "Test Repetition # " << numTests << endl;
        for (Uint32 i = 0; i < connectionList.size(); i++)
        {
            cout << "Start Try Block" << endl;
          try
          {
             cout << "Set Stopwatch" << endl;

             Stopwatch elapsedTime;

             cout << "Create client" << endl;
             CIMClient client;
             client.setTimeout(60 * 1000);
             cout << "Client created" << endl;

                     //
                     //  Get host and port number from connection list entry
                     //
                     Uint32 index = connectionList[i].find (':');
                     String host = connectionList[i].subString (0, index);
                     Uint32 portNumber = 0;
                     if (index != PEG_NOT_FOUND)
                     {
                         String portStr = connectionList[i].subString
                             (index + 1, connectionList[i].size ());
                         sscanf (portStr.getCString (), "%u", &portNumber);
                     }

                     if (useSSL)
             {

                        //
                        // Get environment variables:
                        //
                        const char* pegasusHome = getenv("PEGASUS_HOME");

                        String certpath = FileSystem::getAbsolutePath(
                            pegasusHome, PEGASUS_SSLCLIENT_CERTIFICATEFILE);

            String randFile;
#ifdef PEGASUS_SSL_RANDOMFILE
            randFile = FileSystem::getAbsolutePath(
                            pegasusHome, PEGASUS_SSLCLIENT_RANDOMFILE);
#endif

                        SSLContext sslcontext(certpath,verifyServerCertificate, randFile);

            if (om.isTrue("local"))
            {
                 cout << "Using local SSL connection mechanism " << endl;
                     client.connectLocal();
            }
            else
            {
                            cout << "connecting to " << connectionList[i] << " using SSL" << endl;
                            client.connect (host, portNumber, sslcontext,
                                            userName, password);
                        }
              }
                  else
              {
            if (om.isTrue("local"))
            {
                 cout << "Using local connection mechanism " << endl;
                     client.connectLocal();
            }
            else
            {
              cout << "Connecting to " << connectionList[i] << endl;
                            client.connect (host, portNumber,
                                            userName, password);
            }
              }
              cout << "Client Connected" << endl;

              testStart("Test NameSpace Operations - Relative Name");
              elapsedTime.reset();
              elapsedTime.start();
              TestNamespaceHierarchy1(client, activeTest, verboseTest);
              elapsedTime.stop();
              testEnd(elapsedTime.getElapsed());

              testStart("Test NameSpace Operations - Absolute Name");
              elapsedTime.reset();
              elapsedTime.start();
              TestNamespaceHierarchy2(client, activeTest, verboseTest);
              elapsedTime.stop();
              testEnd(elapsedTime.getElapsed());

              client.disconnect();
          }
          catch(Exception& e)
          {
               PEGASUS_STD(cerr) << "Error: " << e.getMessage() <<
                 PEGASUS_STD(endl);
               exit(1);
          }
        }
    }
    PEGASUS_STD(cout) << "+++++ "<< argv[0] << " Terminated Normally" << PEGASUS_STD(endl);
    return 0;
}