Пример #1
0
/**
 * Formats the given ASTNode as an SBML L3 function name and appends the
 * result to the given StringBuffer.
 */
void
L3FormulaFormatter_formatFunction (StringBuffer_t *sb, const ASTNode_t *node, const L3ParserSettings_t *settings)
{
  ASTNodeType_t type = ASTNode_getType(node);
  switch (type)
  {
  case AST_PLUS:
    StringBuffer_append(sb, "plus");
    break;
  case AST_TIMES:
    StringBuffer_append(sb, "times");
    break;
  case AST_MINUS:
    StringBuffer_append(sb, "minus");
    break;
  case AST_DIVIDE:
    StringBuffer_append(sb, "divide");
    break;
  case AST_POWER:
    StringBuffer_append(sb, "pow");
    break;
  case AST_FUNCTION_LN:
    StringBuffer_append(sb, "ln");
    break;

  default:
    FormulaFormatter_formatFunction(sb, node);
    break;
  }
}
Пример #2
0
/**
 * Formats the given ASTNode as an SBML L1 operator and appends the result
 * to the given StringBuffer.
 */
void
L3FormulaFormatter_formatLogicalRelational (StringBuffer_t *sb, const ASTNode_t *node)
{
  ASTNodeType_t type = ASTNode_getType(node);

  StringBuffer_appendChar(sb, ' ');
  switch(type)
  {
  case AST_LOGICAL_AND:
    StringBuffer_append(sb, "&&");
    break;
  case AST_LOGICAL_OR:
    StringBuffer_append(sb, "||");
    break;
  case AST_RELATIONAL_EQ:
    StringBuffer_append(sb, "==");
    break;
  case AST_RELATIONAL_GEQ:
    StringBuffer_append(sb, ">=");
    break;
  case AST_RELATIONAL_GT:
    StringBuffer_append(sb, ">");
    break;
  case AST_RELATIONAL_LEQ:
    StringBuffer_append(sb, "<=");
    break;
  case AST_RELATIONAL_LT:
    StringBuffer_append(sb, "<");
    break;
  case AST_RELATIONAL_NEQ:
    StringBuffer_append(sb, "!=");
    break;
  case AST_LOGICAL_NOT:
  case AST_LOGICAL_XOR:
  default:
    //Should never be called for these cases; unary not is
    // handled by checking unary not earlier; xor always
    // claims that it's a function, and is caught with 'isFunction'
    assert(0); 
    StringBuffer_append(sb, "!!");
    break;
  }
  StringBuffer_appendChar(sb, ' ');
}
Пример #3
0
static void do_status(SendMail_T *S) {
        int status = 0;
        StringBuffer_clear(S->status_message);
        char buf[STRLEN];
        do {
                if (! Socket_readLine(S->socket, buf, sizeof(buf)))
                        THROW(IOException, "Error receiving data from the mailserver '%s' -- %s", S->server, STRERROR);
                StringBuffer_append(S->status_message, "%s", buf);
        } while (buf[3] == '-'); // multi-line response
        Str_chomp(buf);
        if (sscanf(buf, "%d", &status) != 1 || status < 200 || status >= 400)
                THROW(IOException, "%s", buf);
}
Пример #4
0
/**
 * Prints a document header into the given buffer.
 * @param B StringBuffer object
 * @param V Format version
 * @param myip The client-side IP address
 */
static void document_head(StringBuffer_T B, int V, const char *myip) {
        StringBuffer_append(B, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
        if (V == 2)
                StringBuffer_append(B, "<monit id=\"%s\" incarnation=\"%lld\" version=\"%s\"><server>", Run.id, (long long)Run.incarnation, VERSION);
        else
                StringBuffer_append(B,
                        "<monit>"
                        "<server>"
                        "<id>%s</id>"
                        "<incarnation>%lld</incarnation>"
                        "<version>%s</version>",
                        Run.id,
                        (long long)Run.incarnation,
                        VERSION);
        StringBuffer_append(B,
                "<uptime>%ld</uptime>"
                "<poll>%d</poll>"
                "<startdelay>%d</startdelay>"
                "<localhostname>%s</localhostname>"
                "<controlfile>%s</controlfile>",
                (long)Util_getProcessUptime(Run.pidfile),
                Run.polltime,
                Run.startdelay,
                Run.localhostname ? Run.localhostname : "",
                Run.controlfile ? Run.controlfile : "");

        if (Run.dohttpd) {
                StringBuffer_append(B, "<httpd><address>%s</address><port>%d</port><ssl>%d</ssl></httpd>", Run.bind_addr ? Run.bind_addr : myip, Run.httpdport, Run.httpdssl);

                if (Run.mmonitcredentials)
                        StringBuffer_append(B, "<credentials><username>%s</username><password>%s</password></credentials>", Run.mmonitcredentials->uname, Run.mmonitcredentials->passwd);
        }
 
        StringBuffer_append(B,
                "</server>"
                "<platform>"
                "<name>%s</name>"
                "<release>%s</release>"
                "<version>%s</version>"
                "<machine>%s</machine>"
                "<cpu>%d</cpu>"
                "<memory>%lu</memory>"
                "<swap>%lu</swap>"
                "</platform>",
                systeminfo.uname.sysname,
                systeminfo.uname.release,
                systeminfo.uname.version,
                systeminfo.uname.machine,
                systeminfo.cpus,
                systeminfo.mem_kbyte_max,
                systeminfo.swap_kbyte_max);
}
/**
 * Read all processes to initialize the information tree.
 * @param reference  reference of ProcessTree
 * @return treesize>0 if succeeded otherwise =0.
 */
int initprocesstree_sysdep(ProcessTree_T **reference) {
  int                treesize;
  static kvm_t      *kvm_handle;
  ProcessTree_T     *pt;
  struct kinfo_proc *pinfo;

  if (!(kvm_handle = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, prog))) {
    LogError("system statistic error -- cannot initialize kvm interface\n");
    return FALSE;
  }

  pinfo = kvm_getprocs(kvm_handle, KERN_PROC_PROC, 0, &treesize);
  if (!pinfo || (treesize < 1)) {
    LogError("system statistic error -- cannot get process tree\n");
    kvm_close(kvm_handle);
    return FALSE;
  }

  pt = CALLOC(sizeof(ProcessTree_T), treesize);

  for (int i = 0; i < treesize; i++) {
    StringBuffer_T cmdline = StringBuffer_create(64);
    pt[i].pid       = pinfo[i].ki_pid;
    pt[i].ppid      = pinfo[i].ki_ppid;
    pt[i].starttime = pinfo[i].ki_start.tv_sec;
    pt[i].cputime   = (long)(pinfo[i].ki_runtime / 100000);
    pt[i].mem_kbyte = (unsigned long)(pinfo[i].ki_rssize * pagesize_kbyte);
    int flags       = pinfo[i].ki_stat;
    char * procname = pinfo[i].ki_comm;
    if (flags == SZOMB)
      pt[i].status_flag |= PROCESS_ZOMBIE;
    pt[i].cpu_percent = 0;
    pt[i].time = get_float_time();
    char **args;
    if ((args = kvm_getargv(kvm_handle, &pinfo[i], 0))) {
      for (int j = 0; args[j]; j++)
        StringBuffer_append(cmdline, args[j + 1] ? "%s " : "%s", args[j]);
      pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline)));
    }
    StringBuffer_free(&cmdline);
    if (! pt[i].cmdline || ! *pt[i].cmdline)
      pt[i].cmdline = Str_dup(procname);
  }

  *reference = pt;
  kvm_close(kvm_handle);

  return treesize;
}
Пример #6
0
/**
 * Send an error message
 * @param res HttpResponse object
 * @param code Error Code to lookup and send
 * @param msg Optional error message (may be NULL)
 */
void send_error(HttpResponse res, int code, const char *msg) {
  char server[STRLEN];
  const char *err= get_status_string(code);

  reset_response(res);
  set_content_type(res, "text/html");
  set_status(res, code);
  StringBuffer_append(res->outputbuffer,
	   "<html><head><title>%d %s</title></head>"\
	   "<body bgcolor=#FFFFFF><h2>%s</h2>%s<p>"\
	   "<hr><a href='%s'><font size=-1>%s</font></a>"\
	   "</body></html>\r\n",
	    code, err, err, msg?msg:"", SERVER_URL, get_server(server, STRLEN));
  DEBUG("HttpRequest error: %s %d %s\n", SERVER_PROTOCOL, code, msg ? msg : err);
}
Пример #7
0
/**
 * Formats the given ASTNode as a real number and appends the result to
 * the given StringBuffer.
 */
