Beispiel #1
0
/** Unmarshals the content of buffer into an array of values of size
 * value_count.
 *
 * If the returned number is negative, there were more values than could fit in
 * the array in the buffer, and some were skipped.  This number (when
 * multiplied by -1) indicates  by how much the values array should be
 * extended. If the number is less than
 * -100, it indicates an error.
 *
 * \param mbuf MBuffer to read from
 * \param header pointer to an OmlBinaryHeader corresponding to this message
 * \param values array of OmlValue to be filled
 * \param max_value_count length of the array (XXX: Should be < 100, otherwise confusion may happen with error returns)
 * \return the number of values found (positive), or the number of values that didn't fit in the array (negative; multiplied by -1), <-100 in case of error
 * \see unmarshal_init
 */
int
unmarshal_values(MBuffer* mbuf, OmlBinaryHeader* header, OmlValue* values, int max_value_count)
{
  int value_count = header->values;

  if (0 == value_count) {
    logwarn("No value to unmarshall\n");
    return -102;
  }

  if (value_count > max_value_count) {
    logwarn("Measurement packet contained %d too many values for internal storage (max %d, actual %d); skipping packet\n",
           (value_count - max_value_count), max_value_count, value_count);
    logwarn("Message length appears to be %d + 5\n", header->length);

    mbuf_read_skip (mbuf, header->length + PACKET_HEADER_SIZE);
    mbuf_begin_read (mbuf);

    // FIXME:  Check for sync
    return max_value_count - value_count;  // value array is too small
  }

  int i;
  OmlValue* val = values;
  for (i = 0; i < value_count; i++) {
    if (unmarshal_value(mbuf, &val[i]) == 0) {
      logwarn("Could not unmarshal values %d of %d\n", i, value_count);
      return -101;
    }
  }
  return value_count;
}
Beispiel #2
0
/** Get the name (address+service) of an OSocket.
 *
 * \param s OSocket
 * \param name memory buffer to return the string in (nil-terminated)
 * \param namelen length of name, using socket_get_addr_sz() is a good idea
 * \param remote 0 if the local name is needed, non-zero for the remote peer
 *
 * \see sockaddr_get_name, getsockname(3), socket_get_addr_sz
 */
void
socket_get_name(Socket *s, char *name, size_t namelen, int remote)
{
  sockaddr_t sa;
  socklen_t sa_len = sizeof(sa);
  SocketInt *self = (SocketInt*) s;

  assert(self);
  assert(name);
  assert(self->sockfd);

  memset(&sa, 0, sa_len);

  if(remote) {
    if(!getpeername(self->sockfd, &sa.sa, &sa_len)) {
      sockaddr_get_name(&sa, sa_len, name, namelen);

    } else {
      logwarn("%s: Cannot get details of socket peer: %s", s->name, strerror(errno));
      *name = 0;
    }

  } else {
    if(!getsockname(self->sockfd, &sa.sa, &sa_len)) {
      sockaddr_get_name(&sa, sa_len, name, namelen);

    } else {
      logwarn("%s: Cannot get details of socket: %s", s->name, strerror(errno));
      *name = 0;
    }
  }

}
Beispiel #3
0
/*
 * Convert interface names to IDs
 * Args: Pointer to engine output filter, pointer to initialized interface list
 * Returns: -1 on failure, 0 on success
 */
