Example #1
0
GString *
cellregion_to_string (GnmCellRegion const *cr,
		      gboolean only_visible,
		      GODateConventions const *date_conv)
{
	GString *all, *line;
	GnmCellCopy const *cc;
	int col, row, next_col_check, next_row_check;
	GnmRange extent;
	ColRowStateList	const *col_state = NULL, *row_state = NULL;
	ColRowRLEState const *rle;
	int ncells, i;
	GnmStyle const *style;
	GOFormat const *fmt;

	g_return_val_if_fail (cr != NULL, NULL);
	g_return_val_if_fail (cr->rows >= 0, NULL);
	g_return_val_if_fail (cr->cols >= 0, NULL);

	/* pre-allocate rough approximation of buffer */
	ncells = cr->cell_content ? g_hash_table_size (cr->cell_content) : 0;
	all = g_string_sized_new (20 * ncells + 1);
	line = g_string_new (NULL);

	cellregion_extent (cr, &extent);

	if (only_visible && NULL != (row_state = cr->row_state)) {
		next_row_check = i = 0;
		while ((i += ((ColRowRLEState *)(row_state->data))->length) <= extent.start.row) {
			if (NULL == (row_state = row_state->next)) {
				next_row_check = gnm_sheet_get_max_rows (cr->origin_sheet);
				break;
			}
			next_row_check = i;
		}
	} else
		next_row_check = gnm_sheet_get_max_rows (cr->origin_sheet);

	for (row = extent.start.row; row <= extent.end.row;) {
		if (row >= next_row_check) {
			rle = row_state->data;
			row_state = row_state->next;
			next_row_check += rle->length;
			if (!rle->state.visible) {
				row = next_row_check;
				continue;
			}
		}

		g_string_assign (line, "");

		if (only_visible && NULL != (col_state = cr->col_state)) {
			next_col_check = i = 0;
			while ((i += ((ColRowRLEState *)(col_state->data))->length) <= extent.start.col) {
				if (NULL == (col_state = col_state->next)) {
					next_col_check = gnm_sheet_get_max_cols (cr->origin_sheet);
					break;
				}
				next_col_check = i;
			}
		} else
			next_col_check = gnm_sheet_get_max_cols (cr->origin_sheet);

		for (col = extent.start.col; col <= extent.end.col;) {
			if (col == next_col_check) {
				rle = col_state->data;
				col_state = col_state->next;
				next_col_check += rle->length;
				if (!rle->state.visible) {
					col = next_col_check;
					continue;
				}
			}

			cc = cellregion_get_content (cr, col, row);
			if (cc) {
				style = style_list_get_style (cr->styles, col, row);
				fmt = gnm_style_get_format (style);

				if (go_format_is_general (fmt) &&
				    VALUE_FMT (cc->val))
					fmt = VALUE_FMT (cc->val);

				format_value_gstring (line, fmt, cc->val,
						      -1, date_conv);
			}
			if (++col <= extent.end.col)
				g_string_append_c (line, '\t');
		}
		g_string_append_len (all, line->str, line->len);
		if (++row <= extent.end.row)
			g_string_append_c (all, '\n');
	}

	g_string_free (line, TRUE);
	return all;
}
Example #2
0
/**********************************************************************
 * errlog2event_hash_init:
 * @custom_handle: Plugin's data pointer.
 * 
 * Initializes the Error Log to event translation hash table.
 *
 * Returns:
 * SA_OK - Normal operation.
 * SA_ERR_HPI_OUT_OF_MEMORY - No memory to allocate hash table structures.
 * SA_ERR_HPI_INVALID_PARAMS - @custom_handle NULL
 **********************************************************************/
SaErrorT errlog2event_hash_init(struct snmp_bc_hnd *custom_handle) {
        GMarkupParser parser;
        GMarkupParseContext *pcontext;
        gboolean rc;
        GError *err;
        struct errlog2event_hash_info user_data;
        if (!custom_handle) {
                dbg("Invalid parameter.");
                return(SA_ERR_HPI_INVALID_PARAMS);
        }
	
        err = NULL;
        snmp_bc_lock(snmp_bc_plock);
	/* Initialize hash table */
        errlog2event_hash = g_hash_table_new(g_str_hash, g_str_equal);
        if (errlog2event_hash == NULL) {
                dbg("No memory.");
                snmp_bc_unlock(snmp_bc_plock);
                return(SA_ERR_HPI_OUT_OF_MEMORY);
	}
	
	/* Initialize user data used in parsing XML events */
	user_data.hashtable = errlog2event_hash;

        /* Initialize XML parser */
        memset(&parser, 0, sizeof(parser));
        parser.start_element = event_start_element;
        pcontext = g_markup_parse_context_new(&parser, 0, &user_data, NULL);
        if (pcontext == NULL) {
		dbg("No memory.");
                snmp_bc_unlock(snmp_bc_plock);
		return(SA_ERR_HPI_OUT_OF_MEMORY);
        }

        /* Parse XML events */
        rc = g_markup_parse_context_parse(pcontext,
                                          (const gchar *)eventxml,
                                          (gssize)strlen(eventxml), &err);
        if (rc == FALSE || err != NULL) {
                if (err != NULL) {
                        dbg("Parse error=%s.", err->message);
                        g_error_free(err);
                }
                else {
                        dbg("Unknown XML parse error.");
                }
                g_markup_parse_context_free(pcontext);
                snmp_bc_unlock(snmp_bc_plock);
                return(SA_ERR_HPI_INTERNAL_ERROR);
        }
        g_markup_parse_context_end_parse(pcontext, &err);
        g_markup_parse_context_free(pcontext);

        /* Make sure there are elements in the hash table */
        if (g_hash_table_size(errlog2event_hash) == 0) {
                dbg("Hash table is empty.");
                snmp_bc_unlock(snmp_bc_plock);
                return(SA_ERR_HPI_INTERNAL_ERROR);
        }
        
        snmp_bc_unlock(snmp_bc_plock);
	return(SA_OK);
}
Example #3
0
static void
file_builder_add_hash (FileBuilder         *fb,
                       GHashTable          *table,
                       struct gvdb_pointer *pointer)
{
  guint32_le *buckets, *bloom_filter;
  struct gvdb_hash_item *items;
  HashTable *mytable;
  GvdbItem *item;
  guint32 index;
  gint bucket;

  mytable = hash_table_new (g_hash_table_size (table));
  g_hash_table_foreach (table, hash_table_insert, mytable);
  index = 0;

  for (bucket = 0; bucket < mytable->n_buckets; bucket++)
    for (item = mytable->buckets[bucket]; item; item = item->next)
      item->assigned_index = guint32_to_le (index++);

  file_builder_allocate_for_hash (fb, mytable->n_buckets, index, 5, 0,
                                  &bloom_filter, &buckets, &items, pointer);

  index = 0;
  for (bucket = 0; bucket < mytable->n_buckets; bucket++)
    {
      buckets[bucket] = guint32_to_le (index);

      for (item = mytable->buckets[bucket]; item; item = item->next)
        {
          struct gvdb_hash_item *entry = items++;
          const gchar *basename;

          g_assert (index == guint32_from_le (item->assigned_index));
          entry->hash_value = guint32_to_le (item->hash_value);
          entry->parent = item_to_index (item->parent);
          entry->unused = 0;

          if (item->parent != NULL)
            basename = item->key + strlen (item->parent->key);
          else
            basename = item->key;

          file_builder_add_string (fb, basename,
                                   &entry->key_start,
                                   &entry->key_size);

          if (item->value != NULL)
            {
              g_assert (item->child == NULL && item->table == NULL);

              file_builder_add_value (fb, item->value, &entry->value.pointer);
              entry->type = 'v';
            }

          if (item->child != NULL)
            {
              guint32 children = 0, i = 0;
              guint32_le *offsets;
              GvdbItem *child;

              g_assert (item->table == NULL);

              for (child = item->child; child; child = child->sibling)
                children++;

              offsets = file_builder_allocate (fb, 4, 4 * children,
                                               &entry->value.pointer);
              entry->type = 'L';

              for (child = item->child; child; child = child->sibling)
                offsets[i++] = child->assigned_index;

              g_assert (children == i);
            }

          if (item->table != NULL)
            {
              entry->type = 'H';
              file_builder_add_hash (fb, item->table, &entry->value.pointer);
            }

          index++;
        }
    }