void
FormulaFormatter_formatReal (StringBuffer_t *sb, const ASTNode_t *node)
{
  double value = ASTNode_getReal(node);
  int    sign;


  if (util_isNaN(value))
  {
    StringBuffer_append(sb, "NaN");
  }
  else if ((sign = util_isInf(value)) != 0)
  {
    if (sign == -1)
    {
      StringBuffer_appendChar(sb, '-');
    }

    StringBuffer_append(sb, "INF");
  }
  else if (util_isNegZero(value))
  {
    StringBuffer_append(sb, "-0");
  }
  else
  {
    if (ASTNode_getType(node) == AST_REAL_E)
    {
      StringBuffer_appendExp(sb, value);
    }
    else
    {
      StringBuffer_appendReal(sb, value);
    }
  }
}
Пример #8
0
Файл: xml.c Проект: kemadz/monit
/**
 * Prints a event description into the given buffer.
 * @param E Event object
 * @param B StringBuffer object
 */
static void status_event(Event_T E, StringBuffer_T B) {
        StringBuffer_append(B,
                            "<event>"
                            "<collected_sec>%lld</collected_sec>"
                            "<collected_usec>%ld</collected_usec>"
                            "<service>%s</service>"
                            "<type>%d</type>"
                            "<id>%ld</id>"
                            "<state>%d</state>"
                            "<action>%d</action>"
                            "<message><![CDATA[",
                            (long long)E->collected.tv_sec,
                            (long)E->collected.tv_usec,
                            E->id == Event_Instance ? "Monit" : E->source->name,
                            E->type,
                            E->id,
                            E->state,
                            Event_get_action(E));
        _escapeCDATA(B, E->message);
        StringBuffer_append(B, "]]></message>");
        if (E->source->token)
                StringBuffer_append(B, "<token>%s</token>", E->source->token);
        StringBuffer_append(B, "</event>");
}
Пример #9
0
static int prepare(T C, const char *sql, int len, MYSQL_STMT **stmt) {
        if (! (*stmt = mysql_stmt_init(C->db))) {
                DEBUG("mysql_stmt_init -- Out of memory\n");
                C->lastError = CR_OUT_OF_MEMORY;
                return false;
        }
        if ((C->lastError = mysql_stmt_prepare(*stmt, sql, len))) {
                StringBuffer_clear(C->sb);
                StringBuffer_append(C->sb, "%s", mysql_stmt_error(*stmt));
                mysql_stmt_close(*stmt);
                *stmt = NULL;
                return false;
        }
        return true;
}
Пример #10
0
/**
 * Formats the given ASTNode as a rational number and appends the result to
 * the given StringBuffer.  For SBML L1 this amounts to:
 *
 *   "(numerator/denominator)"
 */
void
L3FormulaFormatter_formatRational (StringBuffer_t *sb, const ASTNode_t *node, const L3ParserSettings_t *settings)
{
  StringBuffer_appendChar( sb, '(');
  StringBuffer_appendInt ( sb, ASTNode_getNumerator(node)   );
  StringBuffer_appendChar( sb, '/');
  StringBuffer_appendInt ( sb, ASTNode_getDenominator(node) );
  StringBuffer_appendChar( sb, ')');

  if (L3ParserSettings_getParseUnits(settings)) {
    if (ASTNode_hasUnits(node)) {
      StringBuffer_appendChar( sb, ' ');
      StringBuffer_append( sb, ASTNode_getUnits(node));
    }
  }
}
Пример #11
0
/**
 * Visits the given ASTNode as a function.  For this node only the
 * traversal is preorder.
 * Writes the function as a directed graph and appends the result
 * to the StringBuffer.
 */
void
FormulaGraphvizFormatter_visitFunction (const ASTNode_t *parent,
                                        const ASTNode_t *node,
                                        StringBuffer_t  *sb )
{
  unsigned int numChildren = ASTNode_getNumChildren(node);
  unsigned int n;
  char         *name;
  char         *uniqueName;
  
  uniqueName = FormulaGraphvizFormatter_getUniqueName(node);
  name       = FormulaGraphvizFormatter_format(node);
  
  StringBuffer_append(sb, uniqueName);
  StringBuffer_append(sb, " [shape=box, label=");
  StringBuffer_append(sb, name);
  StringBuffer_append(sb, "];\n");

  if (parent != NULL) 
  {
    name = FormulaGraphvizFormatter_getUniqueName(node);
    uniqueName = FormulaGraphvizFormatter_getUniqueName(parent);
    
    if(strcmp(name, uniqueName)) 
    {
      StringBuffer_append(sb, uniqueName);
      StringBuffer_append(sb, " -> ");
      StringBuffer_append(sb, name);
      StringBuffer_append(sb, ";\n");
    }
  }

  if (numChildren > 0)
  {
    FormulaGraphvizFormatter_visit( node, ASTNode_getChild(node, 0), sb );
  }

  for (n = 1; n < numChildren; n++)
  {
    FormulaGraphvizFormatter_visit( node, ASTNode_getChild(node, n), sb );
  }

}
Пример #12
0
/**
 * Visits the given ASTNode and continues the inorder traversal.
 * Writes the function as a directed graph and appends the result
 * to the StringBuffer.
 */
void
FormulaGraphvizFormatter_visitOther (const ASTNode_t *parent,
                                     const ASTNode_t *node,
                                     StringBuffer_t  *sb )
{
  unsigned int numChildren = ASTNode_getNumChildren(node);
  char         *name;
  char         *uniqueName;

  if (numChildren > 0)
  {
    uniqueName = FormulaGraphvizFormatter_getUniqueName(node);
    name       = FormulaGraphvizFormatter_format(node);
    
    StringBuffer_append(sb, uniqueName);
    StringBuffer_append(sb, " [shape=box, label=");
    StringBuffer_append(sb, name);
    StringBuffer_append(sb, "];\n");
    
    FormulaGraphvizFormatter_visit( node, ASTNode_getLeftChild(node), sb );
  }

  if (parent != NULL) 
  {
    name       = FormulaGraphvizFormatter_getUniqueName(node);
    uniqueName = FormulaGraphvizFormatter_getUniqueName(parent);
    
    if(strcmp(name, uniqueName)) 
    {
      StringBuffer_append(sb, uniqueName);
      StringBuffer_append(sb, " -> ");
      StringBuffer_append(sb, name);
      StringBuffer_append(sb, ";\n");
    }
  }

  if (numChildren > 1)
  {
    FormulaGraphvizFormatter_visit( node, ASTNode_getRightChild(node), sb );
  }
}
Пример #13
0
// Print a row. If wrap is enabled and the text excceeds width, return true (printed text up to column width, repetition possible to print the rest), otherwise false
static boolean_t _printRow(T t) {
        boolean_t repeat = false;
        for (int i = 0; i < t->columnsCount; i++) {
                StringBuffer_append(t->b, COLOR_DARKGRAY BOX_VERTICAL COLOR_RESET " ");
                if (*(t->columns[i]._color))
                        StringBuffer_append(t->b, "%s", t->columns[i]._color);
                if (! t->columns[i].value || t->columns[i]._cursor > strlen(t->columns[i].value) - 1) {
                        // Empty column pading
                        StringBuffer_append(t->b, "%*s", t->columns[i].width, " ");
                } else if (strlen(t->columns[i].value + t->columns[i]._cursor) > t->columns[i].width) {
                        if (t->columns[i].wrap) {
                                // The value exceeds the column width and should be wrapped
                                int column = 0;
                                for (; t->columns[i].value[t->columns[i]._cursor] && (column == 0 || t->columns[i]._cursor % t->columns[i].width > 0); t->columns[i]._cursor++, column++)
                                        StringBuffer_append(t->b, "%c", t->columns[i].value[t->columns[i]._cursor]);
                                if (t->columns[i]._cursor < t->columns[i]._valueLength)
                                        repeat = true;
                        } else {
                                // The value exceeds the column width and should be truncated
                                Str_trunc(t->columns[i].value, t->columns[i].width);
                                StringBuffer_append(t->b, t->columns[i].align == BoxAlign_Right ? "%*s" : "%-*s", t->columns[i].width, t->columns[i].value);
                                t->columns[i]._cursor = t->columns[i]._valueLength;
                        }
                } else {
                        // The whole value fits in the column width
                        StringBuffer_append(t->b, t->columns[i].align == BoxAlign_Right ? "%*s" : "%-*s", t->columns[i].width, t->columns[i].value + t->columns[i]._cursor);
                        t->columns[i]._cursor = t->columns[i]._valueLength;
                }
                StringBuffer_append(t->b, " ");
                if (*(t->columns[i]._color))
                        StringBuffer_append(t->b, COLOR_RESET);
        }
        StringBuffer_append(t->b, COLOR_DARKGRAY BOX_VERTICAL COLOR_RESET "\n");
        t->index.row++;
        return repeat;
}
Пример #14
0
/* ------------------------------------------------------- Private methods */
static void getSqlErr(T C,SQLHSTMT hstmt) {
	unsigned char szSQLSTATE[10];
	SDWORD nErr;
	unsigned char msg[SQL_MAX_MESSAGE_LENGTH+1];
	SWORD cbmsg;

	unsigned char szData[256];   // Returned data storage

	while(SQLError(0,0,hstmt,szSQLSTATE,&nErr,msg,sizeof(msg),&cbmsg)==
		SQL_SUCCESS)
	{
        snprintf((char *)szData, sizeof(szData), "Error:\nSQLSTATE=%s,Native error=%ld,msg='%s'", szSQLSTATE, nErr, msg);
		//MessageBox(NULL,(const char *)szData,"ODBC Error",MB_OK);
		//return NULL;
		//return strdup(szData);
	}
	StringBuffer_append(C->err,"%s",szData);

}
Пример #15
0
ResultSet_T MysqlConnection_executeQuery(T C, const char *sql, va_list ap) {
        va_list ap_copy;
        MYSQL_STMT *stmt = NULL;
	assert(C);
        StringBuffer_clear(C->sb);
        va_copy(ap_copy, ap);
        StringBuffer_vappend(C->sb, sql, ap_copy);
        va_end(ap_copy);
        if (prepare(C, StringBuffer_toString(C->sb), StringBuffer_length(C->sb), &stmt)) {
#if MYSQL_VERSION_ID >= 50002
                unsigned long cursor = CURSOR_TYPE_READ_ONLY;
                mysql_stmt_attr_set(stmt, STMT_ATTR_CURSOR_TYPE, &cursor);
#endif
                if ((C->lastError = mysql_stmt_execute(stmt))) {
                        StringBuffer_clear(C->sb);
                        StringBuffer_append(C->sb, "%s", mysql_stmt_error(stmt));
                        mysql_stmt_close(stmt);
                }
                else
                        return ResultSet_new(MysqlResultSet_new(stmt, C->maxRows, false), (Rop_T)&mysqlrops);
        }
        return NULL;
}
END_TEST