int name2id(sfilter_t *filter)
{
    unsigned int id;
    sf_rule_t *rptr;
    struct srclist *sptr;

    if (!filter)
        return(0);

    if (filter->type == FILTER) {
        for (rptr=filter->rules;rptr;rptr=rptr->next) {
            if (rptr->src.name == NULL)
                continue;
            if (!(id=namelookup(rptr->src.name))) {
                logwarn("Unknown interface \'%s\' in filter rules",rptr->src.name);
                return(-1);
            }
            free(rptr->src.name);
            rptr->src.id=id;
        }
        return(0);
    }
    
    for (rptr=filter->rules;rptr;rptr=rptr->next)
        for (sptr=rptr->info.source;sptr;sptr=sptr->next) {
            if (!(id=namelookup(sptr->src.name))) {
               logwarn("Unknown interface \'%s\' in failover rules",sptr->src.name);
                return(-1);
            }
            free(sptr->src.name);
            sptr->src.id=id;
        }
    return(0);
}
Beispiel #4
0
/* process new job request from web */
static int __process_web_job(char * buf, int size, int ent_id)
{
    logdebug(_("%s called\n"), __func__);

    if (size != sizeof(int32_t)) {
        logerror(_("unexpected web job data size\n"));
        return -1;
    }

    int job_id = *(int32_t *)buf;
    logdebug(_("web job id %d\n"), job_id);

    LYJobInfo *job = malloc(sizeof(LYJobInfo));
    if (job == NULL) {
        logerror(_("error in %s(%d)\n"), __func__, __LINE__);
        return -1;
    }

    job->j_id = job_id;
    if (db_job_get(job) != 0) {
        logerror(_("error in %s(%d)\n"), __func__, __LINE__);
        free(job);
        return -1;
    }

    if (job_exist(job)){
        logwarn(_("job %d exists already\n"), job_id);
        free(job);
        return 0;
    }

    int ret = job_check(job);
    if (ret){
        logwarn(_("job check for job %d returns %d\n"), job_id, ret);
        if (!JOB_IS_CANCELLED(ret))
            ret = LY_S_CANCEL_INTERNAL_ERROR;
        /* can not use job_remove */
        time(&job->j_started);
        time(&job->j_ended);
        job->j_status = ret;
        db_job_update_status(job);
        free(job);
        return 0;
    }

    if (job_insert(job) != 0) {
        logerror(_("error in %s(%d)\n"), __func__, __LINE__);
        time(&job->j_started);
        time(&job->j_ended);
        job->j_status = LY_S_CANCEL_INTERNAL_ERROR;
        db_job_update_status(job);
        free(job);
        return -1;
    }

    return 0;
}
Beispiel #5
0
/** Assign the content of an OmlValueU of the given OmlValueT to an OmlValue.
 *
 * This function copies value, which is assumed to be of the given type (no
 * check can be made), into the OmlValue pointed to by to.  The to object is
 * set to have the given type. If type is a simple numeric type, the copy
 * simply copies the value.
 *
 * If type is OML_STRING_VALUE, then the string contents are copied into new
 * storage in to.  If to was previously set to be a const string, then the
 * is_const flag is cleared and a new block of memory is allocated to store the
 * copy and its terminating null character. If to did not previously have the
 * is_const flag set, and its string pointer was NULL, then a new block of
 * memory is also allocated as well.  If the string pointer was not NULL, then
 * the string is copied into the previously allocated memory block if it is
 * large enough to fit; otherwise the block is freed and a new one allocated
 * large enough to hold the string (and its terminator).
 *
 * Blobs are handled in a similar fashion.
 *
 * If the source pointer is NULL then an error is returned and a warning
 * message is sent to the log.
 *
 * \param to pointer to OmlValue into which the value should be copied
 * \param value pointer to original OmlValueU to copy into to
 * \param type OmlValueT of value
 * \return 0 if successful, -1 otherwise
 * \see oml_value_init, omlc_copy_string, omlc_copy_blob
 */
int
oml_value_set(OmlValue *to, const OmlValueU *value, OmlValueT type)
{
    oml_value_set_type(to, type);
    if (omlc_is_numeric_type (type) ||
            omlc_is_guid_type (type) ||
            omlc_is_bool_type (type)) {
        to->value = *value;
    } else {
        switch (type) {
        case OML_STRING_VALUE:
            if (!omlc_get_string_ptr(*value)) {
                logwarn("Trying to copy OML_STRING_VALUE from a NULL source\n");
                return -1;
            }
            omlc_copy_string(*oml_value_get_value(to), *value);
            break;

        case OML_DATETIME_VALUE:
            if (!omlc_get_string_ptr(*value)) {
                logwarn("Trying to copy OML_DATETIME_VALUE from a NULL source\n");
                return -1;
            }
            omlc_copy_string(*oml_value_get_value(to), *value);
            break;

        case OML_BLOB_VALUE:
            if (!omlc_get_blob_ptr(*value)) {
                logwarn("Trying to copy OML_BLOB_VALUE from a NULL source\n");
                return -1;
            }
            omlc_copy_blob(*oml_value_get_value(to), *value);
            break;

        case OML_VECTOR_DOUBLE_VALUE:
        case OML_VECTOR_INT32_VALUE:
        case OML_VECTOR_UINT32_VALUE:
        case OML_VECTOR_INT64_VALUE:
        case OML_VECTOR_UINT64_VALUE:
        case OML_VECTOR_BOOL_VALUE:
            if (!omlc_get_vector_ptr(*value)) {
                logwarn("Trying to copy OML_VECTOR_*_VALUE from a NULL source\n");
                return -1;
            }
            omlc_copy_vector(*oml_value_get_value(to), *value);
            break;

        default:
            logerror("%s() for type '%d' not implemented'\n", __FUNCTION__, type);
            return -1;
        }
    }
    return 0;
}
Beispiel #6
0
/** Initialise adapters for a new database
 *
 * If the database already has tables, initialise the adapters.
 *
 * \param database main Database object
 * \return 0 on success, -1 otherwise
 *
 * \see database_create_table, db_adapter_table_create
 */