  hash_table_free (mytable);
}
static void
addres_resolution_to_texbuff(GtkTextBuffer *buffer)
{
    gchar string_buff[ADDRESS_STR_MAX];
	GHashTable *manuf_hashtable;
	GHashTable *wka_hashtable;
	GHashTable *eth_hashtable;
	GHashTable *serv_port_hashtable;
	GHashTable *ipv4_hash_table;
	GHashTable *ipv6_hash_table;

    g_snprintf(string_buff, ADDRESS_STR_MAX, "# Hosts information in Wireshark \n#\n");
    gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);
    g_snprintf(string_buff, ADDRESS_STR_MAX, "# Host data gathered from %s\n\n", cfile.filename);
    gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);

    /* Dump the v4 addresses first, then v6 */
	ipv4_hash_table = get_ipv4_hash_table();
	if(ipv4_hash_table){
		g_hash_table_foreach( ipv4_hash_table, ipv4_hash_table_resolved_to_texbuff, buffer);
	}

	ipv6_hash_table = get_ipv6_hash_table();
	if(ipv6_hash_table){
		g_hash_table_foreach( ipv6_hash_table, ipv6_hash_table_resolved_to_texbuff, buffer);
	}

	g_snprintf(string_buff, ADDRESS_STR_MAX, "\n\n# Address resolution IPv4 Hash table \n#\n");
	gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);

	if(ipv4_hash_table){
		g_snprintf(string_buff, ADDRESS_STR_MAX, "# With %i entries\n#\n", g_hash_table_size(ipv4_hash_table));
		gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);
		g_hash_table_foreach( ipv4_hash_table, ipv4_hash_table_to_texbuff, buffer);
	}

	g_snprintf(string_buff, ADDRESS_STR_MAX, "\n\n# Address resolution IPv6 Hash table \n#\n");
	gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);

	if(ipv6_hash_table){
		g_snprintf(string_buff, ADDRESS_STR_MAX, "# With %i entries\n#\n", g_hash_table_size(ipv6_hash_table));
		gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);
		g_hash_table_foreach( ipv6_hash_table, ipv6_hash_table_to_texbuff, buffer);
	}


	g_snprintf(string_buff, ADDRESS_STR_MAX, "\n\n# Port names information in Wireshark \n#\n");
	gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);

	serv_port_hashtable = get_serv_port_hashtable();
	if(serv_port_hashtable){
		g_snprintf(string_buff, ADDRESS_STR_MAX, "# With %i entries\n#\n", g_hash_table_size(serv_port_hashtable));
		gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);
		g_hash_table_foreach( serv_port_hashtable, serv_port_hash_to_texbuff, buffer);
	}

	g_snprintf(string_buff, ADDRESS_STR_MAX, "\n\n# Eth names information in Wireshark \n#\n");
	gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);

	eth_hashtable = get_eth_hashtable();
	if(eth_hashtable){
		g_snprintf(string_buff, ADDRESS_STR_MAX, "# With %i entries\n#\n", g_hash_table_size(eth_hashtable));
		gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);
		g_hash_table_foreach( eth_hashtable, eth_hash_to_texbuff, buffer);
	}

	g_snprintf(string_buff, ADDRESS_STR_MAX, "\n\n# Manuf information in Wireshark \n#\n");
	gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);

	manuf_hashtable = get_manuf_hashtable();
	if(manuf_hashtable){
		g_snprintf(string_buff, ADDRESS_STR_MAX, "# With %i entries\n#\n", g_hash_table_size(manuf_hashtable));
		gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);
		g_hash_table_foreach( manuf_hashtable, manuf_hash_to_texbuff, buffer);
	}

	g_snprintf(string_buff, ADDRESS_STR_MAX, "\n\n# wka information in Wireshark \n#\n");
	gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);

	wka_hashtable = get_wka_hashtable();
	if(wka_hashtable){
		g_snprintf(string_buff, ADDRESS_STR_MAX, "# With %i entries\n#\n", g_hash_table_size(wka_hashtable));
		gtk_text_buffer_insert_at_cursor (buffer, string_buff, -1);
		g_hash_table_foreach( wka_hashtable, wka_hash_to_texbuff, buffer);
	}


}
Example #5
0
static guint
node_children_num (node_t *f)
{
    return g_hash_table_size (f->children);
}
Example #6
0
static void pdp_qmi_onUpdateFromQmi (PdpQmi* self, GHashTable* properties) {
	GHashTable* _tmp0_;
	gconstpointer _tmp1_ = NULL;
	gchar* _tmp2_;
	gchar* _tmp3_;
	const gchar* _tmp4_;
	const gchar* _tmp6_;
	gchar* _tmp7_;
	gchar* state;
	GHashTable* _tmp8_;
	guint _tmp9_ = 0U;
	gchar* _tmp10_ = NULL;
	gchar* _tmp11_;
	const gchar* _tmp12_;
	const gchar* _tmp13_ = NULL;
	gchar* _tmp14_ = NULL;
	gchar* _tmp15_;
	const gchar* _tmp16_;
	g_return_if_fail (self != NULL);
	g_return_if_fail (properties != NULL);
	_tmp0_ = properties;
	_tmp1_ = g_hash_table_lookup (_tmp0_, "STATE");
	_tmp2_ = g_strdup ((const gchar*) _tmp1_);
	_tmp3_ = _tmp2_;
	_tmp4_ = _tmp3_;
	if (_tmp4_ == NULL) {
		gchar* _tmp5_;
		_tmp5_ = g_strdup ("unknown");
		_g_free0 (_tmp3_);
		_tmp3_ = _tmp5_;
	}
	_tmp6_ = _tmp3_;
	_tmp7_ = g_strdup (_tmp6_);
	state = _tmp7_;
	_tmp8_ = properties;
	_tmp9_ = g_hash_table_size (_tmp8_);
	_tmp10_ = g_strdup_printf ("%u", _tmp9_);
	_tmp11_ = _tmp10_;
	_tmp12_ = state;
	_tmp13_ = string_to_string (_tmp12_);
	_tmp14_ = g_strconcat ("onUpdateFromQmi with ", _tmp11_, " properties [state=", _tmp13_, "]", NULL);
	_tmp15_ = _tmp14_;
	g_message ("plugin.vala:85: %s", _tmp15_);
	_g_free0 (_tmp15_);
	_g_free0 (_tmp11_);
	_tmp16_ = state;
	if (g_strcmp0 (_tmp16_, "up") == 0) {
		GHashTable* _tmp17_;
		gconstpointer _tmp18_ = NULL;
		gchar* _tmp19_;
		gchar* _tmp20_;
		const gchar* _tmp21_;
		const gchar* _tmp23_;
		gchar* _tmp24_;
		gchar* addr;
		GHashTable* _tmp25_;
		gconstpointer _tmp26_ = NULL;
		gchar* _tmp27_;
		gchar* _tmp28_;
		const gchar* _tmp29_;
		const gchar* _tmp31_;
		gchar* _tmp32_;
		gchar* mask;
		GHashTable* _tmp33_;
		gconstpointer _tmp34_ = NULL;
		gchar* _tmp35_;
		gchar* _tmp36_;
		const gchar* _tmp37_;
		const gchar* _tmp39_;
		gchar* _tmp40_;
		gchar* gway;
		GHashTable* _tmp41_;
		gconstpointer _tmp42_ = NULL;
		gchar* _tmp43_;
		gchar* _tmp44_;
		const gchar* _tmp45_;
		const gchar* _tmp47_;
		gchar* _tmp48_;
		gchar* dns1;
		GHashTable* _tmp49_;
		gconstpointer _tmp50_ = NULL;
		gchar* _tmp51_;
		gchar* _tmp52_;
		const gchar* _tmp53_;
		const gchar* _tmp55_;
		gchar* _tmp56_;
		gchar* dns2;
		gchar* _tmp57_;
		const gchar* _tmp58_;
		gchar* _tmp59_;
		const gchar* _tmp60_;
		gchar* _tmp61_;
		const gchar* _tmp62_;
		gchar* _tmp63_;
		const gchar* _tmp64_;
		gchar* _tmp65_;
		const gchar* _tmp66_;
		gchar* _tmp67_;
		FsoGsmRouteInfo* _tmp68_ = NULL;
		FsoGsmRouteInfo* route;
		FsoGsmRouteInfo* _tmp69_;
		_tmp17_ = properties;
		_tmp18_ = g_hash_table_lookup (_tmp17_, "ADDR");
		_tmp19_ = g_strdup ((const gchar*) _tmp18_);
		_tmp20_ = _tmp19_;
		_tmp21_ = _tmp20_;
		if (_tmp21_ == NULL) {
			gchar* _tmp22_;
			_tmp22_ = g_strdup ("unknown");
			_g_free0 (_tmp20_);
			_tmp20_ = _tmp22_;
		}
		_tmp23_ = _tmp20_;
		_tmp24_ = g_strdup (_tmp23_);
		addr = _tmp24_;
		_tmp25_ = properties;
		_tmp26_ = g_hash_table_lookup (_tmp25_, "MASK");
		_tmp27_ = g_strdup ((const gchar*) _tmp26_);
		_tmp28_ = _tmp27_;
		_tmp29_ = _tmp28_;
		if (_tmp29_ == NULL) {
			gchar* _tmp30_;
			_tmp30_ = g_strdup ("unknown");
			_g_free0 (_tmp28_);
			_tmp28_ = _tmp30_;
		}
		_tmp31_ = _tmp28_;
		_tmp32_ = g_strdup (_tmp31_);
		mask = _tmp32_;
		_tmp33_ = properties;
		_tmp34_ = g_hash_table_lookup (_tmp33_, "GATEWAY");
		_tmp35_ = g_strdup ((const gchar*) _tmp34_);
		_tmp36_ = _tmp35_;
		_tmp37_ = _tmp36_;
		if (_tmp37_ == NULL) {
			gchar* _tmp38_;
			_tmp38_ = g_strdup ("unknown");
			_g_free0 (_tmp36_);
			_tmp36_ = _tmp38_;
		}
		_tmp39_ = _tmp36_;
		_tmp40_ = g_strdup (_tmp39_);
		gway = _tmp40_;
		_tmp41_ = properties;
		_tmp42_ = g_hash_table_lookup (_tmp41_, "DNS1");
		_tmp43_ = g_strdup ((const gchar*) _tmp42_);
		_tmp44_ = _tmp43_;
		_tmp45_ = _tmp44_;
		if (_tmp45_ == NULL) {
			gchar* _tmp46_;
			_tmp46_ = g_strdup ("unknown");
			_g_free0 (_tmp44_);
			_tmp44_ = _tmp46_;
		}
		_tmp47_ = _tmp44_;
		_tmp48_ = g_strdup (_tmp47_);
		dns1 = _tmp48_;
		_tmp49_ = properties;
		_tmp50_ = g_hash_table_lookup (_tmp49_, "DNS2");
		_tmp51_ = g_strdup ((const gchar*) _tmp50_);
		_tmp52_ = _tmp51_;
		_tmp53_ = _tmp52_;
		if (_tmp53_ == NULL) {
			gchar* _tmp54_;
			_tmp54_ = g_strdup ("unknown");
			_g_free0 (_tmp52_);
			_tmp52_ = _tmp54_;
		}
		_tmp55_ = _tmp52_;
		_tmp56_ = g_strdup (_tmp55_);
		dns2 = _tmp56_;
		_tmp57_ = g_strdup (PDP_QMI_RMNET_IFACE);
		_tmp58_ = addr;
		_tmp59_ = g_strdup (_tmp58_);
		_tmp60_ = mask;
		_tmp61_ = g_strdup (_tmp60_);
		_tmp62_ = gway;
		_tmp63_ = g_strdup (_tmp62_);
		_tmp64_ = dns1;
		_tmp65_ = g_strdup (_tmp64_);
		_tmp66_ = dns2;
		_tmp67_ = g_strdup (_tmp66_);
		_tmp68_ = fso_gsm_route_info_new ();
		_g_free0 (_tmp68_->iface);
		_tmp68_->iface = _tmp57_;
		_g_free0 (_tmp68_->ipv4addr);
		_tmp68_->ipv4addr = _tmp59_;
		_g_free0 (_tmp68_->ipv4mask);
		_tmp68_->ipv4mask = _tmp61_;
		_g_free0 (_tmp68_->ipv4gateway);
		_tmp68_->ipv4gateway = _tmp63_;
		_g_free0 (_tmp68_->dns1);
		_tmp68_->dns1 = _tmp65_;
		_g_free0 (_tmp68_->dns2);
		_tmp68_->dns2 = _tmp67_;
		route = _tmp68_;
		_tmp69_ = route;
		fso_gsm_ipdp_handler_connectedWithNewDefaultRoute ((FsoGsmIPdpHandler*) self, _tmp69_, NULL, NULL);
		_fso_gsm_route_info_unref0 (route);
		_g_free0 (dns2);
		_g_free0 (_tmp52_);
		_g_free0 (dns1);
		_g_free0 (_tmp44_);
		_g_free0 (gway);
		_g_free0 (_tmp36_);
		_g_free0 (mask);
		_g_free0 (_tmp28_);
		_g_free0 (addr);
		_g_free0 (_tmp20_);
	}
	_g_free0 (state);
	_g_free0 (_tmp3_);
}
Example #7
0
/**
 * Assembles a #SteamHttpReq. The returned strings should be freed
 * with #g_free() when no longer needed.
 *
 * @param req The #SteamHttpReq.
 * @param hs  The return location for the header string.
 * @param ps  The return location for the param string.
 * @param fs  The return location for the full string.
 **/
