/**
 * Record or update stat value.
 */
void update_stat( char *group, char *key, char *value ) {
  syslog(LOG_DEBUG, "update_stat ( %s, %s, %s )\n", group, key, value);
  statsd_stat_t *s;
  statsd_stat_name_t l;

  memset(&l, 0, sizeof(statsd_stat_name_t));
  strcpy(l.group_name, group);
  strcpy(l.key_name, key);
  syslog(LOG_DEBUG, "HASH_FIND '%s' '%s'\n", l.group_name, l.key_name);
  HASH_FIND( hh, stats, &l, sizeof(statsd_stat_name_t), s );

  if (s) {
    syslog(LOG_DEBUG, "Updating old stat entry");

    wait_for_stats_lock();
    s->value = atol( value );
    remove_stats_lock();
  } else {
    syslog(LOG_DEBUG, "Adding new stat entry");
    s = malloc(sizeof(statsd_stat_t));
    memset(s, 0, sizeof(statsd_stat_t));

    strcpy(s->name.group_name, group);
    strcpy(s->name.key_name, key);
    s->value = atol(value);
    s->locked = 0;

    wait_for_stats_lock();
    HASH_ADD( hh, stats, name, sizeof(statsd_stat_name_t), s );
    remove_stats_lock();
  }
}
Exemple #2
0
int statsd_deserialize( char *filename ) {
  FILE *fp;
  int filesize;

  fp = fopen(filename, "r");
  if (!fp) {
    return 0;
  }

  fseek(fp, 0, SEEK_END);
  filesize = ftell(fp);
  rewind(fp);

  if (filesize < 10) {
    syslog(LOG_INFO, "No data found, skipping deserialization (length %d).\n", filesize);
    if (fp) fclose(fp);
    return 0;
  }

  char *data = (char*) calloc(sizeof(char), filesize + 20);

  fread(data, 1, filesize, fp);
  if(ferror(fp)) {
    if (fp) fclose(fp);
    if (data) free(data);
    return 0;
  }
  if (fp) fclose(fp);

  json_object *obj = json_tokener_parse(data);

  json_object *obj_stats = json_object_object_get(obj, "stats");
  {
    json_object_object_foreach(obj_stats, key, val) {
      statsd_stat_t *s = malloc(sizeof(statsd_stat_t));
      memset(s, 0, sizeof(statsd_stat_t));

      syslog(LOG_DEBUG, "Found key %s in file\n", key);

      char *period = strchr(key, '.');
      if (!period) {
        strcpy(s->name.key_name, key);
      } else {
        int period_pos = period - key;
        strncpy(s->name.group_name, key, period_pos);
        strncpy(s->name.key_name, key + period_pos + 1, strlen(key) - period_pos + 1);
      }

      s->value = json_object_get_int(val);
      s->locked = 0;

      wait_for_stats_lock();
      HASH_ADD( hh, stats, name, sizeof(statsd_stat_name_t), s );
      remove_stats_lock();
    }
  }
void init_stats() {
  char startup_time[12];
  sprintf(startup_time, "%ld", time(NULL));

  if (serialize_file && !clear_stats) {
    syslog(LOG_DEBUG, "Deserializing stats from file.");

    statsd_deserialize(serialize_file);
  }

  remove_stats_lock();

  update_stat( "graphite", "last_flush", startup_time );
  update_stat( "messages", "last_msg_seen", startup_time );
  update_stat( "messages", "bad_lines_seen", "0" );
}