int
database_init (Database *database)
{
  int num_tables;
  TableDescr* tables = database->get_table_list (database, &num_tables);
  if (!database->semantic)
  {
    TableDescr* td = tables;

    if (num_tables == -1)
      return -1;

    logdebug("%s: Got table list with %d tables in it\n", database->name, num_tables);
    int i = 0;
    for (i = 0; i < num_tables; i++, td = td->next) {
      if (td->schema) {
        struct schema *schema = schema_copy (td->schema);
        DbTable *table = database_create_table (database, schema);

        if (!table) {
          logwarn ("%s: Failed to create table '%s'\n",
                   database->name, td->name);
          continue;
        }
        /* Create the required table data structures, but don't do SQL CREATE TABLE */
        if (database->table_create (database, table, 1) == -1) {
          logwarn ("%s: Failed to create adapter structures for table '%s'\n",
                   database->name, td->name);
          database_table_free (database, table);
        }
      }
    }

    /* Create default tables if they are not already present in the 'tables' list */
    const char *meta_tables [] = { "_senders", "_experiment_metadata" };
    size_t j;
    for (j = 0; j < LENGTH(meta_tables); j++) {
      if (!table_descr_have_table (tables, meta_tables[j])) {
        if (database->table_create_meta (database, meta_tables[j])) {
          table_descr_list_free (tables);
          logerror("%s: Could not create default table %s\n",
              database->name, meta_tables[j]);
          return -1;
        }
      }
    }

    table_descr_list_free (tables);
  }
  return 0;
}
Beispiel #7
0
/** Actually install a new signal handler.
 *
 * \see sigaction(3)
 */