static void steam_http_req_asm(SteamHttpReq *req, gchar **hs, gchar **ps,
                               gchar **fs)
{
    GHashTableIter  iter;
    GString        *hgs;
    GString        *pgs;
    gchar          *str;
    gchar          *key;
    gchar          *val;

    g_hash_table_iter_init(&iter, req->params);
    pgs = g_string_sized_new(128);

    while (g_hash_table_iter_next(&iter, (gpointer*) &key, (gpointer*) &val)) {
        if (val == NULL)
            val = "";

        key = steam_http_uri_escape(key);
        val = steam_http_uri_escape(val);

        str = (pgs->len > 0) ? "&" : "";
        g_string_append_printf(pgs, "%s%s=%s", str, key, val);

        g_free(key);
        g_free(val);
    }

    if (g_hash_table_size(req->http->cookies) > 0) {
        str = steam_http_cookies_str(req->http);
        steam_http_req_headers_set(req, STEAM_HTTP_PAIR("Cookie", str), NULL);
        g_free(str);
    }

    if (req->flags & STEAM_HTTP_REQ_FLAG_POST) {
        str = g_strdup_printf("%" G_GSIZE_FORMAT, pgs->len);

        steam_http_req_headers_set(req,
            STEAM_HTTP_PAIR("Content-Type",   "application/"
                                              "x-www-form-urlencoded"),
            STEAM_HTTP_PAIR("Content-Length", str),
            NULL
        );

        g_free(str);
    }

    g_hash_table_iter_init(&iter, req->headers);
    hgs = g_string_sized_new(128);

    while (g_hash_table_iter_next(&iter, (gpointer*) &key, (gpointer*) &val)) {
        if (val == NULL)
            val = "";

        g_string_append_printf(hgs, "%s: %s\r\n", key, val);
    }

    if (req->flags & STEAM_HTTP_REQ_FLAG_POST) {
        *fs = g_strdup_printf("POST %s HTTP/1.1\r\n%s\r\n%s",
                              req->path, hgs->str, pgs->str);
    } else {
        *fs = g_strdup_printf("GET %s?%s HTTP/1.1\r\n%s\r\n",
                              req->path, pgs->str, hgs->str);
    }

    *hs = g_string_free(hgs, FALSE);
    *ps = g_string_free(pgs, FALSE);
}
Example #8
0
/** \brief Update TLE files from local files.
 *  \param dir Directory where files are located.
 *  \param filter File filter, e.g. *.txt (not used at the moment!)
 *  \param silent TRUE if function should execute without graphical status indicator.
 *  \param label1 Activity label (can be NULL)
 *  \param label2 Statistics label (can be NULL)
 *  \param progress Pointer to progress indicator.
 *  \param init_prgs Initial value of progress indicator, e.g 0.5 if we are updating
 *                   from network.
 *
 * This function is used to update the TLE data from local files.
 *
 * Functional description: TBD
 *
 */
void tle_update_from_files (const gchar *dir, const gchar *filter,
                            gboolean silent, GtkWidget *progress,
                            GtkWidget *label1, GtkWidget *label2)
{
    static GMutex tle_file_in_progress;

    GHashTable  *data;        /* hash table with fresh TLE data */
    GDir        *cache_dir;   /* directory to scan fresh TLE */
    GDir        *loc_dir;     /* directory for gpredict TLE files */
    GError      *err = NULL;
    gchar       *text;
    gchar       *ldname;
    gchar       *userconfdir;
    const gchar *fnam;
    guint        num = 0;
    guint        updated,updated_tmp;
    guint        skipped,skipped_tmp;
    guint        nodata,nodata_tmp;
    guint        newsats = 0;
    guint        total,total_tmp;
    gdouble      fraction = 0.0;
    gdouble      start = 0.0;

    (void) filter; /* avoid unused parameter compiler warning */

    if (g_mutex_trylock(&tle_file_in_progress) == FALSE)
    {
        sat_log_log (SAT_LOG_LEVEL_ERROR,
                     _("%s: A TLE update process is already running. Aborting."),
                     __FUNCTION__);

        return;
    }

    /* create hash table */
    data = g_hash_table_new_full (g_int_hash, g_int_equal, g_free, free_new_tle);

    /* open directory and read files one by one */
    cache_dir = g_dir_open (dir, 0, &err);

    if (err != NULL) {

        /* send an error message */
        sat_log_log (SAT_LOG_LEVEL_ERROR,
                     _("%s: Error opening directory %s (%s)"),
                     __FUNCTION__, dir, err->message);

        /* insert error message into the status string, too */
        if (!silent && (label1 != NULL)) {
            text = g_strdup_printf (_("<b>ERROR</b> opening directory %s\n%s"),
                                    dir, err->message);

            gtk_label_set_markup (GTK_LABEL (label1), text);
            g_free (text);

        }

        g_clear_error (&err);
        err = NULL;
    }
    else {

        /* scan directory for tle files */
        while ((fnam = g_dir_read_name (cache_dir)) != NULL) {
            /* check that we got a TLE file */
            if (is_tle_file(dir, fnam)) {
                
                /* status message */
                if (!silent && (label1 != NULL)) {
                    text = g_strdup_printf (_("Reading data from %s"), fnam);
                    gtk_label_set_text (GTK_LABEL (label1), text);
                    g_free (text);

                    /* Force the drawing queue to be processed otherwise there will
                        not be any visual feedback, ie. frozen GUI
                        - see Gtk+ FAQ http://www.gtk.org/faq/#AEN602
                    */
                    while (g_main_context_iteration (NULL, FALSE));

                    /* give user a chance to follow progress */
                    g_usleep (G_USEC_PER_SEC / 100);
                }

                /* now, do read the fresh data */
                num = read_fresh_tle (dir, fnam, data);
            } else {
                num = 0;
            }

            if (num < 1) {
                sat_log_log (SAT_LOG_LEVEL_ERROR,
                             _("%s: No valid TLE data found in %s"),
                             __FUNCTION__, fnam);
            }
            else {
                sat_log_log (SAT_LOG_LEVEL_INFO,
                             _("%s: Read %d sats from %s into memory"),
                             __FUNCTION__, num, fnam);
            }
        }

        /* close directory since we don't need it anymore */
        g_dir_close (cache_dir);

        /* now we load each .sat file and update if we have new data */
        userconfdir = get_user_conf_dir ();
        ldname = g_strconcat (userconfdir, G_DIR_SEPARATOR_S, "satdata", NULL);
        g_free (userconfdir);

        /* open directory and read files one by one */
        loc_dir = g_dir_open (ldname, 0, &err);

        if (err != NULL) {

            /* send an error message */
            sat_log_log (SAT_LOG_LEVEL_ERROR,
                         _("%s: Error opening directory %s (%s)"),
                         __FUNCTION__, dir, err->message);

            /* insert error message into the status string, too */
            if (!silent && (label1 != NULL)) {
                text = g_strdup_printf (_("<b>ERROR</b> opening directory %s\n%s"),
                                        dir, err->message);

                gtk_label_set_markup (GTK_LABEL (label1), text);
                g_free (text);
            }

            g_clear_error (&err);
            err = NULL;
        }
        else {
            /* clear statistics */
            updated = 0;
            skipped = 0;
            nodata = 0;
            total = 0;

            /* get initial value of progress indicator */
            if (progress != NULL)
                start = gtk_progress_bar_get_fraction (GTK_PROGRESS_BAR (progress));

            /* This is insane but I don't know how else to count the number of sats */
            num = 0;
            while ((fnam = g_dir_read_name (loc_dir)) != NULL) {
                /* only consider .sat files */
                if (g_str_has_suffix (fnam, ".sat")) {
                    num++;
                }
            }

            g_dir_rewind (loc_dir);

            /* update TLE files one by one */
            while ((fnam = g_dir_read_name (loc_dir)) != NULL) {
                /* only consider .sat files */
                if (g_str_has_suffix (fnam, ".sat")) {

                    /* clear stat bufs */
                    updated_tmp = 0;
                    skipped_tmp = 0;
                    nodata_tmp = 0;
                    total_tmp = 0;

                    /* update TLE data in this file */
                    update_tle_in_file (ldname, fnam, data, 
                                        &updated_tmp,
                                        &skipped_tmp,
                                        &nodata_tmp,
                                        &total_tmp);

                    /* update statistics */
                    updated += updated_tmp;
                    skipped += skipped_tmp;
                    nodata  += nodata_tmp;
                    total   = updated+skipped+nodata;

                    if (!silent) {

                        if (label1 != NULL) {
                            gtk_label_set_text (GTK_LABEL (label1),
                                                _("Updating data..."));
                        }

                        if (label2 != NULL) {
                            text = g_strdup_printf (_("Satellites updated:\t %d\n"\
                                                      "Satellites skipped:\t %d\n"\
                                                      "Missing Satellites:\t %d\n"),
                                                    updated, skipped, nodata);
                            gtk_label_set_text (GTK_LABEL (label2), text);
                            g_free (text);
                        }

                        if (progress != NULL) {
                            /* two different calculations for completeness depending on whether 
                               we are adding new satellites or not. */
                            if (sat_cfg_get_bool (SAT_CFG_BOOL_TLE_ADD_NEW)) {
                                /* In this case we are possibly processing more than num satellites
                                   How many more? We do not know yet.  Worst case is g_hash_table_size more.
                                   
                                   As we update skipped and updated we can reduce the denominator count
                                   as those are in both pools (files and hash table). When we have processed 
                                   all the files, updated and skipped are completely correct and the progress 
                                   is correct. It may be correct sooner if the missed satellites are the 
                                   last files to process.
                                   
                                   Until then, if we eliminate the ones that are updated and skipped from being 
                                   double counted, our progress will shown will always be less or equal to our 
                                   true progress since the denominator will be larger than is correct.
                                   
                                   Advantages to this are that the progress bar does not stall close to 
                                   finished when there are a large number of new satellites.
                                */
                                fraction = start + (1.0-start) * ((gdouble) total) / 
                                    ((gdouble) num + g_hash_table_size(data) - updated - skipped);
                            } else {
                                /* here we only process satellites we have have files for so divide by num */
                                fraction = start + (1.0-start) * ((gdouble) total) / ((gdouble) num);
                            }
                            gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (progress),
                                                           fraction);

                        }

                        /* update the gui only every so often to speed up the process */
                        /* 47 was selected empirically to balance the update looking smooth but not take too much time. */
                        /* it also tumbles all digits in the numbers so that there is no obvious pattern. */
                        /* on a developer machine this improved an update from 5 minutes to under 20 seconds. */
                        if (total%47 == 0) {
                            /* Force the drawing queue to be processed otherwise there will
                               not be any visual feedback, ie. frozen GUI
                               - see Gtk+ FAQ http://www.gtk.org/faq/#AEN602
                            */
                            while (g_main_context_iteration (NULL, FALSE));
                        
                            /* give user a chance to follow progress */
                            g_usleep (G_USEC_PER_SEC / 1000);
                        }
                    }
                }
            }
            
            /* force gui update */
            while (g_main_context_iteration (NULL, FALSE));


            /* close directory handle */
            g_dir_close (loc_dir);
            
            /* see if we have any new sats that need to be added */
            if (sat_cfg_get_bool (SAT_CFG_BOOL_TLE_ADD_NEW)) {
                
                newsats = add_new_sats (data);
                
                if (!silent && (label2 != NULL)) {
                    text = g_strdup_printf (_("Satellites updated:\t %d\n"\
                                              "Satellites skipped:\t %d\n"\
                                              "Missing Satellites:\t %d\n"\
                                              "New Satellites:\t\t %d"),
                                            updated, skipped, nodata, newsats);
                    gtk_label_set_text (GTK_LABEL (label2), text);
                    g_free (text);

                }
                
                sat_log_log (SAT_LOG_LEVEL_INFO,
                             _("%s: Added %d new satellites to local database"),
                             __FUNCTION__, newsats);
            }

            /* store time of update if we have updated something */
            if ((updated > 0) || (newsats > 0)) {
                GTimeVal tval;
                
                g_get_current_time (&tval);
                sat_cfg_set_int (SAT_CFG_INT_TLE_LAST_UPDATE, tval.tv_sec);
            }

        }

        g_free (ldname);

        sat_log_log (SAT_LOG_LEVEL_INFO,
                     _("%s: TLE elements updated."),
                     __FUNCTION__);
    }

    /* destroy hash tables */
    g_hash_table_destroy (data);

    g_mutex_unlock(&tle_file_in_progress);
}
FcitxSubConfigParser* sub_config_parser_new(const gchar* subconfig)
{
    if (subconfig == NULL)
        return NULL;

    FcitxSubConfigParser* parser = g_malloc0(sizeof(FcitxSubConfigParser));
    parser->subconfigs = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, sub_config_pattern_free);
    gchar** strv = g_strsplit(subconfig, ",", 0);

    gchar** str;
    for (str = &strv[0]; *str != NULL; str++) {
        if (strchr(*str, ':') == NULL)
            continue;

        gchar** items = g_strsplit(*str, ":", 0);

        if (g_strv_length(items) < 2)
            goto end;
        if (strlen(items[0]) == 0)
            goto end;

        if (strcmp(items[1], "domain") == 0) {
            parser->domain = g_strdup(items[0]);
            goto end;
        }

        SubConfigType type = parse_type(items[1]);
        if (type == SC_None)
            goto end;
        if (g_hash_table_lookup(parser->subconfigs, items[0]) != NULL)
            continue;

        if (type == SC_ConfigFile) {
            if (g_strv_length(items) != 4)
                goto end;
            if (strlen(items[2]) == 0 || items[2][0] == '/')
                goto end;
        } else if (type == SC_NativeFile) {
            if (g_strv_length(items) != 3)
                goto end;
            if (strchr(items[2], '*') != NULL)
                goto end;
        }

        gchar** paths = g_strsplit(items[2], "/", 0);
        if (paths[0] == 0) {
            g_strfreev(paths);
            goto end;
        }
        gchar** path;
        for (path = &paths[0]; *path != NULL; path++) {
            if (strlen(*path) == 0)
                break;
            if (strcmp(*path, ".") == 0)
                break;
            if (strcmp(*path, "..") == 0)
                break;
        }
        if (*path != NULL) {
            g_strfreev(paths);
            goto end;
        }
        FcitxSubConfigPattern* pattern = g_malloc0(sizeof(FcitxSubConfigPattern));
        pattern->type = type;
        pattern->patternlist = paths;
        if (type == SC_ConfigFile)
            pattern->configdesc = g_strdup(items[3]);
        else if (type == SC_NativeFile)
            pattern->nativepath = g_strdup(items[2]);

        g_hash_table_insert(parser->subconfigs, g_strdup(items[0]), pattern);
    end:
        g_strfreev(items);
    }
    g_strfreev(strv);
    if (g_hash_table_size(parser->subconfigs) == 0 || parser->domain == NULL) {
        sub_config_parser_free(parser);
        parser = NULL;
    }

    return parser;
}
Example #10
0
/*	 A_DC_JOIN_PROCESS_REQ	*/
void
do_dc_join_filter_offer(long long action,
                        enum crmd_fsa_cause cause,
                        enum crmd_fsa_state cur_state,
                        enum crmd_fsa_input current_input, fsa_data_t * msg_data)
{
    xmlNode *generation = NULL;