START_TEST (test_StringBuffer_grow)
{
  char *s;


  StringBuffer_append(SB, "foobar");

  fail_unless( StringBuffer_length(SB)   ==  6 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  StringBuffer_grow(SB, 10);

  fail_unless( StringBuffer_length(SB)   ==  6 );
  fail_unless( StringBuffer_capacity(SB) == 20 );

  s = StringBuffer_toString(SB);
  fail_unless( !strcmp(s, "foobar") );

  safe_free(s);
}
Пример #17
0
/**
 * Since graphviz will interpret identical names as referring to
 * the same node presentation-wise it is better if each function node
 * has a unique name.
 * 
 * Returns the name with the name of the first child
 * prepended
 *
 * THIS COULD BE DONE BETTER
 */
char *
FormulaGraphvizFormatter_getUniqueName (const ASTNode_t *node)
{
  StringBuffer_t *p = StringBuffer_create(128);
  char           *s = NULL;
  
  if (ASTNode_isOperator(node))
  {
    s = FormulaGraphvizFormatter_OperatorGetUniqueName(node);
  }
  else if (ASTNode_isFunction(node))
  {
    s = FormulaGraphvizFormatter_FunctionGetUniqueName(node);
  }
  else if (ASTNode_isInteger(node))
  {
    StringBuffer_appendInt(p, ASTNode_getInteger(node));
    s = StringBuffer_toString(p);
  }
  else if (ASTNode_isRational(node))
  {
    s = FormulaGraphvizFormatter_formatRational(node);
  }
  else if (ASTNode_isReal(node))
  {
    s = FormulaGraphvizFormatter_formatReal(node);
  }
  else if ( !ASTNode_isUnknown(node) )
  {
    StringBuffer_append(p, ASTNode_getName(node));
    s = StringBuffer_toString(p);
  }

  free(p);

  return s;
}
END_TEST


START_TEST (test_StringBuffer_appendChar)
{
  char *s, *t, *u;


  StringBuffer_appendChar(SB, '*');

  fail_unless( StringBuffer_length(SB)   ==  1 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  s = StringBuffer_toString(SB);
  fail_unless( !strcmp(s, "*") );

  StringBuffer_append(SB, "foo");

  fail_unless( StringBuffer_length(SB)   ==  4 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  t = StringBuffer_toString(SB);
  fail_unless( !strcmp(t, "*foo") );

  StringBuffer_appendChar(SB, '*');

  fail_unless( StringBuffer_length(SB)   ==  5 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  u = StringBuffer_toString(SB);
  fail_unless( !strcmp(u, "*foo*") );

  safe_free(s);
  safe_free(t);
  safe_free(u);
}
Пример #19
0
/**
 * Formats the given ASTNode as an SBML L1 function name and appends the
 * result to the given StringBuffer.
 */
void
FormulaFormatter_formatFunction (StringBuffer_t *sb, const ASTNode_t *node)
{
  ASTNodeType_t type = ASTNode_getType(node);


  switch (type)
  {
    case AST_FUNCTION_ARCCOS:
      StringBuffer_append(sb, "acos");
      break;

    case AST_FUNCTION_ARCSIN:
      StringBuffer_append(sb, "asin");
      break;

    case AST_FUNCTION_ARCTAN:
      StringBuffer_append(sb, "atan");
      break;

    case AST_FUNCTION_CEILING:
      StringBuffer_append(sb, "ceil");
      break;

    case AST_FUNCTION_LN:
      StringBuffer_append(sb, "log");
      break;

    case AST_FUNCTION_POWER:
      StringBuffer_append(sb, "pow");
      break;

    default:
      StringBuffer_append(sb, ASTNode_getName(node));
      break;
  }
}
/**
 * Read all processes to initialize the information tree.
 * @param reference reference of ProcessTree
 * @param pflags Process engine flags
 * @return treesize > 0 if succeeded otherwise 0
 */
int initprocesstree_sysdep(ProcessTree_T **reference, ProcessEngine_Flags pflags) {
        size_t pinfo_size = 0;
        int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
        if (sysctl(mib, 4, NULL, &pinfo_size, NULL, 0) < 0) {
                LogError("system statistic error -- sysctl failed: %s\n", STRERROR);
                return 0;
        }
        struct kinfo_proc *pinfo = CALLOC(1, pinfo_size);
        if (sysctl(mib, 4, pinfo, &pinfo_size, NULL, 0)) {
                FREE(pinfo);
                LogError("system statistic error -- sysctl failed: %s\n", STRERROR);
                return 0;
        }
        size_t treesize = pinfo_size / sizeof(struct kinfo_proc);
        ProcessTree_T *pt = CALLOC(sizeof(ProcessTree_T), treesize);

        char *args = NULL;
        StringBuffer_T cmdline = NULL;
        if (pflags & ProcessEngine_CollectCommandLine) {
                cmdline = StringBuffer_create(64);
                args = CALLOC(1, systeminfo.argmax + 1);
        }
        for (int i = 0; i < treesize; i++) {
                pt[i].uptime    = systeminfo.time / 10. - pinfo[i].kp_proc.p_starttime.tv_sec;
                pt[i].zombie    = pinfo[i].kp_proc.p_stat == SZOMB ? true : false;
                pt[i].pid       = pinfo[i].kp_proc.p_pid;
                pt[i].ppid      = pinfo[i].kp_eproc.e_ppid;
                pt[i].cred.uid  = pinfo[i].kp_eproc.e_pcred.p_ruid;
                pt[i].cred.euid = pinfo[i].kp_eproc.e_ucred.cr_uid;
                pt[i].cred.gid  = pinfo[i].kp_eproc.e_pcred.p_rgid;
                if (pflags & ProcessEngine_CollectCommandLine) {
                        size_t size = systeminfo.argmax;
                        mib[0] = CTL_KERN;
                        mib[1] = KERN_PROCARGS2;
                        mib[2] = pt[i].pid;
                        if (sysctl(mib, 3, args, &size, NULL, 0) != -1) {
                                /* KERN_PROCARGS2 sysctl() returns following pseudo structure:
                                 *        struct {
                                 *                int argc
                                 *                char execname[];
                                 *                char argv[argc][];
                                 *                char env[][];
                                 *        }
                                 * The strings are terminated with '\0' and may have variable '\0' padding
                                 */
                                int argc = *args;
                                char *p = args + sizeof(int); // arguments beginning
                                StringBuffer_clear(cmdline);
                                p += strlen(p); // skip exename
                                while (argc && p < args + systeminfo.argmax) {
                                        if (*p == 0) { // skip terminating 0 and variable length 0 padding
                                                p++;
                                                continue;
                                        }
                                        StringBuffer_append(cmdline, argc-- ? "%s " : "%s", p);
                                        p += strlen(p);
                                }
                                if (StringBuffer_length(cmdline))
                                        pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline)));
                        }
                        if (! pt[i].cmdline || ! *pt[i].cmdline) {
                                FREE(pt[i].cmdline);
                                pt[i].cmdline = Str_dup(pinfo[i].kp_proc.p_comm);
                        }
                }
                if (! pt[i].zombie) {
                        struct proc_taskinfo tinfo;
                        int rv = proc_pidinfo(pt[i].pid, PROC_PIDTASKINFO, 0, &tinfo, sizeof(tinfo)); // If the process is zombie, skip this
                        if (rv <= 0) {
                                if (errno != EPERM)
                                        DEBUG("proc_pidinfo for pid %d failed -- %s\n", pt[i].pid, STRERROR);
                        } else if (rv < sizeof(tinfo)) {
                                LogError("proc_pidinfo for pid %d -- invalid result size\n", pt[i].pid);
                        } else {
                                pt[i].memory.usage = (uint64_t)tinfo.pti_resident_size;
                                pt[i].cpu.time     = (double)(tinfo.pti_total_user + tinfo.pti_total_system) / 100000000.; // The time is in nanoseconds, we store it as 1/10s
                                pt[i].threads      = tinfo.pti_threadnum;
                        }
                }
        }
        if (pflags & ProcessEngine_CollectCommandLine) {
                StringBuffer_free(&cmdline);
                FREE(args);
        }
        FREE(pinfo);

        *reference = pt;
        
        return (int)treesize;
}
Пример #21
0
/**
 * Since graphviz will interpret identical names as referring to
 * the same node presentation-wise it is better if each function node
 * has a unique name.
 * 
 * Returns the name of the operator with the name of the first child
 * prepended
 *
 * THIS COULD BE DONE BETTER
 */
char *
FormulaGraphvizFormatter_OperatorGetUniqueName (const ASTNode_t *node)
{
  char           *s;
  char           number[10];
  StringBuffer_t *p   = StringBuffer_create(128);
  ASTNodeType_t  type = ASTNode_getType(node);
  
  if (FormulaGraphvizFormatter_isFunction(ASTNode_getChild(node,0))
    || ASTNode_isOperator(ASTNode_getChild(node,0))) 
  {
    StringBuffer_append(p, "func");
  }
  else
  {
    if (ASTNode_isInteger(ASTNode_getChild(node, 0)))
    {
      sprintf(number, "%d", (int)ASTNode_getInteger(ASTNode_getChild(node, 0)));
      StringBuffer_append(p, number);
    }
    else if (ASTNode_isReal(ASTNode_getChild(node, 0)))
    {
      sprintf(number, "%ld", ASTNode_getNumerator(ASTNode_getChild(node, 0)));
      StringBuffer_append(p, number);
    }
    else
    {
      StringBuffer_append(p, ASTNode_getName(ASTNode_getChild(node,0)));
    }
  }

  switch (type)
  {
    case AST_TIMES:
      StringBuffer_append(p,  "times");
      break;

    case AST_DIVIDE:
      StringBuffer_append(p,  "divide");
      break;

    case AST_PLUS:
      StringBuffer_append(p,  "plus");
      break;

    case AST_MINUS:
      StringBuffer_append(p,  "minus");
      break;

    case AST_POWER:
      StringBuffer_append(p,  "power");
      break;

    default:
      StringBuffer_appendChar(p, ASTNode_getCharacter(node));
      break;
  }
  
  s = StringBuffer_toString(p);

  free(p);

  return s;
}
Пример #22
0
/**
 * Prints a document footer into the given buffer.
 * @param B StringBuffer object
 */
static void document_foot(StringBuffer_T B) {
        StringBuffer_append(B, "</monit>");
}
Пример #23
0
/**
 * Prints a service status into the given buffer.
 * @param S Service object
 * @param B StringBuffer object
 * @param L Status information level
 * @param V Format version
 */
static void status_service(Service_T S, StringBuffer_T B, short L, int V) {
        Event_T E = S->eventlist;

        if (V == 2)
                StringBuffer_append(B, "<service name=\"%s\"><type>%d</type>", S->name ? S->name : "", S->type);
        else
                StringBuffer_append(B, "<service type=\"%d\"><name>%s</name>", S->type, S->name ? S->name : "");
        StringBuffer_append(B,
                "<collected_sec>%ld</collected_sec>"
                "<collected_usec>%ld</collected_usec>"
                "<status>%d</status>"
                "<status_hint>%d</status_hint>"
                "<monitor>%d</monitor>"
                "<monitormode>%d</monitormode>"
                "<pendingaction>%d</pendingaction>",
                S->collected.tv_sec,
                (long)S->collected.tv_usec,
                S->error,
                S->error_hint,
                S->monitor,
                S->mode,
                S->doaction);
        if (S->every.type != EVERY_CYCLE) {
                StringBuffer_append(B, "<every><type>%d</type>", S->every.type);
                if (S->every.type == 1)
                        StringBuffer_append(B, "<counter>%d</counter><number>%d</number>", S->every.spec.cycle.counter, S->every.spec.cycle.number);
                else
                        StringBuffer_append(B, "<cron><![CDATA[%s]]></cron>", S->every.spec.cron);
                StringBuffer_append(B, "</every>");
        }

        /* if the service is in error state, display first active error message to provide more details */
        while (E) {
                if ((E->state == STATE_FAILED || E->state == STATE_CHANGED) && (S->error & E->id) && E->message) {
                        StringBuffer_append(B, "<status_message><![CDATA[%s]]></status_message>", E->message);
                        break;
                }
                E = E->next;
        }
        if (L == LEVEL_FULL) {
                if (Util_hasServiceStatus(S)) {
                        if (S->type == TYPE_FILE || S->type == TYPE_DIRECTORY || S->type == TYPE_FIFO || S->type == TYPE_FILESYSTEM)
                                StringBuffer_append(B, "<mode>%o</mode><uid>%d</uid><gid>%d</gid>", S->inf->st_mode & 07777, (int)S->inf->st_uid, (int)S->inf->st_gid);
                        if (S->type == TYPE_FILE || S->type == TYPE_FIFO || S->type == TYPE_DIRECTORY)
                                StringBuffer_append(B, "<timestamp>%ld</timestamp>", (long)S->inf->timestamp);
                        if (S->type == TYPE_FILE) {
                                StringBuffer_append(B, "<size>%llu</size>", (unsigned long long) S->inf->priv.file.st_size);
                                if (S->checksum)
                                        StringBuffer_append(B, "<checksum type=\"%s\">%s</checksum>", checksumnames[S->checksum->type], S->inf->priv.file.cs_sum);
                        }
                        if (S->type == TYPE_FILESYSTEM) {
                                StringBuffer_append(B,
                                        "<flags>%d</flags>"
                                        "<block>"
                                        "<percent>%.1f</percent>"
                                        "<usage>%.1f</usage>"
                                        "<total>%.1f</total>"
                                        "</block>",
                                        S->inf->priv.filesystem.flags,
                                        S->inf->priv.filesystem.space_percent/10.,
                                        S->inf->priv.filesystem.f_bsize > 0 ? (float)S->inf->priv.filesystem.space_total / (float)1048576 * (float)S->inf->priv.filesystem.f_bsize : 0,
                                        S->inf->priv.filesystem.f_bsize > 0 ? (float)S->inf->priv.filesystem.f_blocks / (float)1048576 * (float)S->inf->priv.filesystem.f_bsize : 0);
                                if (S->inf->priv.filesystem.f_files > 0) {
                                        StringBuffer_append(B,
                                  	        "<inode>"
                                                "<percent>%.1f</percent>"
                                                "<usage>%ld</usage>"
                                                "<total>%ld</total>"
                                        	"</inode>",
                                        	S->inf->priv.filesystem.inode_percent/10.,
                                        	S->inf->priv.filesystem.inode_total,
                                                S->inf->priv.filesystem.f_files);
                                }
                        }
                        if (S->type == TYPE_PROCESS) {
                                StringBuffer_append(B,
                                        "<pid>%d</pid>"
                                        "<ppid>%d</ppid>"
                                        "<uptime>%ld</uptime>",
                                        S->inf->priv.process.pid,
                                        S->inf->priv.process.ppid,
                                        (long)S->inf->priv.process.uptime);
                                if (Run.doprocess) {
                                        StringBuffer_append(B,
                                                "<children>%d</children>"
                                                "<memory>"
                                                "<percent>%.1f</percent>"
                                                "<percenttotal>%.1f</percenttotal>"
                                                "<kilobyte>%ld</kilobyte>"
                                                "<kilobytetotal>%ld</kilobytetotal>"
                                                "</memory>"
                                                "<cpu>"
                                                "<percent>%.1f</percent>"
                                                "<percenttotal>%.1f</percenttotal>"
                                                "</cpu>",
                                                S->inf->priv.process.children,
                                                S->inf->priv.process.mem_percent/10.0,
                                                S->inf->priv.process.total_mem_percent/10.0,
                                                S->inf->priv.process.mem_kbyte,
                                                S->inf->priv.process.total_mem_kbyte,
                                                S->inf->priv.process.cpu_percent/10.0,
                                                S->inf->priv.process.total_cpu_percent/10.0);
                                }
                        }
                        if (S->type == TYPE_HOST && S->icmplist) {
                                for (Icmp_T i = S->icmplist; i; i = i->next) {
                                        StringBuffer_append(B,
                                                "<icmp>"
                                                "<type>%s</type>"
                                                "<responsetime>%.3f</responsetime>"
                                                "</icmp>",
                                                icmpnames[i->type],
                                                i->is_available ? i->response : -1.);
                                }
                        }
                        if ((S->type == TYPE_HOST || S->type == TYPE_PROCESS) && S-> portlist) {
                                Port_T p;
                                for (p = S->portlist; p; p = p->next) {
                                        if (p->family == AF_INET)
                                                StringBuffer_append(B,
                                                  	"<port>"
                                                  	"<hostname>%s</hostname>"
                                                  	"<portnumber>%d</portnumber>"
                                                  	"<request>%s</request>"
                                                  	"<protocol>%s</protocol>"
                                                  	"<type>%s</type>"
                                                  	"<responsetime>%.3f</responsetime>"
                                                  	"</port>",
                                                  	p->hostname?p->hostname:"",
                                                  	p->port,
                                                  	p->request?p->request:"",
                                                  	p->protocol->name?p->protocol->name:"",
                                                  	Util_portTypeDescription(p),
                                                  	p->is_available?p->response:-1.);
                                        else if (p->family == AF_UNIX)
                                                StringBuffer_append(B,
                                                  	"<unix>"
                                                	"<path>%s</path>"
                                                	"<protocol>%s</protocol>"
                                                	"<responsetime>%.3f</responsetime>"
                                                	"</unix>",
                                                	p->pathname?p->pathname:"",
                                                	p->protocol->name?p->protocol->name:"",
                                                	p->is_available?p->response:-1.);
                                }
                        }
                        if (S->type == TYPE_SYSTEM && Run.doprocess) {
                                StringBuffer_append(B,
                                        "<system>"
                                        "<load>"
                                        "<avg01>%.2f</avg01>"
                                        "<avg05>%.2f</avg05>"
                                        "<avg15>%.2f</avg15>"
                                        "</load>"
                                        "<cpu>"
                                        "<user>%.1f</user>"
                                        "<system>%.1f</system>"
#ifdef HAVE_CPU_WAIT
                                        "<wait>%.1f</wait>"
#endif
                                        "</cpu>"
                                        "<memory>"
                                        "<percent>%.1f</percent>"
                                        "<kilobyte>%ld</kilobyte>"
                                        "</memory>"
                                        "<swap>"
                                        "<percent>%.1f</percent>"
                                        "<kilobyte>%ld</kilobyte>"
                                        "</swap>"
                                        "</system>",
                                        systeminfo.loadavg[0],
                                        systeminfo.loadavg[1],
                                        systeminfo.loadavg[2],
                                        systeminfo.total_cpu_user_percent > 0 ? systeminfo.total_cpu_user_percent/10. : 0,
                                        systeminfo.total_cpu_syst_percent > 0 ? systeminfo.total_cpu_syst_percent/10. : 0,
#ifdef HAVE_CPU_WAIT
                                        systeminfo.total_cpu_wait_percent > 0 ? systeminfo.total_cpu_wait_percent/10. : 0,
#endif
                                        systeminfo.total_mem_percent/10.,
                                        systeminfo.total_mem_kbyte,
                                        systeminfo.total_swap_percent/10.,
                                        systeminfo.total_swap_kbyte);
                        }
                        if (S->type == TYPE_PROGRAM && S->program->started) {
                                StringBuffer_append(B,
                                        "<program>"
                                        "<started>%lu</started>"
                                        "<status>%d</status>"
                                        "</program>",
                                        (unsigned long)S->program->started,
                                        S->program->exitStatus);
                        }
                }
        }
        StringBuffer_append(B, "</service>");
}
Пример #24
0
/**
 * Prints a servicegroups into the given buffer.
 * @param SG ServiceGroup object
 * @param B StringBuffer object
 * @param L Status information level
 */
static void status_servicegroup(ServiceGroup_T SG, StringBuffer_T B, short L) {
        StringBuffer_append(B, "<servicegroup name=\"%s\">", SG->name);
        for (ServiceGroupMember_T SGM = SG->members; SGM; SGM = SGM->next)
                StringBuffer_append(B, "<service>%s</service>", SGM->name);
        StringBuffer_append(B, "</servicegroup>");
}
Пример #25
0
T StringBuffer_new(const char *s) {
        return StringBuffer_append(ctor(STRLEN), "%s", s);
}
Пример #26
0
static int _doConnect(T C, char **error) {
#define ERROR(e) do {*error = Str_dup(e); goto error;} while (0)
        /* User */
        if (URL_getUser(C->url))
                StringBuffer_append(C->sb, "user='******' ", URL_getUser(C->url));
        else if (URL_getParameter(C->url, "user"))
                StringBuffer_append(C->sb, "user='******' ", URL_getParameter(C->url, "user"));
        else
                ERROR("no username specified in URL");
        /* Password */
        if (URL_getPassword(C->url))
                StringBuffer_append(C->sb, "password='******' ", URL_getPassword(C->url));
        else if (URL_getParameter(C->url, "password"))
                StringBuffer_append(C->sb, "password='******' ", URL_getParameter(C->url, "password"));
        else
                ERROR("no password specified in URL");
        /* Host */
        if (URL_getParameter(C->url, "unix-socket")) {
                if (URL_getParameter(C->url, "unix-socket")[0] != '/')
                        ERROR("invalid unix-socket directory");
                StringBuffer_append(C->sb, "host='%s' ", URL_getParameter(C->url, "unix-socket"));
        } else if (URL_getHost(C->url)) {
                StringBuffer_append(C->sb, "host='%s' ", URL_getHost(C->url));
                /* Port */
                if (URL_getPort(C->url) > 0)
                        StringBuffer_append(C->sb, "port=%d ", URL_getPort(C->url));
                else
                        ERROR("no port specified in URL");
        } else
                ERROR("no host specified in URL");
        /* Database name */
        if (URL_getPath(C->url))
                StringBuffer_append(C->sb, "dbname='%s' ", URL_getPath(C->url) + 1);
        else
                ERROR("no database specified in URL");
        /* Options */
        StringBuffer_append(C->sb, "sslmode='%s' ", IS(URL_getParameter(C->url, "use-ssl"), "true") ? "require" : "disable");
        if (URL_getParameter(C->url, "connect-timeout")) {
                TRY
                        StringBuffer_append(C->sb, "connect_timeout=%d ", Str_parseInt(URL_getParameter(C->url, "connect-timeout")));
                ELSE
                        ERROR("invalid connect timeout value");
                END_TRY;
        } else
                StringBuffer_append(C->sb, "connect_timeout=%d ", SQL_DEFAULT_TCP_TIMEOUT);
        if (URL_getParameter(C->url, "application-name"))
                StringBuffer_append(C->sb, "application_name='%s' ", URL_getParameter(C->url, "application-name"));
        /* Connect */
        C->db = PQconnectdb(StringBuffer_toString(C->sb));
        if (PQstatus(C->db) == CONNECTION_OK)
                return true;
        *error = Str_dup(PQerrorMessage(C->db));
error:
        return false;
}
Пример #27
0
static void Client_route( ClientConnection *client ) {
	#define OkayRoute "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\nContent-Length:"
	#define InvalidRoute "HTTP/1.0 403 Forbidden\r\nContent-Type: text/plain\r\nConnection: close\r\nContent-Length:12\r\n\r\nGET WRECKED\n"

	HttpParserInfo *parserInfo = client->parserInfo;

	char *path, *query;
	size_t pathSize, querySize;
	HttpParser_parseURL( parserInfo, &path, &pathSize, &query, &querySize );

	dbg_info( "Requested path: %.*s", (int)pathSize, path );
	dbg_info( "Request query: %.*s", (int)querySize, query );
	if ( EqualLiteralLength( path, pathSize, "/announce" ) ) {
		StringBuffer_append( client->writeBuffer, OkayRoute, strlen( OkayRoute ) );
		ClientAnnounceData *announce = ClientAnnounceData_new( );
		Client_CheckAllocReplyError( client, announce );

		announce->score = uv_now( client->handle.stream->loop );
		client->requestType = ClientRequest_announce;
		client->request.announce = announce;
		if ( ClientAnnounceData_fromQuery( announce, query, querySize ) ) {
			log_warn( "%s", announce->errorMessage );
			Client_replyErrorLen( client, announce->errorMessage );
			return;
		}

		dbg_info( "There was no error parsing the announce." );
		if ( announce->event == AnnounceEvent_stop ) {
			StringBuffer_append( client->writeBuffer, "6\r\n\r\n3:bye\n", 11 );
			Client_reply( client );
			return;
		}

		// check if ip has been set
		if ( !(announce->compact[0] & CompactAddress_IPv4Flag) && !(announce->compact[0] & CompactAddress_IPv6Flag) ) {
			// read from socket and header.
			char *xRealIP = HttpParser_realIP( client->parserInfo );
			if ( xRealIP ) {
				CompactAddress_fromString( announce->compact, xRealIP, NULL );
				free( xRealIP );
			} else {
				struct sockaddr_storage sock;
				int len = sizeof(sock);
				int e = uv_tcp_getpeername( client->handle.tcpHandle, (struct sockaddr*)&sock, &len );
				if ( e ) {
					Client_replyErrorLen( client, "IP could not be determined." );
					return;
				}

				CompactAddress_fromSocket( announce->compact, &sock, false );
			}
		}
		CompactAddress_dump( announce->compact );
		MemoryStore_processAnnounce( client->server->memStore, client );

	} else if ( EqualLiteralLength( path, pathSize, "/scrape" ) ) {
		StringBuffer_append( client->writeBuffer, OkayRoute, strlen( OkayRoute ) );
		ScrapeData *scrape = ScrapeData_new( );
		Client_CheckAllocReplyError( client, scrape );

		client->requestType = ClientRequest_scrape;
		client->request.scrape = scrape;
		if ( ScrapeData_fromQuery( scrape, query, querySize ) ) {
			Client_replyErrorLen( client, "Invalid scrape request." );
			return;
		}

		MemoryStore_processScrape( client->server->memStore, client );

	} else {
		StringBuffer_append( client->writeBuffer, InvalidRoute, strlen( InvalidRoute ) );
		Client_reply( client );
	}
	#undef OkayRoute
	#undef InvalidRoute
}
Пример #28
0
int main(void) {
        StringBuffer_T sb;

        Bootstrap(); // Need to initialize library

        printf("============> Start StringBuffer Tests\n\n");

        printf("=> Test1: create/destroy\n");
        {
                sb= StringBuffer_new("");
                assert(sb);
                assert(StringBuffer_length(sb)==0);
                StringBuffer_free(&sb);
                assert(sb==NULL);
                sb= StringBuffer_create(1024);
                assert(sb);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test1: OK\n\n");

        printf("=> Test2: Append NULL value\n");
        {
                sb= StringBuffer_new("");
                assert(sb);
                StringBuffer_append(sb, NULL);
                assert(StringBuffer_length(sb)==0);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test2: OK\n\n");

        printf("=> Test3: Create with string\n");
        {
                sb= StringBuffer_new("abc");
                assert(sb);
                assert(StringBuffer_length(sb)==3);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test3: OK\n\n");

        printf("=> Test4: Append string value\n");
        {
                sb= StringBuffer_new("abc");
                assert(sb);
                printf("\tTesting StringBuffer_append:..");
                StringBuffer_append(sb, "def");
                assert(StringBuffer_length(sb)==6);
                printf("ok\n");
                printf("\tTesting StringBuffer_vappend:..");
                append(sb, "%c%s", 'g', "hi");
                assert(StringBuffer_length(sb)==9);
                assert(Str_isEqual(StringBuffer_toString(sb), "abcdefghi"));
                printf("ok\n");
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test4: OK\n\n");

        printf("=> Test5: trim\n");
        {
                sb= StringBuffer_new("\t 'foo bar' \n ");
                assert(Str_isEqual(StringBuffer_toString(StringBuffer_trim(sb)), "'foo bar'"));
                StringBuffer_clear(sb);
                StringBuffer_append(sb, "'foo bar'");
                StringBuffer_trim(sb);
                assert(Str_isEqual(StringBuffer_toString(sb), "'foo bar'"));
                StringBuffer_clear(sb);
                StringBuffer_append(sb, "\t \r \n  ");
                assert(Str_isEqual(StringBuffer_toString(StringBuffer_trim(sb)), ""));
                StringBuffer_free(&sb);
                sb = StringBuffer_create(10);
                StringBuffer_trim(sb);
                assert(StringBuffer_toString(sb)[0] == 0);
                StringBuffer_free(&sb);
        }
        printf("=> Test5: OK\n\n");

        printf("=> Test6: deleteFrom\n");
        {
                sb= StringBuffer_new("abcdefgh");
                assert(sb);
                StringBuffer_delete(sb,3);
                assert(StringBuffer_length(sb)==3);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test6: OK\n\n");

        printf("=> Test7: indexOf and lastIndexOf\n");
        {
                sb= StringBuffer_new("jan-henrik haukeland");
                assert(sb);
                assert(StringBuffer_indexOf(sb, "henrik")==4);
                assert(StringBuffer_indexOf(sb, "an")==1);
                assert(StringBuffer_indexOf(sb, "-")==3);
                assert(StringBuffer_lastIndexOf(sb, "an")==17);
                assert(StringBuffer_indexOf(sb, "")==-1);
                assert(StringBuffer_indexOf(sb, 0)==-1);
                assert(StringBuffer_indexOf(sb, "d")==19);
                assert(StringBuffer_indexOf(sb, "j")==0);
                assert(StringBuffer_lastIndexOf(sb, "d")==19);
                assert(StringBuffer_lastIndexOf(sb, "j")==0);
                assert(StringBuffer_lastIndexOf(sb, "x")==-1);
                assert(StringBuffer_indexOf(sb, "jane")==-1);
                assert(StringBuffer_indexOf(sb, "jan-henrik haukeland")==0);
                assert(StringBuffer_indexOf(sb, "haukeland")==11);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test7: OK\n\n");

        printf("=> Test8: length and clear\n");
        {
                sb= StringBuffer_new("jan-henrik haukeland");
                assert(sb);
                assert(StringBuffer_length(sb)==20);
                StringBuffer_clear(sb);
                assert(StringBuffer_length(sb)==0);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test8: OK\n\n");

        printf("=> Test9: toString value\n");
        {
                sb= StringBuffer_new("abc");
                assert(sb);
                StringBuffer_append(sb, "def");
                assert(Str_isEqual(StringBuffer_toString(sb), "abcdef"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test9: OK\n\n");

        printf("=> Test10: internal resize\n");
        {
                int i;
                sb= StringBuffer_new("");
                assert(sb);
                for (i= 0; i<1024; i++)
                        StringBuffer_append(sb, "a");
                assert(StringBuffer_length(sb)==1024);
                assert(StringBuffer_toString(sb)[1023]=='a');
                assert(StringBuffer_toString(sb)[1024]==0);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test10: OK\n\n");

        printf("=> Test11: substring\n");
        {
                sb= StringBuffer_new("jan-henrik haukeland");
                assert(sb);
                assert(Str_isEqual(StringBuffer_substring(sb, StringBuffer_indexOf(sb, "-")),
                                                 "-henrik haukeland"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test11: OK\n\n");

        printf("=> Test12: replace\n");
        {
                printf("\tNothing to replace\n");
                sb= StringBuffer_new("abc?def?");
                assert(sb);
                StringBuffer_replace(sb, "x", "$x");
                assert(Str_isEqual(StringBuffer_toString(sb), "abc?def?"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace and expand\n");
                sb= StringBuffer_new("abc?def?");
                assert(sb);
                StringBuffer_replace(sb, "?", "$x");
                assert(Str_isEqual(StringBuffer_toString(sb), "abc$xdef$x"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace and shrink\n");
                sb= StringBuffer_new("abc$xdef$x");
                assert(sb);
                StringBuffer_replace(sb, "$x", "?");
                assert(Str_isEqual(StringBuffer_toString(sb), "abc?def?"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace with empty string\n");
                sb= StringBuffer_new("abc$xdef$x");
                assert(sb);
                StringBuffer_replace(sb, "$x", "");
                assert(Str_isEqual(StringBuffer_toString(sb), "abcdef"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace with same length\n");
                sb= StringBuffer_new("foo bar baz foo bar baz");
                assert(sb);
                StringBuffer_replace(sb, "baz", "bar");
                assert(Str_isEqual(StringBuffer_toString(sb), "foo bar bar foo bar bar"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tRemove words and test traceback\n");
                sb= StringBuffer_new("foo bar baz foo foo bar baz");
                assert(sb);
                StringBuffer_replace(sb, "baz", "bar");
                assert(Str_isEqual(StringBuffer_toString(sb), "foo bar bar foo foo bar bar"));
                StringBuffer_replace(sb, "foo bar ", "");
                assert(Str_isEqual(StringBuffer_toString(sb), "bar foo bar"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace all elements\n");
                sb= StringBuffer_new("aaaaaaaaaaaaaaaaaaaaaaaa");
                assert(sb);
                StringBuffer_replace(sb, "a", "b");
                assert(Str_isEqual(StringBuffer_toString(sb), "bbbbbbbbbbbbbbbbbbbbbbbb"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace and expand with resize of StringBuffer\n");
                sb= StringBuffer_new("insert into(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) values (1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,01,2,3);");
                assert(sb);
                StringBuffer_replace(sb, "?", "$x");
                assert(Str_isEqual(StringBuffer_toString(sb), "insert into($x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x) values (1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,01,2,3);"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test12: OK\n\n");

        printf("============> StringBuffer Tests: OK\n\n");

        return 0;
}
Пример #29
0
/**
 * Read all processes to initialize the information tree.
 * @param reference  reference of ProcessTree
 * @return treesize > 0 if succeeded otherwise = 0.
 */
int initprocesstree_sysdep(ProcessTree_T **reference) {
    int                       treesize;
    char                      buf[_POSIX2_LINE_MAX];
    size_t                    size = sizeof(maxslp);
    int                       mib_proc[6] = {CTL_KERN, KERN_PROC, KERN_PROC_KTHREAD, 0, sizeof(struct kinfo_proc), 0};
    static int                mib_maxslp[] = {CTL_VM, VM_MAXSLP};
    ProcessTree_T            *pt;
    kvm_t                    *kvm_handle;
    static struct kinfo_proc *pinfo;

    if (sysctl(mib_maxslp, 2, &maxslp, &size, NULL, 0) < 0) {
        LogError("system statistic error -- vm.maxslp failed");
        return FALSE;
    }

    if (sysctl(mib_proc, 6, NULL, &size, NULL, 0) == -1) {
        LogError("system statistic error -- kern.proc #1 failed");
        return FALSE;
    }

    size *= 2; // Add reserve for new processes which were created between calls of sysctl
    pinfo = CALLOC(1, size);
    mib_proc[5] = (int)(size / sizeof(struct kinfo_proc));
    if (sysctl(mib_proc, 6, pinfo, &size, NULL, 0) == -1) {
        FREE(pinfo);
        LogError("system statistic error -- kern.proc #2 failed");
        return FALSE;
    }

    treesize = (int)(size / sizeof(struct kinfo_proc));

    pt = CALLOC(sizeof(ProcessTree_T), treesize);

    if (! (kvm_handle = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf))) {
        LogError("system statistic error -- kvm_openfiles failed: %s", buf);
        return FALSE;
    }

    for (int i = 0; i < treesize; i++) {
        pt[i].pid         = pinfo[i].p_pid;
        pt[i].ppid        = pinfo[i].p_ppid;
        pt[i].starttime   = pinfo[i].p_ustart_sec;
        pt[i].cputime     = (long)((pinfo[i].p_rtime_sec * 10) + (pinfo[i].p_rtime_usec / 100000));
        pt[i].cpu_percent = 0;
        pt[i].mem_kbyte   = (unsigned long)(pinfo[i].p_vm_rssize * pagesize_kbyte);
        if (pinfo[i].p_stat == SZOMB)
            pt[i].status_flag |= PROCESS_ZOMBIE; //FIXME: save system service flag too (kernel threads)
        pt[i].time = get_float_time();
        char **args;
        if ((args = kvm_getargv(kvm_handle, &pinfo[i], 0))) {
            StringBuffer_T cmdline = StringBuffer_create(64);;
            for (int j = 0; args[j]; j++)
                StringBuffer_append(cmdline, args[j + 1] ? "%s " : "%s", args[j]);
            pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline)));
            StringBuffer_free(&cmdline);
        }
        if (! pt[i].cmdline || ! *pt[i].cmdline)
            pt[i].cmdline = Str_dup(pinfo[i].p_comm);
    }
    FREE(pinfo);
    kvm_close(kvm_handle);

    *reference = pt;

    return treesize;
}
Пример #30
0
Файл: xml.c Проект: kemadz/monit
/**
 * Prints a service status into the given buffer.
 * @param S Service object
 * @param B StringBuffer object
 * @param L Status information level
 * @param V Format version
 */
static void status_service(Service_T S, StringBuffer_T B, Level_Type L, int V) {
        if (V == 2)
                StringBuffer_append(B, "<service name=\"%s\"><type>%d</type>", S->name ? S->name : "", S->type);
        else
                StringBuffer_append(B, "<service type=\"%d\"><name>%s</name>", S->type, S->name ? S->name : "");
        StringBuffer_append(B,
                            "<collected_sec>%lld</collected_sec>"
                            "<collected_usec>%ld</collected_usec>"
                            "<status>%d</status>"
                            "<status_hint>%d</status_hint>"
                            "<monitor>%d</monitor>"
                            "<monitormode>%d</monitormode>"
                            "<pendingaction>%d</pendingaction>",
                            (long long)S->collected.tv_sec,
                            (long)S->collected.tv_usec,
                            S->error,
                            S->error_hint,
                            S->monitor,
                            S->mode,
                            S->doaction);
        if (S->every.type != Every_Cycle) {
                StringBuffer_append(B, "<every><type>%d</type>", S->every.type);
                if (S->every.type == 1)
                        StringBuffer_append(B, "<counter>%d</counter><number>%d</number>", S->every.spec.cycle.counter, S->every.spec.cycle.number);
                else
                        StringBuffer_append(B, "<cron>%s</cron>", S->every.spec.cron);
                StringBuffer_append(B, "</every>");
        }

        if (L == Level_Full) {
                if (Util_hasServiceStatus(S)) {
                        switch (S->type) {
                                case Service_File:
                                        StringBuffer_append(B,
                                                "<mode>%o</mode>"
                                                "<uid>%d</uid>"
                                                "<gid>%d</gid>"
                                                "<timestamp>%lld</timestamp>"
                                                "<size>%llu</size>",
                                                S->inf->priv.file.mode & 07777,
                                                (int)S->inf->priv.file.uid,
                                                (int)S->inf->priv.file.gid,
                                                (long long)S->inf->priv.file.timestamp,
                                                (unsigned long long)S->inf->priv.file.size);
                                        if (S->checksum)
                                                StringBuffer_append(B, "<checksum type=\"%s\">%s</checksum>", checksumnames[S->checksum->type], S->inf->priv.file.cs_sum);
                                        break;

                                case Service_Directory:
                                        StringBuffer_append(B,
                                                "<mode>%o</mode>"
                                                "<uid>%d</uid>"
                                                "<gid>%d</gid>"
                                                "<timestamp>%lld</timestamp>",
                                                S->inf->priv.directory.mode & 07777,
                                                (int)S->inf->priv.directory.uid,
                                                (int)S->inf->priv.directory.gid,
                                                (long long)S->inf->priv.directory.timestamp);
                                        break;

                                case Service_Fifo:
                                        StringBuffer_append(B,
                                                "<mode>%o</mode>"
                                                "<uid>%d</uid>"
                                                "<gid>%d</gid>"
                                                "<timestamp>%lld</timestamp>",
                                                S->inf->priv.fifo.mode & 07777,
                                                (int)S->inf->priv.fifo.uid,
                                                (int)S->inf->priv.fifo.gid,
                                                (long long)S->inf->priv.fifo.timestamp);
                                        break;

                                case Service_Filesystem:
                                        StringBuffer_append(B,
                                                "<mode>%o</mode>"
                                                "<uid>%d</uid>"
                                                "<gid>%d</gid>"
                                                "<flags>%d</flags>"
                                                "<block>"
                                                "<percent>%.1f</percent>"
                                                "<usage>%.1f</usage>"
                                                "<total>%.1f</total>"
                                                "</block>",
                                                S->inf->priv.filesystem.mode & 07777,
                                                (int)S->inf->priv.filesystem.uid,
                                                (int)S->inf->priv.filesystem.gid,
                                                S->inf->priv.filesystem.flags,
                                                S->inf->priv.filesystem.space_percent,
                                                S->inf->priv.filesystem.f_bsize > 0 ? (double)S->inf->priv.filesystem.space_total / 1048576. * (double)S->inf->priv.filesystem.f_bsize : 0.,
                                                S->inf->priv.filesystem.f_bsize > 0 ? (double)S->inf->priv.filesystem.f_blocks / 1048576. * (double)S->inf->priv.filesystem.f_bsize : 0.);
                                        if (S->inf->priv.filesystem.f_files > 0) {
                                                StringBuffer_append(B,
                                                        "<inode>"
                                                        "<percent>%.1f</percent>"
                                                        "<usage>%lld</usage>"
                                                        "<total>%lld</total>"
                                                        "</inode>",
                                                        S->inf->priv.filesystem.inode_percent,
                                                        S->inf->priv.filesystem.inode_total,
                                                        S->inf->priv.filesystem.f_files);
                                        }
                                        break;

                                case Service_Net:
                                        StringBuffer_append(B,
                                                "<link>"
                                                "<state>%d</state>"
                                                "<speed>%lld</speed>"
                                                "<duplex>%d</duplex>"
                                                "<download>"
                                                "<packets>"
                                                "<now>%lld</now>"
                                                "<total>%lld</total>"
                                                "</packets>"
                                                "<bytes>"
                                                "<now>%lld</now>"
                                                "<total>%lld</total>"
                                                "</bytes>"
                                                "<errors>"
                                                "<now>%lld</now>"
                                                "<total>%lld</total>"
                                                "</errors>"
                                                "</download>"
                                                "<upload>"
                                                "<packets>"
                                                "<now>%lld</now>"
                                                "<total>%lld</total>"
                                                "</packets>"
                                                "<bytes>"
                                                "<now>%lld</now>"
                                                "<total>%lld</total>"
                                                "</bytes>"
                                                "<errors>"
                                                "<now>%lld</now>"
                                                "<total>%lld</total>"
                                                "</errors>"
                                                "</upload>"
                                                "</link>",
                                                Link_getState(S->inf->priv.net.stats),
                                                Link_getSpeed(S->inf->priv.net.stats),
                                                Link_getDuplex(S->inf->priv.net.stats),
                                                Link_getPacketsInPerSecond(S->inf->priv.net.stats),
                                                Link_getPacketsInTotal(S->inf->priv.net.stats),
                                                Link_getBytesInPerSecond(S->inf->priv.net.stats),
                                                Link_getBytesInTotal(S->inf->priv.net.stats),
                                                Link_getErrorsInPerSecond(S->inf->priv.net.stats),
                                                Link_getErrorsInTotal(S->inf->priv.net.stats),
                                                Link_getPacketsOutPerSecond(S->inf->priv.net.stats),
                                                Link_getPacketsOutTotal(S->inf->priv.net.stats),
                                                Link_getBytesOutPerSecond(S->inf->priv.net.stats),
                                                Link_getBytesOutTotal(S->inf->priv.net.stats),
                                                Link_getErrorsOutPerSecond(S->inf->priv.net.stats),
                                                Link_getErrorsOutTotal(S->inf->priv.net.stats));
                                        break;

                                case Service_Process:
                                        StringBuffer_append(B,
                                                "<pid>%d</pid>"
                                                "<ppid>%d</ppid>"
                                                "<uid>%d</uid>"
                                                "<euid>%d</euid>"
                                                "<gid>%d</gid>"
                                                "<uptime>%lld</uptime>",
                                                S->inf->priv.process.pid,
                                                S->inf->priv.process.ppid,
                                                S->inf->priv.process.uid,
                                                S->inf->priv.process.euid,
                                                S->inf->priv.process.gid,
                                                (long long)S->inf->priv.process.uptime);
                                        if (Run.flags & Run_ProcessEngineEnabled) {
                                                StringBuffer_append(B,
                                                        "<threads>%d</threads>"
                                                        "<children>%d</children>"
                                                        "<memory>"
                                                        "<percent>%.1f</percent>"
                                                        "<percenttotal>%.1f</percenttotal>"
                                                        "<kilobyte>%llu</kilobyte>"
                                                        "<kilobytetotal>%llu</kilobytetotal>"
                                                        "</memory>"
                                                        "<cpu>"
                                                        "<percent>%.1f</percent>"
                                                        "<percenttotal>%.1f</percenttotal>"
                                                        "</cpu>",
                                                        S->inf->priv.process.threads,
                                                        S->inf->priv.process.children,
                                                        S->inf->priv.process.mem_percent,
                                                        S->inf->priv.process.total_mem_percent,
                                                        (unsigned long long)((double)S->inf->priv.process.mem / 1024.),       // Send as kB for backward compatibility
                                                        (unsigned long long)((double)S->inf->priv.process.total_mem / 1024.), // Send as kB for backward compatibility
                                                        S->inf->priv.process.cpu_percent,
                                                        S->inf->priv.process.total_cpu_percent);
                                        }
                                        break;

                                default:
                                        break;
                        }
                        for (Icmp_T i = S->icmplist; i; i = i->next) {
                                StringBuffer_append(B,
                                                    "<icmp>"
                                                    "<type>%s</type>"
                                                    "<responsetime>%.6f</responsetime>"
                                                    "</icmp>",
                                                    icmpnames[i->type],
                                                    i->is_available == Connection_Ok ? i->response / 1000. : -1.); // We send the response time in [s] for backward compatibility (with microseconds precision)
                        }
                        for (Port_T p = S->portlist; p; p = p->next) {
                                StringBuffer_append(B,
                                                    "<port>"
                                                    "<hostname>%s</hostname>"
                                                    "<portnumber>%d</portnumber>"
                                                    "<request><![CDATA[%s]]></request>"
                                                    "<protocol>%s</protocol>"
                                                    "<type>%s</type>"
                                                    "<responsetime>%.6f</responsetime>"
                                                    "</port>",
                                                    p->hostname ? p->hostname : "",
                                                    p->target.net.port,
                                                    Util_portRequestDescription(p),
                                                    p->protocol->name ? p->protocol->name : "",
                                                    Util_portTypeDescription(p),
                                                    p->is_available == Connection_Ok ? p->response / 1000. : -1.); // We send the response time in [s] for backward compatibility (with microseconds precision)
                        }
                        for (Port_T p = S->socketlist; p; p = p->next) {
                                StringBuffer_append(B,
                                                    "<unix>"
                                                    "<path>%s</path>"
                                                    "<protocol>%s</protocol>"
                                                    "<responsetime>%.6f</responsetime>"
                                                    "</unix>",
                                                    p->target.unix.pathname ? p->target.unix.pathname : "",
                                                    p->protocol->name ? p->protocol->name : "",
                                                    p->is_available == Connection_Ok ? p->response / 1000. : -1.); // We send the response time in [s] for backward compatibility (with microseconds precision)
                        }
                        if (S->type == Service_System && (Run.flags & Run_ProcessEngineEnabled)) {
                                StringBuffer_append(B,
                                                    "<system>"
                                                    "<load>"
                                                    "<avg01>%.2f</avg01>"
                                                    "<avg05>%.2f</avg05>"
                                                    "<avg15>%.2f</avg15>"
                                                    "</load>"
                                                    "<cpu>"
                                                    "<user>%.1f</user>"
                                                    "<system>%.1f</system>"
#ifdef HAVE_CPU_WAIT
                                                    "<wait>%.1f</wait>"
#endif
                                                    "</cpu>"
                                                    "<memory>"
                                                    "<percent>%.1f</percent>"
                                                    "<kilobyte>%llu</kilobyte>"
                                                    "</memory>"
                                                    "<swap>"
                                                    "<percent>%.1f</percent>"
                                                    "<kilobyte>%llu</kilobyte>"
                                                    "</swap>"
                                                    "</system>",
                                                    systeminfo.loadavg[0],
                                                    systeminfo.loadavg[1],
                                                    systeminfo.loadavg[2],
                                                    systeminfo.total_cpu_user_percent > 0. ? systeminfo.total_cpu_user_percent : 0.,
                                                    systeminfo.total_cpu_syst_percent > 0. ? systeminfo.total_cpu_syst_percent : 0.,
#ifdef HAVE_CPU_WAIT
                                                    systeminfo.total_cpu_wait_percent > 0. ? systeminfo.total_cpu_wait_percent : 0.,
#endif
                                                    systeminfo.total_mem_percent,
                                                    (unsigned long long)((double)systeminfo.total_mem / 1024.),               // Send as kB for backward compatibility
                                                    systeminfo.total_swap_percent,
                                                    (unsigned long long)((double)systeminfo.total_swap / 1024.));             // Send as kB for backward compatibility
                        }
                        if (S->type == Service_Program && S->program->started) {
                                StringBuffer_append(B,
                                                    "<program>"
                                                    "<started>%lld</started>"
                                                    "<status>%d</status>"
                                                    "<output><![CDATA[",
                                                    (long long)S->program->started,
                                                    S->program->exitStatus);
                                _escapeCDATA(B, StringBuffer_toString(S->program->output));
                                StringBuffer_append(B,
                                                    "]]></output>"
                                                    "</program>");
                        }
                }
        }
        StringBuffer_append(B, "</service>");
}