static void signal_install(sh_t handler)
{
  struct sigaction sa;

  sa.sa_handler = (void(*) (int))handler;
  sigemptyset (&sa.sa_mask);
  sa.sa_flags = 0;

  if(sigaction(SIGTERM, &sa, NULL))
    logwarn("Unable to install SIGTERM handler: %s\n", strerror(errno));
  if(sigaction(SIGINT, &sa, NULL))
    logwarn("Unable to install SIGINT handler: %s\n", strerror(errno));
  if(sigaction(SIGUSR1, &sa, NULL))
    logwarn("Unable to install SIGUSR1 handler: %s\n", strerror(errno));
}
Beispiel #8
0
void
run(opts_t *opts, oml_mps_t *oml_mps)
{
  long val = 1;
  struct sigaction sa;
  int i;
  FILE *fp;
  int rx = 10;
  char *string;

  bzero(&sa, sizeof(struct sigaction));
  sa.sa_handler = sighandler;
  sigaction(SIGINT, &sa, NULL);
  
  for(i=0;i<100; i++)
   {
     system("ifconfig eth0 | grep bytes | awk '{print $2}' | cut -c 1-6 --complement > traffic.txt");
     fp = fopen("traffic.txt","r");    // caculating total traffic
	 string = readFile(fp);
	 rx = atoi(string);
     fclose(fp);
     oml_inject_sensor(oml_mps->sensor,rx);
   }

  do {
    /* The oml_inject_MPNAME() helpers are defined in generator_oml.h*/
    if(oml_inject_sensor(oml_mps->sensor, ((int32_t)-val)) != 0) {
      logwarn("Failed to inject data into MP 'sensor'\n");
    }

    val += 2;
    sleep(1);
  } while (loop);
}
Beispiel #9
0
int libvirt_connect(int driver)
{
    if (g_conn != NULL) {
        logwarn(_("conneted already.\n"));
        return -1;
    }

    virSetErrorFunc(NULL, __customErrorFunc);

    const char * URI;
    if (driver == HYPERVISOR_IS_KVM)
        URI = HYPERVISOR_URI_KVM;
    else if (driver == HYPERVISOR_IS_XEN)
        URI = HYPERVISOR_URI_XEN;
    else {
        logerror(_("unrecognized hypervisor driver(%d).\n"), driver);
        return -1;
    }

    __this_lock();
    g_conn = virConnectOpen(URI);
    __this_unlock();
    if (g_conn == NULL) {
        logerror(_("Connet to %s error.\n"), URI);
        return -1;
    } 
    else {
        loginfo(_("Connect to %s success!\n"), URI);
    }

    return 0;
}
/*=========================================================================*\
      Get boolean value from repository 
         return false on error of if key is not found
\*=========================================================================*/
bool persistGetBool( const char *key )
{
  json_t *jObj;

  DBGMSG( "persistGetBool: (%s)", key ); 
    
/*------------------------------------------------------------------------*\
    Get Object
\*------------------------------------------------------------------------*/
  jObj = persistGetJSON( key );
  if( !jObj ) {
  	DBGMSG( "persistGetBool: (%s) not set", key );
    return false;  
  }
  
/*------------------------------------------------------------------------*\
    Check type
\*------------------------------------------------------------------------*/
  if( !json_is_true(jObj) && !json_is_false(jObj) ) {
     logwarn( "Value for key \"%s\" is not a boolean (%d): ", 
                          key, json_typeof(jObj) );
     return false;
  }  

/*------------------------------------------------------------------------*\
    return real value 
\*------------------------------------------------------------------------*/
  bool value = json_is_true( jObj );
  DBGMSG( "persistGetBool: (%s)=%s", key, value?"True":"False" ); 
  return value;
}
Beispiel #11
0
ssize_t pkv_serialize(struct pkv *p)
{
	size_t payload_sz = dict_serialized_size(p->payload);
	size_t sz = sizeof(*(p->pkt)) + payload_sz;

	if(p->pkt)
		logwarn("serializing over non-NULL p->pkt : %p\n", p->pkt);

	if((p->pkt = malloc(sz)) == NULL) {
		logerror("could not serialize pkv : %s\n", strerror(errno));
		return -1;
	}
	p->pkt_size = sz;

	/* fill in header */
	p->pkt->magic[0] = 'P';
	p->pkt->magic[1] = 'K';
	p->pkt->magic[2] = 'V';
	p->pkt->version = PKV_VERSION;
	p->pkt->type = p->type;
	p->pkt->length = payload_sz;
	p->pkt->checksum = pkv_calc_checksum(p->pkt);

	/* fill in payload */
	if(dict_serialize_into(p->payload, p->pkt->payload) < 0) {
		logerror("could not serialize pkv payload\n");
		free(p->pkt);
		p->pkt = NULL;
		p->pkt_size = 0;
		return -1;
	}

	return sz;
}
Beispiel #12
0
// Create some logs
void create_logs() {
	logtrace(1 << " logtrace");
	logtraceEx(1 << " logtraceEx", 
			std::make_shared<LogValExtraExample>("logtraceEx_", 100));

	logdebug(2 << " logdebug");
	logdebugEx(2 << " logdebugEx", 
			std::make_shared<LogValExtraExample>("logdebugEx_", 200));

	loginfo(3 << " loginfo");
	loginfoEx(3 <<" loginfoEx", 
			std::make_shared<LogValExtraExample>("loginfoEx_", 300));

	logwarn(4 << " logwarn");
	logwarnEx(4 << " logwarnEx", 
			std::make_shared<LogValExtraExample>("logwarnEx_", 400));
	
	logerror(5 << " logerror");
	logerrorEx(5 << " logerrorEx", 
			std::make_shared<LogValExtraExample>("logerrorEx_", 500));

	logfatal(6 << " logfatal");
	logfatalEx(6 << " logfatalEx", 
			std::make_shared<LogValExtraExample>("logfatalEx_", 600));

	// mylevel
	make_mylevel();
	logging(makelevel(MyLevel1), "7 test MyLevel1", log_tools::get_pid(),
			__func__, __FILE__, __LINE__);
	logging(makelevel(MyLevel2), "7 test MyLevel2", log_tools::get_pid(),
			__func__, __FILE__, __LINE__, 
			std::make_shared<LogValExtraExample>("test MyLevel2", 700));
}
Beispiel #13
0
int main(int argc, char **argv)
{
    const char *device = "lo";
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t * pcap;

    typhoon_t * typhoon;

    pcap = pcap_open_live(device, 65535, 0, 0, errbuf);
    if (!pcap)
    {
        logerror("error: pcap_open_live(): %s\n", errbuf);
        exit(-1);
    }

    typhoon = malloc(sizeof(typhoon_t));
    typhoon->linktype = pcap_datalink(pcap);
    typhoon->pcap = pcap;
    typhoon->network_type_offset = network_type_offset(pcap_datalink(pcap));

    logwarn("linktype: %d\n", typhoon->linktype);
    pcap_loop(pcap, -1, handler, (u_char *)typhoon);

    pcap_close(pcap);

    return 0;
}
Beispiel #14
0
static void handler(u_char *arg, const struct pcap_pkthdr *pkthdr,
        const u_char *packet)
{
#define typh ((typhoon_t *)arg)
    u_short network_type;
    struct header_ip *hdip;
    u_short tcp_len;

    if (pkthdr->caplen != pkthdr->len)
    {
        logwarn("This pkt the date get is short.\n");
        return;
    }

    network_type = *(u_short *)(packet + typh->network_type_offset);
    network_type = ntohs(network_type);

    if (NETWORK_TYPE_IP != network_type)  return;
    // now all IP packet

    hdip = (struct header_ip *)(packet + typh->network_type_offset + 2);
    if (TRANSPORT_TYPE_TCP != hdip->ip_p) return;
    // now all tcp packet
    
    tcp_len = ntohs(hdip->ip_len) - IP_HL(hdip);

    logerror("network type: %d\n", network_type);

#undef typh
}
Beispiel #15
0
static void listener_thread(struct ctrlthread *thread)
{
	struct net_listener *l = (struct net_listener *)thread->priv;
	int e;
	struct pollfd listenpoll;

	/* Setup the poll */
	listenpoll.fd = l->sock;
	listenpoll.events = POLLIN;
	listenpoll.revents = 0;

	e = poll(&listenpoll, 1, 200);
	if(e == 0) {
		/* nothing to do */
	} else if(e < 0) {
		/* error */
		logwarn("poll returned an error: %s\n", strerror(errno));
	} else {
		/* client is trying to connect */
		listener_accept_connection(l);
	}

	if(l->shutdown) {
		logdebug("shutting down listener\n");
		close(l->sock);
		l->sock = -1;
		thread->shutdown = 1;
		pthread_mutex_unlock(&l->listener_lock);
	}
}
Beispiel #16
0
int handleaccept(int efd, int fd)
{
  char logbuf[256];
  char addrbuf[64];
  struct sockaddr_in sain;
  socklen_t sl = sizeof(sain);
  int requestfd;
  while(1){
    requestfd = accept(fd,(struct sockaddr *)&sain,&sl);
    if(requestfd == -1){
      if(errno == EINTR) continue;
      else break;
    }
    else{
      inet_ntop(AF_INET, &sain.sin_addr, addrbuf, sizeof(addrbuf));
      sprintf(logbuf, "recieve a request from %s.\n", addrbuf);
      loginfo(logbuf);
      setnonblock(requestfd);
      if(addtoepoll(efd, requestfd, ETINOUT) != 0){
	logwarn("epoll add request fd error.\n");
	close(requestfd);
	continue;
      }
    }
  }
  return 0;
}
/*=========================================================================*\
      Get real number from repository 
         return 0.0 on error of if key is not found
\*=========================================================================*/
double persistGetReal( const char *key )
{
  json_t *jObj;
    
/*------------------------------------------------------------------------*\
    Get Object
\*------------------------------------------------------------------------*/
  jObj = persistGetJSON( key );
  if( !jObj ) {
  	DBGMSG( "persistGetReal: (%s) not set", key );
    return 0;  
  }

/*------------------------------------------------------------------------*\
    Check type
\*------------------------------------------------------------------------*/
  if( !json_is_real(jObj) ) {
     logwarn( "Value for key \"%s\" is not a real number (%d): ", 
                          key, json_typeof(jObj) );
     return 0;
  }  

/*------------------------------------------------------------------------*\
    return real value 
\*------------------------------------------------------------------------*/
  double value = json_real_value( jObj );
  DBGMSG( "persistGetReal: (%s)=%g", key, value ); 
  return value;
}
Beispiel #18
0
/** Close an output stream and destroy the objects.
 *
 * \param instance handle (i.e., pointer) to a BufferedWriter
 */