    int cmp = 0;
    int join_id = -1;
    gboolean ack_nack_bool = TRUE;
    const char *ack_nack = CRMD_JOINSTATE_MEMBER;
    ha_msg_input_t *join_ack = fsa_typed_data(fsa_dt_ha_msg);

    const char *join_from = crm_element_value(join_ack->msg, F_CRM_HOST_FROM);
    const char *ref = crm_element_value(join_ack->msg, XML_ATTR_REFERENCE);

    crm_node_t *join_node = crm_get_peer(0, join_from);

    crm_debug("Processing req from %s", join_from);

    generation = join_ack->xml;
    crm_element_value_int(join_ack->msg, F_CRM_JOIN_ID, &join_id);

    if (max_generation_xml != NULL && generation != NULL) {
        int lpc = 0;

        const char *attributes[] = {
            XML_ATTR_GENERATION_ADMIN,
            XML_ATTR_GENERATION,
            XML_ATTR_NUMUPDATES,
        };

        for (lpc = 0; cmp == 0 && lpc < DIMOF(attributes); lpc++) {
            cmp = compare_int_fields(max_generation_xml, generation, attributes[lpc]);
        }
    }

    if (join_id != current_join_id) {
        crm_debug("Invalid response from %s: join-%d vs. join-%d",
                  join_from, join_id, current_join_id);
        check_join_state(cur_state, __FUNCTION__);
        return;

    } else if (join_node == NULL || crm_is_peer_active(join_node) == FALSE) {
        crm_err("Node %s is not a member", join_from);
        ack_nack_bool = FALSE;

    } else if (generation == NULL) {
        crm_err("Generation was NULL");
        ack_nack_bool = FALSE;

    } else if (max_generation_xml == NULL) {
        max_generation_xml = copy_xml(generation);
        max_generation_from = strdup(join_from);

    } else if (cmp < 0 || (cmp == 0 && safe_str_eq(join_from, fsa_our_uname))) {
        crm_debug("%s has a better generation number than"
                  " the current max %s", join_from, max_generation_from);
        if (max_generation_xml) {
            crm_log_xml_debug(max_generation_xml, "Max generation");
        }
        crm_log_xml_debug(generation, "Their generation");

        free(max_generation_from);
        free_xml(max_generation_xml);

        max_generation_from = strdup(join_from);
        max_generation_xml = copy_xml(join_ack->xml);
    }

    if (ack_nack_bool == FALSE) {
        /* NACK this client */
        ack_nack = CRMD_JOINSTATE_NACK;
        crm_err("join-%d: NACK'ing node %s (ref %s)", join_id, join_from, ref);
    } else {
        crm_debug("join-%d: Welcoming node %s (ref %s)", join_id, join_from, ref);
    }

    /* add them to our list of CRMD_STATE_ACTIVE nodes */
    g_hash_table_insert(integrated_nodes, strdup(join_from), strdup(ack_nack));

    crm_debug("%u nodes have been integrated into join-%d",
              g_hash_table_size(integrated_nodes), join_id);

    g_hash_table_remove(welcomed_nodes, join_from);

    if (check_join_state(cur_state, __FUNCTION__) == FALSE) {
        /* dont waste time by invoking the PE yet; */
        crm_debug("join-%d: Still waiting on %d outstanding offers",
                  join_id, g_hash_table_size(welcomed_nodes));
    }
}
Example #11
0
gboolean
check_join_state(enum crmd_fsa_state cur_state, const char *source)
{
    crm_debug("Invoked by %s in state: %s", source, fsa_state2string(cur_state));

    if (saved_ccm_membership_id != crm_peer_seq) {
        crm_debug("%s: Membership changed since join started: %llu -> %llu",
                 source, saved_ccm_membership_id, crm_peer_seq);
        register_fsa_input_before(C_FSA_INTERNAL, I_NODE_JOIN, NULL);

    } else if (cur_state == S_INTEGRATION) {
        if (g_hash_table_size(welcomed_nodes) == 0) {
            crm_debug("join-%d: Integration of %d peers complete: %s",
                      current_join_id, g_hash_table_size(integrated_nodes), source);
            register_fsa_input_before(C_FSA_INTERNAL, I_INTEGRATED, NULL);
            return TRUE;
        }

    } else if (cur_state == S_FINALIZE_JOIN) {
        if (is_set(fsa_input_register, R_HAVE_CIB) == FALSE) {
            crm_debug("join-%d: Delaying I_FINALIZED until we have the CIB", current_join_id);
            return TRUE;

        } else if (g_hash_table_size(integrated_nodes) == 0
                   && g_hash_table_size(finalized_nodes) == 0) {
            crm_debug("join-%d complete: %s", current_join_id, source);
            register_fsa_input_later(C_FSA_INTERNAL, I_FINALIZED, NULL);

        } else if (g_hash_table_size(integrated_nodes) != 0
                   && g_hash_table_size(finalized_nodes) != 0) {
            char *msg = NULL;

            crm_err("join-%d: Waiting on %d integrated nodes"
                    " AND %d finalized nodes",
                    current_join_id,
                    g_hash_table_size(integrated_nodes), g_hash_table_size(finalized_nodes));
            msg = strdup("Integrated node");
            g_hash_table_foreach(integrated_nodes, ghash_print_node, msg);
            free(msg);

            msg = strdup("Finalized node");
            g_hash_table_foreach(finalized_nodes, ghash_print_node, msg);
            free(msg);

        } else if (g_hash_table_size(integrated_nodes) != 0) {
            crm_debug("join-%d: Still waiting on %d integrated nodes",
                      current_join_id, g_hash_table_size(integrated_nodes));

        } else if (g_hash_table_size(finalized_nodes) != 0) {
            crm_debug("join-%d: Still waiting on %d finalized nodes",
                      current_join_id, g_hash_table_size(finalized_nodes));
        }
    }

    return FALSE;
}
Example #12
0
/*	 A_DC_JOIN_OFFER_ONE	*/
void
do_dc_join_offer_one(long long action,
                     enum crmd_fsa_cause cause,
                     enum crmd_fsa_state cur_state,
                     enum crmd_fsa_input current_input, fsa_data_t * msg_data)
{
    crm_node_t *member;
    ha_msg_input_t *welcome = NULL;

    const char *op = NULL;
    const char *join_to = NULL;

    if (msg_data->data) {
        welcome = fsa_typed_data(fsa_dt_ha_msg);

    } else {
        crm_info("A new node joined - wait until it contacts us");
        return;
    }

    if (welcome == NULL) {
        crm_err("Attempt to send welcome message without a message to reply to!");
        return;
    }

    join_to = crm_element_value(welcome->msg, F_CRM_HOST_FROM);
    if (join_to == NULL) {
        crm_err("Attempt to send welcome message without a host to reply to!");
        return;
    }

    member = crm_get_peer(0, join_to);
    if (crm_is_peer_active(member) == FALSE) {
        crm_err("%s is not a fully active member of our partition", join_to);
        return;
    }

    op = crm_element_value(welcome->msg, F_CRM_TASK);
    if (join_to != NULL && (cur_state == S_INTEGRATION || cur_state == S_FINALIZE_JOIN)) {
        /* note: it _is_ possible that a node will have been
         *  sick or starting up when the original offer was made.
         *  however, it will either re-announce itself in due course
         *  _or_ we can re-store the original offer on the client.
         */
        crm_trace("(Re-)offering membership to %s...", join_to);
    }

    crm_info("join-%d: Processing %s request from %s in state %s",
             current_join_id, op, join_to, fsa_state2string(cur_state));

    join_make_offer(NULL, member, NULL);

    /* always offer to the DC (ourselves)
     * this ensures the correct value for max_generation_from
     */
    member = crm_get_peer(0, fsa_our_uname);
    join_make_offer(NULL, member, NULL);

    /* this was a genuine join request, cancel any existing
     * transition and invoke the PE
     */
    start_transition(fsa_state);