void
bw_close(BufferedWriter* instance)
{
  int *retval;
  BufferedWriter *self = (BufferedWriter*)instance;

  if(!self) { return; }

  if (oml_lock (&self->lock, __FUNCTION__)) { return; }
  self->active = 0;

  loginfo ("%s: Waiting for buffered queue thread to drain...\n", self->outStream->dest);

  pthread_cond_signal (&self->semaphore);
  oml_unlock (&self->lock, __FUNCTION__);

  if(pthread_join (self->readerThread, (void**)&retval)) {
    logwarn ("%s: Cannot join buffered queue reader thread: %s\n",
        self->outStream->dest, strerror(errno));

  } else {
    if (1 == *retval) {
      logdebug ("%s: Buffered queue fully drained\n", self->outStream->dest);
    } else {
      logerror ("%s: Buffered queue did not fully drain\n",
          self->outStream->dest, *retval);
    }
  }

  self->outStream->close(self->outStream);
  destroyBufferChain(self);
  oml_free(self);
}
/*=========================================================================*\
      Get integer number from repository 
         return 0 on error of if key is not found
\*=========================================================================*/
int persistGetInteger( const char *key )
{
  json_t *jObj;
    
/*------------------------------------------------------------------------*\
    Get Object
\*------------------------------------------------------------------------*/
  jObj = persistGetJSON( key );
  if( !jObj ) {
  	DBGMSG( "persistGetInteger: (%s) not set", key );
    return 0;  
  }

/*------------------------------------------------------------------------*\
    Check type
\*------------------------------------------------------------------------*/
  if( !json_is_integer(jObj) ) {
     logwarn( "Value for key \"%s\" is not an integer (%d): ", 
             key, json_typeof(jObj) );
     return 0;
  }  

/*------------------------------------------------------------------------*\
    return integer value 
\*------------------------------------------------------------------------*/
  int value = json_integer_value( jObj );  
  DBGMSG( "persistGetInteger: (%s)=%d", key, value ); 
  return value;
}
/*=========================================================================*\
      Get String object from repository 
         Returns NULL on error or if key is not found
         String reference is only good until the key or repository changes!
         So you might copy it for longer usage. 
\*=========================================================================*/
const char *persistGetString( const char *key )
{
  json_t *jObj;
    
/*------------------------------------------------------------------------*\
    Get Object
\*------------------------------------------------------------------------*/
  jObj = persistGetJSON( key );
  if( !jObj ) {
  	DBGMSG( "persistGetString: (%s) not set", key );
    return NULL;  
  }


/*------------------------------------------------------------------------*\
    Check type
\*------------------------------------------------------------------------*/
  if( !json_is_string(jObj) ) {
     logwarn( "Value for key \"%s\" is not a string (%d): ", 
                          key, json_typeof(jObj) );
     return NULL;
  }  

/*------------------------------------------------------------------------*\
    return string value as reference
\*------------------------------------------------------------------------*/
  const char *value = json_string_value( jObj );
  DBGMSG( "persistGetString: (%s)=\"%s\"", key, value?value:"(null)" );
  return value;
}
/*=========================================================================*\
      Remove a key:value entry from repository
        return -1 if key was not found or on error
\*=========================================================================*/
int persistRemove( const char *key )
{
  DBGMSG( "persistRemove: (%s)", key ); 

/*------------------------------------------------------------------------*\
    Repository needs to be available
\*------------------------------------------------------------------------*/
  if( !jRepository ) {
    logwarn( "Try to remove key \"%s\" from uninitialized repository.", 
                          key );
    return -1;
  }

/*------------------------------------------------------------------------*\
    Store or replace value in repository, steal reference
\*------------------------------------------------------------------------*/
  if( json_object_del(jRepository,key) ) {
    logerr( "Cannot remove key \"%s\" from repository.", key );
    return -1;
  }

/*------------------------------------------------------------------------*\
    Dump repository, that's it
\*------------------------------------------------------------------------*/
  return _dumpRepository( repositoryFileName );
}
/*=========================================================================*\
      Store JSON value in repository, steal reference 
\*=========================================================================*/
int persistSetJSON_new( const char *key, json_t *value )
{
  DBGMSG( "persistSetJSON_new: (%s)", key ); 
   
/*------------------------------------------------------------------------*\
    Create repository if not available
\*------------------------------------------------------------------------*/
  if( !jRepository ) {
    logwarn( "Set value in uninitialized repository: \"%s\"", key );
    jRepository = json_object();
  }
  if( !jRepository ) {
    logerr( "Could not create repository object." );
    return -1;
  }

/*------------------------------------------------------------------------*\
    Store or replace value in repository, steal reference
\*------------------------------------------------------------------------*/
  if( json_object_set(jRepository,key,value) ) {
    logerr( "Cannot add vlaue for key \"%s\" to repository.", key );
    return -1;  
  }
  
/*------------------------------------------------------------------------*\
    Dump repository, that's it
\*------------------------------------------------------------------------*/
  return _dumpRepository( repositoryFileName );
}
Beispiel #23
0
/*=========================================================================*\
  Get HTTP log info
    this includes a corresponding HTTP header
    returns an allocated string (caller must free) or NULL on error
\*=========================================================================*/
char *_ickP2pGetLogFile( ickP2pContext_t *ictx, const char *uri )
{
  int          level = 7;
  char        *logContent;
  int          dlen, hlen;
  char        *message;
  char         header[512];

  debug( "_ickP2pGetLogFile (%p): \"%s\"", ictx, uri );

/*------------------------------------------------------------------------*\
    Get minimum log level from path
\*------------------------------------------------------------------------*/
  if( strlen(uri)>strlen(ICK_P2PLOGURI) ) {
    const char *ptr = uri + strlen(ICK_P2PLOGURI);
    char       *eptr;
    if( *ptr!='/' )
      return strdup( HTTP_404 );
    ptr++;
    level = (int) strtol( ptr, &eptr, 10 );
    while( isspace(*eptr) )
      eptr++;
    if( *eptr ) {
      logwarn("_ickP2pGetLogFile (%p): Requested minimum level is not a number (%s)", ictx, ptr );
      return strdup( HTTP_404 );
    }
  }

/*------------------------------------------------------------------------*\
    Get debug info
\*------------------------------------------------------------------------*/
  logContent = ickP2pGetLogContent( level );
  if( !logContent )
    return strdup( HTTP_404 );

/*------------------------------------------------------------------------*\
  Construct header
\*------------------------------------------------------------------------*/
  dlen = strlen( logContent);
  hlen = sprintf( header, HTTP_200, "text/plain", (long)dlen );

/*------------------------------------------------------------------------*\
  Merge header and payload
\*------------------------------------------------------------------------*/
  message = malloc( hlen+dlen+1 );
  if( !message ) {
    Sfree( logContent );
    logerr( "_ickP2pGetLogFile: out of memory" );
    return NULL;
  }
  strcpy( message, header );
  strcpy( message+hlen, logContent );
  Sfree( logContent );

/*------------------------------------------------------------------------*\
  That's all
\*------------------------------------------------------------------------*/
  return message;
}
Beispiel #24
0
static void
termination_handler(int signum)
{
  // SIGPIPE is handled by disabling the writer that caused it.
  if (signum == SIGPIPE) {
    logwarn("Net_stream: caught SIGPIPE\n");
  }
}
Beispiel #25
0
/** Try to obtain a lock on the BufferedWriter until it succeeds
 * \param mutexP pointer to mutex to unlock
 * \param mutexName name of mutex; used for error reporting only
 * \see oml_lock, oml_unlock
 */