    /* dont waste time by invoking the pe yet; */
    crm_debug("Waiting on %d outstanding join acks for join-%d",
              g_hash_table_size(welcomed_nodes), current_join_id);
}
Example #13
0
uint32_t
get_ht_size (GHashTable * ht)
{
  return g_hash_table_size (ht);
}
gboolean
gnc_xml_convert_single_file (const gchar *filename)
{
    GncXmlImportData *data;
    GtkWidget *widget;
    GtkBuilder *builder;
    gboolean success;

    data = g_new0 (GncXmlImportData, 1);
    data->filename = gnc_uri_get_path (filename);
    data->canceled = FALSE;

    /* gather ambiguous info */
    gxi_check_file (data);
    if (data->n_impossible == -1)
        return FALSE;

    if (!g_hash_table_size (data->ambiguous_ht))
    {
        /* no ambiguous strings */
        success = gxi_parse_file (data) &&
                  gxi_save_file (data);

        gxi_data_destroy (data);
    }
    else
    {
        /* common assistant initialization */
        builder = gtk_builder_new();
        gnc_builder_add_from_file  (builder , "assistant-xml-encoding.glade", "assistant_xml_encoding");
        data->assistant = GTK_WIDGET(gtk_builder_get_object (builder, "assistant_xml_encoding"));

        /* Enable buttons on all pages. */
        gtk_assistant_set_page_complete (GTK_ASSISTANT (data->assistant),
                                         GTK_WIDGET(gtk_builder_get_object(builder, "start_page")),
                                         TRUE);
        gtk_assistant_set_page_complete (GTK_ASSISTANT (data->assistant),
                                         GTK_WIDGET(gtk_builder_get_object(builder, "conversion_page")),
                                         TRUE);
        gtk_assistant_set_page_complete (GTK_ASSISTANT (data->assistant),
                                         GTK_WIDGET(gtk_builder_get_object(builder, "end_page")),
                                         TRUE);

        /* start page, explanations */
        gtk_assistant_set_page_title (GTK_ASSISTANT(data->assistant),
                                      gtk_assistant_get_nth_page (GTK_ASSISTANT(data->assistant), 0),
                                      gettext(encodings_doc_page_title));

        widget = GTK_WIDGET(gtk_builder_get_object (builder, "start_page"));
        gtk_label_set_text (GTK_LABEL(widget), gettext (encodings_doc_string));

        /* conversion page */
        data->default_encoding_hbox = GTK_WIDGET(gtk_builder_get_object (builder, "default_enc_box"));
        data->string_box_container = GTK_WIDGET(gtk_builder_get_object (builder, "string_box_container"));
        data->impossible_label = GTK_WIDGET(gtk_builder_get_object (builder, "impossible_label"));

        /* finish page */
        widget = GTK_WIDGET(gtk_builder_get_object(builder, "end_page"));
        gtk_label_set_text (GTK_LABEL(widget), gettext (finish_convert_string));

        gtk_builder_connect_signals(builder, data);

        gtk_widget_show_all (data->assistant);

        gxi_update_default_enc_combo (data);
        gxi_update_string_box (data);

        g_object_unref(G_OBJECT(builder));

        /* This won't return until the assistant is finished */
        gtk_main();

        if (data->canceled)
            success = FALSE;
        else
            success = gxi_save_file (data);
    }

    /* destroy all the data variables */
    gxi_data_destroy (data);
    g_free (data);

    return success;
}
Example #15
0
static guint
gcr_union_collection_real_get_length (GcrCollection *coll)
{
	GcrUnionCollection *self = GCR_UNION_COLLECTION (coll);
	return g_hash_table_size (self->pv->items);
}
Example #16
0
int backup(Jcr* jcr) {

	fingerchunk_queue = sync_queue_new(-1);
	ContainerUsageMonitor* usage_monitor = container_usage_monitor_new();
	cfl_monitor = cfl_monitor_new(read_cache_size);

	if (simulation_level == SIMULATION_ALL) {
		start_read_trace_phase(jcr);
	} else {
		start_read_phase(jcr);
		start_chunk_phase(jcr);
		start_hash_phase(jcr);
	}
	start_segment_phase(jcr);
	start_filter_phase(jcr);
	start_append_phase(jcr);

	ContainerId seed_id = -1;
	int32_t seed_len = 0;
	FingerChunk* fchunk = NULL;
	int signal = recv_fingerchunk(&fchunk);
	while (signal != STREAM_END) {
		container_usage_monitor_update(usage_monitor, fchunk->container_id,
				&fchunk->fingerprint, fchunk->length);
		jvol_append_fingerchunk(jcr->job_volume, fchunk);

		if (seed_id != -1 && seed_id != fchunk->container_id) {
			jvol_append_seed(jcr->job_volume, seed_id, seed_len);
			seed_len = 0;
		}
		/* merge sequential accesses */
		seed_id = fchunk->container_id;
		seed_len += fchunk->length;

		free(fchunk);
		signal = recv_fingerchunk(&fchunk);
	}

	if (seed_len > 0)
		jvol_append_seed(jcr->job_volume, seed_id, seed_len);
	sync_queue_free(fingerchunk_queue, NULL);

	jcr->sparse_container_num = g_hash_table_size(usage_monitor->sparse_map);
	jcr->total_container_num = g_hash_table_size(usage_monitor->dense_map)
			+ jcr->sparse_container_num;

	while ((jcr->inherited_sparse_num = container_usage_monitor_print(
			usage_monitor, jcr->job_id, jcr->historical_sparse_containers)) < 0) {
		dprint("retry!");
	}

	/* store recipes of processed file */
	int i = 0;
	for (; i < jcr->file_num; ++i) {
		Recipe *recipe = (Recipe*) sync_queue_pop(jcr->completed_files_queue);
		recipe->fileindex = i;
		if (jvol_append_meta(jcr->job_volume, recipe) != SUCCESS) {
			printf("%s, %d: some errors happened in appending recipe!\n",
			__FILE__, __LINE__);
			return FAILURE;
		}
		jcr->chunk_num += recipe->chunknum;
		recipe_free(recipe);
	}

	stop_append_phase();
	stop_filter_phase();
	stop_segment_phase();
	if (simulation_level == SIMULATION_ALL) {
		stop_read_trace_phase(jcr);
	} else {
		stop_hash_phase();
		stop_chunk_phase();
		stop_read_phase();
	}

	container_usage_monitor_free(usage_monitor);
	print_cfl(cfl_monitor);
	cfl_monitor_free(cfl_monitor);

	return 0;
}
Example #17
0
/**
 * gcr_union_collection_size:
 * @self: the union collection
 *
 * Return the number of collections in this union. This does not reflect
 * the number of objects in the combined collection.
 *
 * Returns: number of collections inlcuded
 */
guint
gcr_union_collection_size (GcrUnionCollection *self)
{
	g_return_val_if_fail (GCR_IS_UNION_COLLECTION (self), FALSE);
	return g_hash_table_size (self->pv->collections);
}
Example #18
0
gboolean
ostree_builtin_diff (int argc, char **argv, OstreeRepo *repo, GCancellable *cancellable, GError **error)
{
  gboolean ret = FALSE;
  GOptionContext *context;
  const char *src;
  const char *target;
  gs_free char *src_prev = NULL;
  gs_unref_object GFile *srcf = NULL;
  gs_unref_object GFile *targetf = NULL;
  gs_unref_ptrarray GPtrArray *modified = NULL;
  gs_unref_ptrarray GPtrArray *removed = NULL;
  gs_unref_ptrarray GPtrArray *added = NULL;

  context = g_option_context_new ("REV TARGETDIR - Compare directory TARGETDIR against revision REV");
  g_option_context_add_main_entries (context, options, NULL);

  if (!g_option_context_parse (context, &argc, &argv, error))
    goto out;

  if (argc < 2)
    {
      gchar *help = g_option_context_get_help (context, TRUE, NULL);
      g_printerr ("%s\n", help);
      g_free (help);
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                               "REV must be specified");
      goto out;
    }

  if (argc == 2)
    {
      src_prev = g_strconcat (argv[1], "^", NULL);
      src = src_prev;
      target = argv[1];
    }
  else
    {
      src = argv[1];
      target = argv[2];
    }

  if (!opt_stats && !opt_fs_diff)
    opt_fs_diff = TRUE;

  if (opt_fs_diff)
    {
      if (!parse_file_or_commit (repo, src, &srcf, cancellable, error))
        goto out;
      if (!parse_file_or_commit (repo, target, &targetf, cancellable, error))
        goto out;

      modified = g_ptr_array_new_with_free_func ((GDestroyNotify)ostree_diff_item_unref);
      removed = g_ptr_array_new_with_free_func ((GDestroyNotify)g_object_unref);
      added = g_ptr_array_new_with_free_func ((GDestroyNotify)g_object_unref);
      
      if (!ostree_diff_dirs (OSTREE_DIFF_FLAGS_NONE, srcf, targetf, modified, removed, added, cancellable, error))
        goto out;

      ostree_diff_print (srcf, targetf, modified, removed, added);
    }

  if (opt_stats)
    {
      gs_unref_hashtable GHashTable *reachable_a = NULL;
      gs_unref_hashtable GHashTable *reachable_b = NULL;
      gs_unref_hashtable GHashTable *reachable_intersection = NULL;
      gs_free char *rev_a = NULL;
      gs_free char *rev_b = NULL;
      gs_free char *size = NULL;
      guint a_size;
      guint b_size;
      guint64 total_common;

      if (!ostree_repo_resolve_rev (repo, src, FALSE, &rev_a, error))
        goto out;
      if (!ostree_repo_resolve_rev (repo, target, FALSE, &rev_b, error))
        goto out;

      if (!ostree_repo_traverse_commit (repo, rev_a, -1, &reachable_a, cancellable, error))
        goto out;
      if (!ostree_repo_traverse_commit (repo, rev_b, -1, &reachable_b, cancellable, error))
        goto out;

      a_size = g_hash_table_size (reachable_a);
      b_size = g_hash_table_size (reachable_b);
      g_print ("[A] Object Count: %u\n", a_size);
      g_print ("[B] Object Count: %u\n", b_size);

      reachable_intersection = reachable_set_intersect (reachable_a, reachable_b);

      g_print ("Common Object Count: %u\n", g_hash_table_size (reachable_intersection));

      if (!object_set_total_size (repo, reachable_intersection, &total_common,
                                  cancellable, error))
        goto out;
      size = g_format_size_full (total_common, 0);
      g_print ("Common Object Size: %s\n", size);
    }

  ret = TRUE;
 out:
  if (context)
    g_option_context_free (context);
  return ret;
}
static void
on_status_changed (TpYtsStatus *self,
    const gchar *contact_id,
    const gchar *capability,
    const gchar *service_name,
    const gchar *status,
    gpointer user_data,
    GObject *weak_object)
{
  GHashTable *capability_service;
  GHashTable *service_status;
  gboolean removing;

  removing = tp_str_empty (status);

  /* Dig out the capability/service dict */
  capability_service = g_hash_table_lookup (self->priv->discovered_statuses,
      contact_id);
  if (capability_service == NULL)
    {
      if (removing)
        return;
      capability_service = g_hash_table_new_full (g_str_hash, g_str_equal,
          g_free, (GDestroyNotify) g_hash_table_unref);
      g_hash_table_replace (self->priv->discovered_statuses,
          g_strdup (contact_id), capability_service);
    }

  /* Dig out the service/status dict */
  service_status = g_hash_table_lookup (capability_service, capability);
  if (service_status == NULL)
    {
      if (removing)
        return;
      service_status = g_hash_table_new_full (g_str_hash, g_str_equal, g_free,
          g_free);
      g_hash_table_replace (capability_service, g_strdup (capability),
          service_status);
    }

  if (removing)
    {
      g_hash_table_remove (service_status, service_name);
      if (g_hash_table_size (service_status) == 0)
        {
          g_hash_table_remove (capability_service, capability);
          if (g_hash_table_size (capability_service) == 0)
            {
              g_hash_table_remove (self->priv->discovered_statuses, contact_id);
            }
        }
    }
  else
    {
      g_hash_table_replace (service_status, g_strdup (service_name),
          g_strdup (status));
    }

  g_object_notify (G_OBJECT (self), "discovered-statuses");

  g_signal_emit (self, signals[STATUS_CHANGED], 0,
      contact_id, capability, service_name, status);
}
Example #20
0
static void
store_unread_mails (GabbleConnection *conn,
    WockyNode *mailbox)
{
  GabbleConnectionMailNotificationPrivate *priv = conn->mail_priv;
  GHashTableIter iter;
  GPtrArray *mails_removed;
  MailThreadCollector collector;
  const gchar *url, *unread_count;

  collector.conn = conn;
  collector.old_mails = priv->unread_mails;
  priv->unread_mails = g_hash_table_new_full (g_str_hash, g_str_equal,
      g_free, (GDestroyNotify) g_hash_table_unref);
  collector.mails_added = g_ptr_array_new ();

  url = wocky_node_get_attribute (mailbox, "url");
  g_free (priv->inbox_url);

  /* Use empty string to differentiate pending request from server failing to
     provide an URL.*/
  if (url != NULL)
    priv->inbox_url = g_strdup (url);
  else
    priv->inbox_url = g_strdup ("");

  /* Store new mails */
  wocky_node_each_child (mailbox, mail_thread_info_each, &collector);

  /* Generate the list of removed thread IDs */
  mails_removed = g_ptr_array_new_with_free_func (g_free);

  if (collector.old_mails != NULL)
    {
      gpointer key;

      g_hash_table_iter_init (&iter, collector.old_mails);

      while (g_hash_table_iter_next (&iter, &key, NULL))
        {
          gchar *tid = key;
          g_ptr_array_add (mails_removed, g_strdup (tid));
        }

      g_hash_table_unref (collector.old_mails);
    }
  g_ptr_array_add (mails_removed, NULL);

  unread_count = wocky_node_get_attribute (mailbox, "total-matched");

  if (unread_count != NULL)
    priv->unread_count = (guint)g_ascii_strtoll (unread_count, NULL, 0);
  else
    priv->unread_count = g_hash_table_size (priv->unread_mails);

  tp_svc_connection_interface_mail_notification_emit_unread_mails_changed (
      conn, priv->unread_count, collector.mails_added,
      (const char **)mails_removed->pdata);

  g_ptr_array_free (collector.mails_added, TRUE);
  g_ptr_array_free (mails_removed, TRUE);
}
static void
meta_monitor_manager_kms_read_current (MetaMonitorManager *manager)
{
  MetaMonitorManagerKms *manager_kms = META_MONITOR_MANAGER_KMS (manager);
  drmModeRes *resources;
  GHashTable *modes;
  GHashTableIter iter;
  drmModeModeInfo *mode;
  unsigned int i, j, k;
  unsigned int n_actual_outputs;
  int width, height;
  MetaOutput *old_outputs;
  unsigned int n_old_outputs;

  resources = drmModeGetResources(manager_kms->fd);
  modes = g_hash_table_new (drm_mode_hash, drm_mode_equal);

  manager->max_screen_width = resources->max_width;
  manager->max_screen_height = resources->max_height;

  manager->power_save_mode = META_POWER_SAVE_ON;

  old_outputs = manager->outputs;
  n_old_outputs = manager->n_outputs;

  /* Note: we must not free the public structures (output, crtc, monitor
     mode and monitor info) here, they must be kept alive until the API
     users are done with them after we emit monitors-changed, and thus
     are freed by the platform-independent layer. */
  free_resources (manager_kms);

  manager_kms->n_connectors = resources->count_connectors;
  manager_kms->connectors = g_new (drmModeConnector *, manager_kms->n_connectors);
  for (i = 0; i < manager_kms->n_connectors; i++)
    {
      drmModeConnector *connector;

      connector = drmModeGetConnector (manager_kms->fd, resources->connectors[i]);
      manager_kms->connectors[i] = connector;

      if (connector->connection == DRM_MODE_CONNECTED)
        {
          /* Collect all modes for this connector */
          for (j = 0; j < (unsigned)connector->count_modes; j++)
            g_hash_table_add (modes, &connector->modes[j]);
        }
    }

  manager_kms->n_encoders = resources->count_encoders;
  manager_kms->encoders = g_new (drmModeEncoder *, manager_kms->n_encoders);
  for (i = 0; i < manager_kms->n_encoders; i++)
    {
      manager_kms->encoders[i] = drmModeGetEncoder (manager_kms->fd,
                                                    resources->encoders[i]);
    }

  manager->n_modes = g_hash_table_size (modes);
  manager->modes = g_new0 (MetaMonitorMode, manager->n_modes);
  g_hash_table_iter_init (&iter, modes);
  i = 0;
  while (g_hash_table_iter_next (&iter, NULL, (gpointer)&mode))
    {
      MetaMonitorMode *meta_mode;

      meta_mode = &manager->modes[i];

      meta_mode->mode_id = i;
      meta_mode->name = g_strndup (mode->name, DRM_DISPLAY_MODE_LEN);
      meta_mode->width = mode->hdisplay;
      meta_mode->height = mode->vdisplay;
      meta_mode->refresh_rate = (1000 * mode->clock /
                                 ((float)mode->htotal * mode->vtotal));

      meta_mode->driver_private = g_slice_dup (drmModeModeInfo, mode);
      meta_mode->driver_notify = (GDestroyNotify)meta_monitor_mode_destroy_notify;

      i++;
    }
  g_hash_table_destroy (modes);

  manager->n_crtcs = resources->count_crtcs;
  manager->crtcs = g_new0 (MetaCRTC, manager->n_crtcs);
  width = 0; height = 0;
  for (i = 0; i < (unsigned)resources->count_crtcs; i++)
    {
      drmModeCrtc *crtc;
      MetaCRTC *meta_crtc;

      crtc = drmModeGetCrtc (manager_kms->fd, resources->crtcs[i]);

      meta_crtc = &manager->crtcs[i];

      meta_crtc->crtc_id = crtc->crtc_id;
      meta_crtc->rect.x = crtc->x;
      meta_crtc->rect.y = crtc->y;
      meta_crtc->rect.width = crtc->width;
      meta_crtc->rect.height = crtc->height;
      meta_crtc->is_dirty = FALSE;
      meta_crtc->transform = META_MONITOR_TRANSFORM_NORMAL;
      /* FIXME: implement! */
      meta_crtc->all_transforms = 1 << META_MONITOR_TRANSFORM_NORMAL;

      if (crtc->mode_valid)
        {
          for (j = 0; j < manager->n_modes; j++)
            {
              if (drm_mode_equal (&crtc->mode, manager->modes[j].driver_private))
                {
                  meta_crtc->current_mode = &manager->modes[j];
                  break;
                }
            }

          width = MAX (width, meta_crtc->rect.x + meta_crtc->rect.width);
          height = MAX (height, meta_crtc->rect.y + meta_crtc->rect.height);
        }

      drmModeFreeCrtc (crtc);
    }

  manager->screen_width = width;
  manager->screen_height = height;

  manager->outputs = g_new0 (MetaOutput, manager_kms->n_connectors);
  n_actual_outputs = 0;

  for (i = 0; i < manager_kms->n_connectors; i++)
    {
      MetaOutput *meta_output, *old_output;
      MetaOutputKms *output_kms;
      drmModeConnector *connector;
      GArray *crtcs;
      unsigned int crtc_mask;
      GBytes *edid;

      connector = manager_kms->connectors[i];
      meta_output = &manager->outputs[n_actual_outputs];

      if (connector->connection == DRM_MODE_CONNECTED)
	{
          meta_output->driver_private = output_kms = g_slice_new0 (MetaOutputKms);
          meta_output->driver_notify = (GDestroyNotify)meta_output_destroy_notify;

	  meta_output->winsys_id = connector->connector_id;
	  meta_output->name = make_output_name (connector);
	  meta_output->width_mm = connector->mmWidth;
	  meta_output->height_mm = connector->mmHeight;

          switch (connector->subpixel)
            {
            case DRM_MODE_SUBPIXEL_NONE:
              meta_output->subpixel_order = COGL_SUBPIXEL_ORDER_NONE;
              break;
            case DRM_MODE_SUBPIXEL_HORIZONTAL_RGB:
              meta_output->subpixel_order = COGL_SUBPIXEL_ORDER_HORIZONTAL_RGB;
              break;
            case DRM_MODE_SUBPIXEL_HORIZONTAL_BGR:
              meta_output->subpixel_order = COGL_SUBPIXEL_ORDER_HORIZONTAL_BGR;
              break;
            case DRM_MODE_SUBPIXEL_VERTICAL_RGB:
              meta_output->subpixel_order = COGL_SUBPIXEL_ORDER_VERTICAL_RGB;
              break;
            case DRM_MODE_SUBPIXEL_VERTICAL_BGR:
              meta_output->subpixel_order = COGL_SUBPIXEL_ORDER_VERTICAL_BGR;
              break;
            case DRM_MODE_SUBPIXEL_UNKNOWN:
            default:
              meta_output->subpixel_order = COGL_SUBPIXEL_ORDER_UNKNOWN;
              break;
            }

	  meta_output->n_modes = connector->count_modes;
	  meta_output->modes = g_new0 (MetaMonitorMode *, meta_output->n_modes);
	  for (j = 0; j < meta_output->n_modes; j++)
            meta_output->modes[j] = find_meta_mode (manager, &connector->modes[j]);
	  meta_output->preferred_mode = meta_output->modes[0];

          output_kms->connector = connector;
          output_kms->n_encoders = connector->count_encoders;
          output_kms->encoders = g_new0 (drmModeEncoderPtr, output_kms->n_encoders);

          crtc_mask = ~(unsigned int)0;
	  for (j = 0; j < output_kms->n_encoders; j++)
	    {
              output_kms->encoders[j] = drmModeGetEncoder (manager_kms->fd, connector->encoders[j]);

              /* We only list CRTCs as supported if they are supported by all encoders
                 for this connectors.

                 This is what xf86-video-modesetting does (see drmmode_output_init())
              */
              crtc_mask &= output_kms->encoders[j]->possible_crtcs;

              if (output_kms->encoders[j]->encoder_id == connector->encoder_id)
                output_kms->current_encoder = output_kms->encoders[j];
            }

          crtcs = g_array_new (FALSE, FALSE, sizeof (MetaCRTC*));

          for (j = 0; j < manager->n_crtcs; j++)
            {
              if (crtc_mask & (1 << j))
                {
                  MetaCRTC *crtc = &manager->crtcs[j];
                  g_array_append_val (crtcs, crtc);
		}
	    }

	  meta_output->n_possible_crtcs = crtcs->len;
	  meta_output->possible_crtcs = (void*)g_array_free (crtcs, FALSE);

          if (output_kms->current_encoder && output_kms->current_encoder->crtc_id != 0)
            {
              for (j = 0; j < manager->n_crtcs; j++)
                {
                  if (manager->crtcs[j].crtc_id == output_kms->current_encoder->crtc_id)
                    {
                      meta_output->crtc = &manager->crtcs[j];
                      break;
                    }
                }
            }
          else
            meta_output->crtc = NULL;

          old_output = find_output_by_id (old_outputs, n_old_outputs,
                                          meta_output->winsys_id);
          if (old_output)
            {
              meta_output->is_primary = old_output->is_primary;
              meta_output->is_presentation = old_output->is_presentation;
            }
          else
            {
              meta_output->is_primary = FALSE;
              meta_output->is_presentation = FALSE;
            }

          find_properties (manager_kms, output_kms);

          edid = read_output_edid (manager_kms, meta_output);
          if (edid)
            {
              MonitorInfo *parsed_edid;
              gsize len;

              parsed_edid = decode_edid (g_bytes_get_data (edid, &len));
              if (parsed_edid)
                {
                  meta_output->vendor = g_strndup (parsed_edid->manufacturer_code, 4);
                  meta_output->product = g_strndup (parsed_edid->dsc_product_name, 14);
                  meta_output->serial = g_strndup (parsed_edid->dsc_serial_number, 14);

                  g_free (parsed_edid);
                }

              g_bytes_unref (edid);
            }
          if (!meta_output->vendor)
            {
              meta_output->vendor = g_strdup ("unknown");
              meta_output->product = g_strdup ("unknown");
              meta_output->serial = g_strdup ("unknown");
            }

          /* FIXME: backlight is a very driver specific thing unfortunately,
             every DDX does its own thing, and the dumb KMS API does not include it.

             For example, xf86-video-intel has a list of paths to probe in /sys/class/backlight
             (one for each major HW maker, and then some).
             We can't do the same because we're not root.
             It might be best to leave backlight out of the story and rely on the setuid
             helper in gnome-settings-daemon.
          */
	  meta_output->backlight_min = 0;
          meta_output->backlight_max = 0;
          meta_output->backlight = -1;

	  n_actual_outputs++;
	}
    }
Example #22
0
gboolean
gkm_xdg_trust_have_assertion (GkmXdgTrust *self)
{
	g_return_val_if_fail (GKM_XDG_IS_TRUST (self), FALSE);
	return g_hash_table_size (self->pv->assertions);
}
Example #23
0
GstGraveyard *
gst_graveyard_new_from_trace (const char *filename, GstClockTime from, GstClockTime till, gboolean query_duration_only)
{
  FILE *input = fopen (filename,  "rt");
  if (input == NULL)
    return NULL;
  
  GstGraveyard *graveyard = g_new0(GstGraveyard, 1);
  
  graveyard->tasks = g_hash_table_new (g_direct_hash, g_direct_equal);
  graveyard->elements = g_hash_table_new (g_direct_hash, g_direct_equal);
  
  while (!feof (input)) {
    GstClockTime event_timestamp;
    gchar event_name[1000];
    if (fscanf (input, "%" G_GUINT64_FORMAT " %s", &event_timestamp, event_name) != 2) {
      break;
    }
    
    if (event_timestamp > graveyard->duration)
      graveyard->duration = event_timestamp;
    
    if (query_duration_only)
    {
      gchar buffer[1024];
      fgets (buffer, sizeof (buffer), input);
      continue;
    }
    
    if (g_ascii_strcasecmp (event_name, "element-discovered") == 0) {
      gpointer element_id;
      gpointer parent_element_id;
      gchar element_name[1000];
      gchar element_type_name[1000];
      if (fscanf (input, "%p %s %s %p\n", &element_id, element_name, element_type_name, &parent_element_id) == 4) {
        GstElementHeadstone *element = gst_graveyard_get_element (graveyard, element_id, element_name);
        if (parent_element_id) {
          GstElementHeadstone *parent = gst_graveyard_get_element (graveyard, parent_element_id, NULL);
          if (element->type_name == NULL)
            element->type_name = g_string_new (element_type_name);
          gst_element_headstone_add_child (parent, element);
        }
      } else {
        g_print ("couldn't parse event: %s\n", event_name);
        goto error;
      }
    } else if (g_ascii_strcasecmp (event_name, "element-entered") == 0) {
      gpointer task_id;
      gchar from_element_name[1000];
      gpointer from_element_id;
      gchar element_name[1000];
      gpointer element_id;
      guint64 thread_time;
      if (fscanf (input, "%p %s %p %s %p %" G_GUINT64_FORMAT "\n", &task_id, from_element_name, &from_element_id, element_name, &element_id, &thread_time) == 6) {
        GstElementHeadstone *element = gst_graveyard_get_element (graveyard, element_id, element_name);
        
        g_assert_true (element != NULL);
        
        GstTaskHeadstone *task = g_hash_table_lookup (graveyard->tasks, task_id);
        if (!task) {
          task = g_new0 (GstTaskHeadstone, 1);
          task->identifier = task_id;
          task->total_upstack_time = 0;
          task->upstack_enter_timestamp = 0;
          task->currently_in_upstack_element = TRUE;
          task->name = NULL;
          task->upstack_element_identifier = NULL;
          g_hash_table_insert (graveyard->tasks, task_id, task);
        }
        
        g_assert_true (task != NULL);
        
        if (task->currently_in_upstack_element) {
          element->is_subtopstack = TRUE;
          task->upstack_exit_timestamp = thread_time;
          if ((task->upstack_enter_timestamp > 0) && TIMESTAMP_FITS (event_timestamp, from, till))
            task->total_upstack_time += task->upstack_exit_timestamp - task->upstack_enter_timestamp;
          task->currently_in_upstack_element = FALSE;
          if (task->name == NULL) {
            task->upstack_element_identifier = from_element_id;
            task->name = g_string_new (from_element_name);
          }
        } else {
          element->is_subtopstack = FALSE;
        }
        if (TIMESTAMP_FITS (event_timestamp, from, till))
          task->total_downstack_time += task->current_downstack_time;
        task->current_downstack_time = 0;
      } else {
        g_print ("couldn't parse event: %s\n", event_name);
        goto error;
      }
    }
    else if (g_ascii_strcasecmp (event_name, "data-sent") == 0)
    {
      gchar mode[2];
      GstPadMode pad_mode;
      gpointer element_from;
      gpointer element_to;
      gpointer pad_from;
      gpointer pad_to;
      gint buffers_count;
      guint64 size;
      if (fscanf (input, "%1s %p %p %p %p %d %" G_GUINT64_FORMAT "\n", mode, &element_from, &pad_from, &element_to, &pad_to, &buffers_count, &size) == 7) {
        GstElementHeadstone *element = gst_graveyard_get_element (graveyard, element_from, NULL);
        pad_mode = mode[0] == 'l' ? GST_PAD_MODE_PULL : GST_PAD_MODE_PUSH;
        
        if (TIMESTAMP_FITS (event_timestamp, from, till)) {
          element->bytes_sent += size;
          
          GstPadHeadstone *pad = g_hash_table_lookup (element->pads, pad_from);
          if (!pad)
          {
            pad = g_new0 (GstPadHeadstone, 1);
            pad->identifier = pad_from;
            pad->parent_element = element_from;
            pad->peer = pad_to;
            pad->peer_element = element_to;
            pad->mode = pad_mode;
            pad->bytes = 0;
            pad->direction = GST_PAD_SRC;
            g_hash_table_insert (element->pads, pad_from, pad);
          }
          pad->bytes += size;
        }
        
        element = gst_graveyard_get_element (graveyard, element_to, NULL);
        
        if (TIMESTAMP_FITS (event_timestamp, from, till)) {
          element->bytes_received += size;
          
          GstPadHeadstone *pad = g_hash_table_lookup (element->pads, pad_to);
          if (!pad)
          {
            pad = g_new0 (GstPadHeadstone, 1);
            pad->identifier = pad_to;
            pad->parent_element = element_to;
            pad->peer = pad_from;
            pad->peer_element = element_from;
            pad->mode = pad_mode;
            pad->bytes = 0;
            pad->direction = GST_PAD_SINK;
            g_hash_table_insert (element->pads, pad_to, pad);
          }
          pad->bytes += size;
        }
      } else {
        g_print ("couldn't parse event: %s\n", event_name);
        goto error;
      }
    } else if (g_ascii_strcasecmp (event_name, "element-exited") == 0) {
      gpointer task_id;
      gchar element_name[1000];
      gpointer element_id;
      guint64 thread_time;
      guint64 duration;
      if (fscanf (input, "%p %s %p %" G_GUINT64_FORMAT " %" G_GUINT64_FORMAT "\n", &task_id, element_name, &element_id, &thread_time, &duration) == 5) {
        GstTaskHeadstone *task = g_hash_table_lookup (graveyard->tasks, task_id);
        if (!task) {
          g_print ("couldn't find task %p\n", task_id);
          goto error;
        }
        GstElementHeadstone *element = g_hash_table_lookup (graveyard->elements, element_id);
        if (!element) {
          g_print ("couldn't find element %p: %s\n", element_id, element_name);
          goto error;
        }
        if (TIMESTAMP_FITS (event_timestamp, from, till))
          element->total_cpu_time += duration - task->current_downstack_time;
        task->current_downstack_time = duration;
        if (element->is_subtopstack) {
          task->upstack_enter_timestamp = thread_time;
          task->currently_in_upstack_element = TRUE;
        } else {
          task->currently_in_upstack_element = FALSE;
        }
      } else {
        g_print ("couldn't parse event: %s\n", event_name);
        goto error;
      }
    } else if (g_ascii_strcasecmp (event_name, "task") == 0) {
      gpointer task_id;
      if (fscanf (input, "%p\n", &task_id) != 1) {
        g_print ("couldn't parse task\n");
        goto error;
      }
    } else {
      g_print ("couldn't recognize event: %s\n", event_name);
      goto error;
    }
  }
  fclose (input);
  
  g_hash_table_foreach (graveyard->tasks, for_each_task, graveyard);
  
  gint elements_count = g_hash_table_size (graveyard->elements);
  graveyard->elements_sorted = g_array_sized_new (FALSE, FALSE, sizeof (gpointer), elements_count);
  graveyard->from = (from == GST_CLOCK_TIME_NONE) ? 0 : from;
  graveyard->till = (till == GST_CLOCK_TIME_NONE) ? graveyard->duration : till;
  g_hash_table_foreach (graveyard->elements, for_each_element, graveyard);
  g_array_sort (graveyard->elements_sorted, element_headstone_compare);
  
  return graveyard;
  
error:
  gst_graveyard_free (graveyard);
  return NULL;
}
Example #24
0
void vfs_dir_finalize( GObject *obj )
{
    VFSDir * dir = VFS_DIR( obj );
//printf("vfs_dir_finalize  %s\n", dir->path );
    do{}
    while( g_source_remove_by_user_data( dir ) );

    if( G_UNLIKELY( dir->task ) )
    {
        g_signal_handlers_disconnect_by_func( dir->task, on_list_task_finished, dir );
        /* FIXME: should we generate a "file-list" signal to indicate the dir loading was cancelled? */
//printf("spacefm: vfs_dir_finalize -> vfs_async_task_cancel\n");
        vfs_async_task_cancel( dir->task );
        g_object_unref( dir->task );
        dir->task = NULL;
    }
    if ( dir->monitor )
    {
        vfs_file_monitor_remove( dir->monitor,
                                 vfs_dir_monitor_callback,
                                 dir );
    }
    if ( dir->path )
    {
        if( G_LIKELY( dir_hash ) )
        {
            g_hash_table_remove( dir_hash, dir->path );

            /* There is no VFSDir instance */
            if ( 0 == g_hash_table_size( dir_hash ) )
            {
                g_hash_table_destroy( dir_hash );
                dir_hash = NULL;

                vfs_mime_type_remove_reload_cb( mime_cb );
                mime_cb = NULL;

                if( change_notify_timeout )
                {
                    g_source_remove( change_notify_timeout );
                    change_notify_timeout = 0;
                }

                g_signal_handler_disconnect( gtk_icon_theme_get_default(),
                                                                theme_change_notify );
                theme_change_notify = 0;
            }
        }
        g_free( dir->path );
        g_free( dir->disp_path );
        dir->path = dir->disp_path = NULL;
    }
    /* g_debug( "dir->thumbnail_loader: %p", dir->thumbnail_loader ); */
    if( G_UNLIKELY( dir->thumbnail_loader ) )
    {
        /* g_debug( "FREE THUMBNAIL LOADER IN VFSDIR" ); */
        vfs_thumbnail_loader_free( dir->thumbnail_loader );
        dir->thumbnail_loader = NULL;
    }

    if ( dir->file_list )
    {
        g_list_foreach( dir->file_list, ( GFunc ) vfs_file_info_unref, NULL );
        g_list_free( dir->file_list );
        dir->file_list = NULL;
        dir->n_files = 0;
    }

    if( dir->changed_files )
    {
        g_slist_foreach( dir->changed_files, (GFunc)vfs_file_info_unref, NULL );
        g_slist_free( dir->changed_files );
        dir->changed_files = NULL;
    }

    if( dir->created_files )
    {
        g_slist_foreach( dir->created_files, (GFunc)g_free, NULL );
        g_slist_free( dir->created_files );
        dir->created_files = NULL;
    }

    g_mutex_free( dir->mutex );
    G_OBJECT_CLASS( parent_class ) ->finalize( obj );
}
Example #25
0
static gboolean
load_pitivi_file_from_uri (GESFormatter * self,
    GESTimeline * timeline, const gchar * uri, GError ** error)
{
  xmlDocPtr doc;
  GESLayer *layer;
  GESPitiviFormatterPrivate *priv = GES_PITIVI_FORMATTER (self)->priv;

  gboolean ret = TRUE;
  gint *prio = malloc (sizeof (gint));

  *prio = 0;
  layer = ges_layer_new ();
  g_object_set (layer, "auto-transition", TRUE, NULL);

  g_hash_table_insert (priv->layers_table, prio, layer);
  g_object_set (layer, "priority", (gint32) 0, NULL);

  if (!ges_timeline_add_layer (timeline, layer)) {
    GST_ERROR ("Couldn't add layer");
    return FALSE;
  }

  if (!(doc = xmlParseFile (uri))) {
    GST_ERROR ("The xptv file for uri %s was badly formed or did not exist",
        uri);
    return FALSE;
  }

  priv->xpathCtx = xmlXPathNewContext (doc);

  if (self->project)
    parse_metadatas (self);

  if (!create_tracks (self)) {
    GST_ERROR ("Couldn't create tracks");
    return FALSE;
  }

  list_sources (self);

  if (!parse_clips (self)) {
    GST_ERROR ("Couldn't find clips markup in the xptv file");
    return FALSE;
  }

  if (!parse_track_elements (self)) {
    GST_ERROR ("Couldn't find track objects markup in the xptv file");
    return FALSE;
  }



  /* If there are no clips to load we should emit
   * 'project-loaded' signal.
   */
  if (!g_hash_table_size (priv->clips_table) && GES_FORMATTER (self)->project) {
    ges_project_set_loaded (GES_FORMATTER (self)->project,
        GES_FORMATTER (self));
  } else {
    if (!make_clips (self)) {
      GST_ERROR ("Couldn't deserialise the project properly");
      return FALSE;
    }
  }

  xmlXPathFreeContext (priv->xpathCtx);
  xmlFreeDoc (doc);
  return ret;
}
Example #26
0
void close_har() {
	sds fname = sdsdup(destor.working_directory);
	fname = sdscat(fname, "recipes/bv");
	char s[20];
	sprintf(s, "%d", jcr.id);
	fname = sdscat(fname, s);
	fname = sdscat(fname, ".sparse");

	FILE* fp = fopen(fname, "w");
	if (!fp) {
		fprintf(stderr, "Can not create sparse file");
		perror("The reason is");
		exit(1);
	}

	jcr.total_container_num = g_hash_table_size(container_utilization_monitor);

	GSequence *seq = g_sequence_new(NULL);
	int64_t total_size = 0;
	int64_t sparse_size = 0;

	/* collect sparse containers */
	GHashTableIter iter;
	gpointer key, value;
	g_hash_table_iter_init(&iter, container_utilization_monitor);
	while (g_hash_table_iter_next(&iter, &key, &value)) {
		struct containerRecord* cr = (struct containerRecord*) value;
		total_size += cr->size;

		if((1.0*cr->size/(CONTAINER_SIZE - CONTAINER_META_SIZE))
				< destor.rewrite_har_utilization_threshold){
			/* It is sparse */
			if (inherited_sparse_containers
					&& g_hash_table_lookup(inherited_sparse_containers, &cr->cid))
				/* It is an inherited sparse container */
				jcr.inherited_sparse_num++;

			jcr.sparse_container_num++;
			sparse_size += cr->size;

			g_sequence_insert_sorted(seq, cr, g_record_cmp, NULL);
		}
	}

	/*
	 * If the sparse size is too large,
	 * we need to trim the sequence to control the rewrite ratio.
	 * We use sparse_size/total_size to estimate the rewrite ratio of next backup.
	 * However, the estimation is inaccurate (generally over-estimating), since:
	 * 	1. the sparse size is not an accurate indicator of utilization for next backup.
	 * 	2. self-references.
	 */
	while(sparse_size*1.0/total_size > destor.rewrite_har_rewrite_limit){
		/*
		 * The expected rewrite ratio exceeds the limit.
		 * We trim the last several records in the sequence.
		 * */
		GSequenceIter* iter = g_sequence_iter_prev(g_sequence_get_end_iter(seq));
		struct containerRecord* r = g_sequence_get(iter);
		NOTICE("Trim sparse container %lld", r->cid);
		sparse_size -= r->size;
		g_sequence_remove(iter);
	}

	GSequenceIter* sparse_iter = g_sequence_get_begin_iter(seq);
	while(sparse_iter != g_sequence_get_end_iter(seq)){
		struct containerRecord* r = g_sequence_get(sparse_iter);
		fprintf(fp, "%lld %d\n", r->cid, r->size);
		sparse_iter = g_sequence_iter_next(sparse_iter);
	}
	fclose(fp);

	NOTICE("Record %d sparse containers, and %d of them are inherited",
			g_sequence_get_length(seq),	jcr.inherited_sparse_num);

	g_sequence_free(seq);
	sdsfree(fname);
}
Example #27
0
static void hev_scgi_handler_cgi_handle(HevSCGIHandler *handler, GObject *scgi_task)
{
	HevSCGIHandlerCGI *self = HEV_SCGI_HANDLER_CGI(handler);
	HevSCGIHandlerCGIPrivate *priv = HEV_SCGI_HANDLER_CGI_GET_PRIVATE(self);

	HevSCGIHandlerCGITaskData *task_data = NULL;
	gchar *str = NULL, **argv = NULL, *workdir = NULL;
	GPid pid = 0;
	GError *error = NULL;
	GObject *connection = NULL;
	GSocket *socket = NULL;

	g_debug("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);

	task_data = g_slice_new0(HevSCGIHandlerCGITaskData);
	if(!task_data)
	{
		g_critical("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);
		return;
	}

	connection = hev_scgi_task_get_socket_connection(HEV_SCGI_TASK(scgi_task));
	socket = g_socket_connection_get_socket(G_SOCKET_CONNECTION(connection));
	task_data->fd = g_socket_get_fd(socket);

	task_data->scgi_task = scgi_task;
	task_data->scgi_request = hev_scgi_task_get_request(HEV_SCGI_TASK(scgi_task));
	task_data->scgi_response = hev_scgi_task_get_response(HEV_SCGI_TASK(scgi_task));
	task_data->req_hash_table =
		hev_scgi_request_get_header_hash_table(HEV_SCGI_REQUEST(task_data->scgi_request));

	task_data->envp =
		g_malloc0_n(g_hash_table_size(task_data->req_hash_table)+1, sizeof(gchar *));
	g_hash_table_foreach(task_data->req_hash_table, req_hash_table_foreach_handler, task_data);

	/* Script file and Work dir */
	str = g_hash_table_lookup(task_data->req_hash_table, "SCRIPT_FILE");
	argv = g_malloc0_n(2, sizeof(gchar *));
	if(str)
	{
		argv[0] = g_strdup(str);
		workdir = g_path_get_dirname(str);
	}
	else
	{
		argv[0] = g_key_file_get_string(priv->config, "Module", "CGIBinPath", NULL);
		workdir = g_key_file_get_string(priv->config, "Module", "WorkDir", NULL);

		if(NULL == argv[0])
		  argv[0] = g_strdup(HEV_SCGI_HANDLER_CGI_BIN_PATH);
		if(NULL == workdir)
		  workdir = g_strdup(HEV_SCGI_HANDLER_CGI_WORK_DIR);
	}

#ifdef G_OS_UNIX
	/* User and Group */
	str = g_hash_table_lookup(task_data->req_hash_table, "_USER");
	if(str)
	  task_data->user = g_strdup(str);
	else
	  task_data->user = g_key_file_get_string(priv->config, "Module", "User", NULL);

	str = g_hash_table_lookup(task_data->req_hash_table, "_GROUP");
	if(str)
	  task_data->group = g_strdup(str);
	else
	  task_data->group = g_key_file_get_string(priv->config, "Module", "Group", NULL);
#endif /* G_OS_UNIX */

	if(g_spawn_async(workdir, argv, task_data->envp, G_SPAWN_DO_NOT_REAP_CHILD,
					hev_scgi_handler_spawn_child_setup_handler,
					task_data, &pid, &error))
	{
		g_object_ref(scgi_task);
		g_child_watch_add(pid, hev_scgi_handler_child_watch_handler, task_data);
	}
	else
	{
		g_critical("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
					__FUNCTION__, error->message);
		g_error_free(error);
	}

	g_strfreev(argv);
	g_free(workdir);
}
Example #28
0
static guint
gcr_simple_collection_real_get_length (GcrCollection *coll)
{
	GcrSimpleCollection *self = GCR_SIMPLE_COLLECTION (coll);
	return g_hash_table_size (self->pv->items);
}
Example #29
0
// Store (key,value) pairs from a GHashTable in the kwallet.
// Every 'slot' has to take care of it's own data.
gboolean dt_pwstorage_kwallet_set(const backend_kwallet_context_t *context, const gchar* slot, GHashTable* table)
{
  printf("slot %s\n", slot);

  GArray* byte_array = g_array_new(FALSE, FALSE, sizeof(gchar));

  GHashTableIter iter;
  g_hash_table_iter_init (&iter, table);
  gpointer key, value;

  guint size = g_hash_table_size(table);

  size = GINT_TO_BE(size);

  g_array_append_vals(byte_array, &size, sizeof(guint)/sizeof(gchar));

  while (g_hash_table_iter_next (&iter, &key, &value))
  {
    dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_kwallet_set] storing (%s, %s)\n",(gchar*)key, (gchar*)value);
    gsize length;
    gchar* new_key = char2qstring(key, &length);
    if(new_key == NULL)
    {
      g_free(g_array_free(byte_array, FALSE));
      return FALSE;
    }
    g_array_append_vals(byte_array, new_key, length);
    g_free(new_key);

    gchar* new_value = char2qstring(value, &length);
    if(new_value == NULL)
    {
      g_free(g_array_free(byte_array, FALSE));
      return FALSE;
    }
    g_array_append_vals(byte_array, new_value, length);
    g_free(new_value);
  }

  int wallet_handle = get_wallet_handle(context);
  GError* error = NULL;

  /* signature:
   *
   * in  i handle,
   * in  s folder,
   * in  s key,
   * in  ay value,
   * in  s appid,
   *
   * out i arg_0
   */
  GVariant *ret = g_dbus_proxy_call_sync(context->proxy,
                                         "writeMap",
                                         g_variant_new("(iss@ays)", wallet_handle, kwallet_folder, slot,
                                             g_variant_new_from_data(G_VARIANT_TYPE_BYTESTRING,
                                                 byte_array->data,
                                                 byte_array->len,
                                                 TRUE,
                                                 g_free,
                                                 byte_array->data),
                                             app_id),
                                         G_DBUS_CALL_FLAGS_NONE,
                                         -1,
                                         NULL,
                                         &error);

  g_array_free(byte_array, FALSE);

  if(check_error(error))
  {
    g_variant_unref(ret);
    return FALSE;
  }

  GVariant *child = g_variant_get_child_value(ret, 0);
  int return_code = g_variant_get_int32(child);
  g_variant_unref(child);
  g_variant_unref(ret);

  if (return_code != 0)
    dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_kwallet_set] Warning: bad return code %d from kwallet\n", return_code);

  return return_code == 0;
}
Example #30
0
int recent_get_remote_host_list_size(void)
{
  return g_hash_table_size (remote_host_list);
}