void
oml_lock_persistent(pthread_mutex_t* mutexP, const char* mutexName)
{
  while (oml_lock(mutexP, mutexName)) {
    logwarn("Cannot get lock in %s; will try again soon.\n", mutexName);
    sleep(1);
  }
}
Beispiel #26
0
/** Signal handler
 * \param signum received signal number
 */
static void
signal_handler(int signum)
{
    // SIGPIPE is handled by disabling the writer that caused it.
    if (signum == SIGPIPE) {
        logwarn("OmlNetOutStream: caught SIGPIPE\n");
    }
}
Beispiel #27
0
/* node register and authtication */
static int __node_register_auth(NodeInfo * nf, int ent_id)
{
    if (nf->host_tag <= 0) {
        logerror(_("error in %s(%d)\n"), __func__, __LINE__);
        return -1;
    }

    int ret = -1;
    DBNodeRegInfo db_nf;
    bzero(&db_nf, sizeof(DBNodeRegInfo));

    int found = db_node_find(DB_NODE_FIND_BY_ID, &nf->host_tag, &db_nf);
    if (found == 1) {
        logdebug(_("tagged node found in db(%d %s %d %d)\n"),
                    db_nf.id, db_nf.ip, db_nf.status, db_nf.enabled);
        if (!ly_entity_is_authenticated(ent_id)) {
            logwarn(_("authentication is required for node(%d, %s)\n"),
                      nf->host_tag, nf->host_ip);
            goto out;
        }
        if (strcmp(nf->host_ip, db_nf.ip) != 0)
            logwarn(_("tagged node ip changed from %s to %s\n"),
                       db_nf.ip, nf->host_ip);

        nf->cpu_vlimit = db_nf.cpu_vlimit;
        nf->mem_vlimit = db_nf.mem_vlimit;
        ly_entity_enable(ent_id, db_nf.id, db_nf.enabled);
        ret = LY_S_REGISTERING_DONE_SUCCESS;
    }
    else if (found == 0) {
        logwarn(_("invalid tag for node(%d, %s), re-registration needed\n"),
                  nf->host_tag, nf->host_ip);
        ret = LY_S_REGISTERING_REINIT;
        goto out;
    }
    else {
        logerror(_("error in %s(%d)\n"), __func__, __LINE__);
        goto out;
    }

out:
    db_node_reginfo_free(&db_nf);
    return ret;
}
Beispiel #28
0
/*=========================================================================*\
  Get debug info from a context for a device registered there
    ictx       - the ickstream context
    uuid       - the device of interest or NULL for complete debugging info
                 of the context
    the returned string is allocated and must be freed by caller
    returns NULL on error or if debugging is not enabled
\*=========================================================================*/
char *ickP2pGetDebugInfo( ickP2pContext_t *ictx, const char *uuid )
{
  char *result = NULL;
  debug( "ickP2pGetDebugInfo (%p): \"%s\"", ictx, uuid );

#ifndef ICK_P2PENABLEDEBUGAPI
  logwarn( "ickP2pGetDebugInfo: p2plib not compiled with debugging API support." );
#else
  ickDevice_t *device;

/*------------------------------------------------------------------------*\
    Get complete context info?
\*------------------------------------------------------------------------*/
  if( !uuid )
    result = _ickContextStateJson( ictx, 0 );

/*------------------------------------------------------------------------*\
    Get info for specific device identified by UUID
\*------------------------------------------------------------------------*/
  else {

    // Lock device list and try to find device
    _ickLibDeviceListLock( ictx );
    device = _ickLibDeviceFindByUuid( ictx, uuid );
    if( !device ) {
      logwarn( "ickP2pGetDebugInfo: no such device (%s)", uuid );
      _ickLibDeviceListUnlock( ictx );
      return NULL;
    }

    // Get debug info as JSON object string
    result = _ickDeviceStateJson( device, 0 );

    // Unlock device list
    _ickLibDeviceListUnlock( ictx );
  }

#endif

/*------------------------------------------------------------------------*\
    That's all
\*------------------------------------------------------------------------*/
  return result;
}
Beispiel #29
0
/** Reset one OmlValue, cleaning any allocated memory.
 *
 * The type of the value is also reset (to 0, i.e., OML_DOUBLE_VALUE).
 *
 * \param v pointer to OmlValue to reset
 * \return 0 if successful, -1 otherwise
 * \see oml_value_init, oml_value_array_reset, memset(3)
 */
int
oml_value_reset(OmlValue* v)
{
    switch(v->type) {
    case OML_LONG_VALUE:
        logwarn("%s(): OML_LONG_VALUE is deprecated, please use OML_INT32_VALUE instead\n", __FUNCTION__);
    case OML_INT32_VALUE:
    case OML_UINT32_VALUE:
    case OML_INT64_VALUE:
    case OML_UINT64_VALUE:
    case OML_DOUBLE_VALUE:
    case OML_GUID_VALUE:
    case OML_BOOL_VALUE:
        /* No deep cleanup needed, memset(3) below is sufficient */
        break;

    case OML_STRING_VALUE:
        omlc_reset_string(v->value);
        break;

    case OML_DATETIME_VALUE:
        omlc_reset_string(v->value);
        break;

    case OML_BLOB_VALUE:
        omlc_reset_blob(v->value);
        break;

    case OML_VECTOR_DOUBLE_VALUE:
    case OML_VECTOR_INT32_VALUE:
    case OML_VECTOR_UINT32_VALUE:
    case OML_VECTOR_INT64_VALUE:
    case OML_VECTOR_UINT64_VALUE:
    case OML_VECTOR_BOOL_VALUE:
        omlc_reset_vector(v->value);
        break;

    default:
        logwarn("%s() for type '%d' not implemented, zeroing storage\n", __FUNCTION__, v->type);
    }
    memset(v, 0, sizeof(OmlValue));
    return 0;
}
Beispiel #30
0
/** Try to read a string as a boolean
 *
 * Anything is True except if clearly False (which includes a NULL string).
 *
 * Partial matches work too: 'f', 'Fa', 'fAl' or 'FAlS' are equivalents to
 * 'false'; longer strings starting with a variation of 'false' are true.
 *
 * \param value_s string to read as a boolean
 * \return a bool representation suitable for omlc_set_bool
 * \see omlc_set_bool
 */
uint8_t
oml_value_string_to_bool(const char* value_s)
{
    if (NULL != value_s) {
        return (uint8_t)(strncasecmp(value_s, "false", strlen(value_s)) != 0);
    }

    logwarn("%s: trying to convert NULL string to bool, assuming false\n", __FUNCTION__);
    return (uint8_t)0;
}