示例#1
0
static struct oh_handler *new_handler(GHashTable *handler_config)
{       /* Return a new oh_handler instance */
        struct oh_plugin *plugin = NULL;
        struct oh_handler *handler = NULL;
	char *plugin_name = NULL;
        static unsigned int handler_id = 1;
        unsigned int *hidp;

        if (!handler_config) {
                dbg("ERROR creating new handler. Invalid parameter.");
                return NULL;
        }

	plugin_name = (char *)g_hash_table_lookup(handler_config, "plugin");
	if (!plugin_name) {
		dbg("ERROR creating new handler. No plugin name received.");
		return NULL;
	}

        handler = (struct oh_handler *)g_malloc0(sizeof(struct oh_handler));
        hidp = (unsigned int *)g_malloc0(sizeof(unsigned int));

        plugin = oh_get_plugin(plugin_name);
        if(!plugin) { /* Attempt to load plugin here once */
		int rc = oh_load_plugin(plugin_name);
		if (rc) {
                	dbg("Could not create handler. Plugin %s not loaded",
                    	    plugin_name);
                	goto cleanexit;
		}

		plugin = oh_get_plugin(plugin_name);
		if (!plugin) {
			dbg("Tried but could not get a plugin to "
			    "create this handler.");
			goto cleanexit;
		}
        }

        /* Initialize handler */
        handler->abi = plugin->abi;
        plugin->handler_count++; /* Increment # of handlers using the plugin */
        oh_release_plugin(plugin);
        g_static_rec_mutex_lock(&oh_handlers.lock);
        handler->id = handler_id++;
        g_static_rec_mutex_unlock(&oh_handlers.lock);
        *hidp = handler->id;
        handler->plugin_name = (char *)g_hash_table_lookup(handler_config, "plugin");
        handler->config = handler_config;
        handler->refcount = 0;
        g_static_rec_mutex_init(&handler->lock);
        g_static_rec_mutex_init(&handler->refcount_lock);

        return handler;
cleanexit:
        g_free(hidp);
        g_free(handler);
        return NULL;
}
示例#2
0
/**
 * oh_create_domain
 * @capabilities:
 * @isPeer:
 * @tag:
 *
 *
 *
 * Returns: Domain id of newly created domain, or 0 if failed to create.
 **/
SaHpiDomainIdT oh_create_domain(SaHpiDomainCapabilitiesT capabilities,
                                SaHpiTimeoutT   aitimeout,
                                SaHpiTextBufferT *tag)
{
        struct oh_domain *domain = NULL;
        static SaHpiDomainIdT id = OH_FIRST_DOMAIN; /* domain ids will start at 1 */
        struct oh_global_param param = { .type = OPENHPI_DEL_SIZE_LIMIT };
        char del_filepath[SAHPI_MAX_TEXT_BUFFER_LENGTH*2];

        domain = g_new0(struct oh_domain,1);
        if (!domain) return 0;

        domain->capabilities = capabilities;
        domain->ai_timeout = aitimeout;
        domain->is_peer = SAHPI_FALSE;
        oh_init_rpt(&(domain->rpt));

        if (tag)
                memcpy(&(domain->tag), tag, sizeof(SaHpiTextBufferT));

        oh_get_global_param(&param);

        domain->del = oh_el_create(param.u.del_size_limit);
        domain->sessions = g_array_sized_new(FALSE, TRUE,
                                             sizeof(SaHpiSessionIdT),
                                             OH_SESSION_PREALLOC);

        g_static_rec_mutex_init(&(domain->lock));
        g_static_rec_mutex_init(&(domain->refcount_lock));

        if (!domain->del || !domain->sessions) {
                g_free(domain->del);
                g_array_free(domain->sessions, TRUE);
                g_static_rec_mutex_free(&(domain->lock));
                g_static_rec_mutex_free(&(domain->refcount_lock));
                g_free(domain);
                return 0;
        }

        param.type = OPENHPI_DEL_SAVE;
        oh_get_global_param(&param);

        g_static_rec_mutex_lock(&(oh_domains.lock)); /* Locked domain table */
        domain->id = id++;
        if (param.u.del_save) {
                param.type = OPENHPI_VARPATH;
                oh_get_global_param(&param);
                snprintf(del_filepath,
                         SAHPI_MAX_TEXT_BUFFER_LENGTH*2,
                         "%s/del.%u", param.u.varpath, domain->id);
                oh_el_map_from_file(domain->del, del_filepath);
        }
        g_hash_table_insert(oh_domains.table, &(domain->id), domain);
        g_static_rec_mutex_unlock(&(oh_domains.lock));  /* Unlocked domain table */

        return domain->id;
}
CGenericCanvas::CGenericCanvas(GCContext Context, wstring name): CGCBase(NULL)
{ 
  FCanvas = this;
  _className = "CGenericCanvas";
  FName = name;
  FContext = Context;
  FCurrentView = NULL;
  FStates = 0;

#ifdef _WINDOWS
  InitializeCriticalSection(&FLock);
#else
  g_static_rec_mutex_init(&FLock);
#endif

  FListener.canvas = this;
  FModel = new CGCModel(this);
  FModel->addListener(&FListener);
  FAnimationManager = new CAnimationManager(this);

  determineExtensions();
  initializeOpenGLExtensions();

  // Set a new lock on the font manager (and create it by the way if not yet done).
  lockFontManager();
}
void
rb_threads_init (void)
{
	GMutex *m;

	private_is_primary_thread = g_private_new (NULL);
	g_private_set (private_is_primary_thread, GUINT_TO_POINTER (1));

	g_static_rec_mutex_init (&rb_gdk_mutex);
	gdk_threads_set_lock_functions (_threads_enter, _threads_leave);
	gdk_threads_init ();

	m = g_mutex_new ();

	g_mutex_lock (m);
	mutex_recurses = g_mutex_trylock (m);
	if (mutex_recurses)
		g_mutex_unlock (m);
	g_mutex_unlock (m);
	g_mutex_free (m);

	rb_debug ("GMutex %s recursive", mutex_recurses ? "is" : "isn't");

	/* purge useless thread-pool threads occasionally */
	g_timeout_add_seconds (30, purge_useless_threads, NULL);
}
示例#5
0
void
VMTools_ConfigLogToStdio(const gchar *domain)
{
   static LogHandler *gStdLogHandler = NULL;
   GKeyFile *cfg;

   g_return_if_fail(gStdLogHandler == NULL); /* Already called */

   ASSERT(domain != NULL);
   gLogDomain = g_strdup(domain);
   cfg = g_key_file_new();
   gStdLogHandler = VMToolsGetLogHandler(STD_HANDLER,
                                         gLogDomain,
                                         ~0,
                                         cfg);
   if (!gStdLogHandler) {
      fprintf(stderr, "Failed to create the STD log handler\n");
      goto exit;
   }

   g_log_set_handler(gLogDomain, ~0, VMToolsLog, gStdLogHandler);

   if (!gLogInitialized) {
      gLogInitialized = TRUE;
      g_static_rec_mutex_init(&gLogStateMutex);
   }

   gLogEnabled = TRUE;

exit:
   g_key_file_free(cfg);
}
示例#6
0
static void
iris_coordination_arbiter_init (IrisCoordinationArbiter *arbiter)
{
	arbiter->priv = G_TYPE_INSTANCE_GET_PRIVATE (arbiter,
	                                             IRIS_TYPE_COORDINATION_ARBITER,
	                                             IrisCoordinationArbiterPrivate);
	g_static_rec_mutex_init (&arbiter->priv->mutex);
	arbiter->priv->active = 0;
}
示例#7
0
文件: fm-job.c 项目: Gontxal0/libfm
/**
 * fm_job_init_cancellable
 * @job: the job to init
 *
 * Used by derived classes to implement #FmJobClass:run() using gio inside.
 * This API tries to initialize a #GCancellable object for use with gio and
 * should only be called once in the constructor of derived classes which
 * require the use of #GCancellable.
 *
 * This APIs is private to #FmJob and should only be used in the
 * implementation of classes derived from #FmJob.
 *
 * Since: 0.1.0
 */
void fm_job_init_cancellable(FmJob* job)
{
#if GLIB_CHECK_VERSION(2, 32, 0)
    g_rec_mutex_init(&job->stop);
#else
    g_static_rec_mutex_init(&job->stop);
#endif
    job->cancellable = g_cancellable_new();
    g_signal_connect(job->cancellable, "cancelled", G_CALLBACK(on_cancellable_cancelled), job);
}
示例#8
0
static void
gst_swfdec_init (GstSwfdec * swfdec)
{
  /* create the sink and src pads */
  swfdec->sinkpad =
      gst_pad_new_from_static_template (&sink_template_factory, "sink");
  gst_element_add_pad (GST_ELEMENT (swfdec), swfdec->sinkpad);

  gst_pad_set_chain_function (swfdec->sinkpad, gst_swfdec_chain);
  gst_pad_set_event_function (swfdec->sinkpad, gst_swfdec_sink_event);

  swfdec->videopad =
      gst_pad_new_from_static_template (&video_template_factory, "video_00");
  gst_pad_set_query_function (swfdec->videopad, gst_swfdec_src_query);
  gst_pad_set_getcaps_function (swfdec->videopad, gst_swfdec_video_getcaps);
  gst_pad_set_setcaps_function (swfdec->videopad, gst_swfdec_video_link);
  gst_pad_set_event_function (swfdec->videopad, gst_swfdec_src_event);

  gst_pad_set_query_type_function (swfdec->videopad,
      gst_swfdec_get_query_types);

  gst_element_add_pad (GST_ELEMENT (swfdec), swfdec->videopad);

  swfdec->audiopad =
      gst_pad_new_from_static_template (&audio_template_factory, "audio_00");
  gst_pad_set_query_function (swfdec->audiopad, gst_swfdec_src_query);
  gst_pad_set_event_function (swfdec->audiopad, gst_swfdec_src_event);

  gst_pad_set_query_type_function (swfdec->audiopad,
      gst_swfdec_get_query_types);

  gst_element_add_pad (GST_ELEMENT (swfdec), swfdec->audiopad);


  /* initialize the swfdec decoder state */
  swfdec->decoder = swfdec_decoder_new ();
  g_return_if_fail (swfdec->decoder != NULL);

  swfdec_decoder_set_colorspace (swfdec->decoder, SWF_COLORSPACE_RGB888);

  swfdec->frame_rate_n = 0;
  swfdec->frame_rate_d = 1;
  swfdec->x = -1;
  swfdec->y = -1;

  swfdec->skip_frames = 2;
  swfdec->skip_index = 0;

  swfdec->adapter = gst_adapter_new ();
  swfdec->task = gst_task_create ((GstTaskFunction) gst_swfdec_loop, swfdec);
  g_static_rec_mutex_init (&swfdec->mutex);
  gst_task_set_lock (swfdec->task, &swfdec->mutex);

}
示例#9
0
static void
gst_fake_sink_init (GstFakeSink * fakesink, GstFakeSinkClass * g_class)
{
  fakesink->silent = DEFAULT_SILENT;
  fakesink->dump = DEFAULT_DUMP;
  GST_BASE_SINK (fakesink)->sync = DEFAULT_SYNC;
  fakesink->last_message = g_strdup (DEFAULT_LAST_MESSAGE);
  fakesink->state_error = DEFAULT_STATE_ERROR;
  fakesink->signal_handoffs = DEFAULT_SIGNAL_HANDOFFS;
  fakesink->num_buffers = DEFAULT_NUM_BUFFERS;
  g_static_rec_mutex_init (&fakesink->notify_lock);
}
static void
fs_msn_session_init (FsMsnSession *self)
{
  /* member init */
  self->priv = FS_MSN_SESSION_GET_PRIVATE (self);
  self->priv->disposed = FALSE;
  self->priv->construction_error = NULL;

  g_static_rec_mutex_init (&self->mutex);

  self->priv->media_type = FS_MEDIA_TYPE_LAST + 1;
}
示例#11
0
GstAlsaMixer *
gst_alsa_mixer_new (const char *device, GstAlsaMixerDirection dir)
{
  GstAlsaMixer *ret = NULL;

  g_return_val_if_fail (device != NULL, NULL);

  ret = g_new0 (GstAlsaMixer, 1);

  if (pipe (ret->pfd) == -1)
    goto error;

  ret->rec_mutex = g_new (GStaticRecMutex, 1);
  g_static_rec_mutex_init (ret->rec_mutex);

  ret->task_mutex = g_new (GStaticRecMutex, 1);
  g_static_rec_mutex_init (ret->task_mutex);

  ret->task = gst_task_create (task_monitor_alsa, ret);
  gst_task_set_lock (ret->task, ret->task_mutex);

  ret->device = g_strdup (device);
  ret->dir = dir;

  if (!gst_alsa_mixer_open (ret))
    goto error;

  if (gst_task_start (ret->task) == FALSE) {
    GST_WARNING ("Could not start alsamixer task");
  }

  return ret;

  /* ERRORS */
error:
  {
    gst_alsa_mixer_free (ret);
    return NULL;
  }
}
示例#12
0
static void
gst_hls_demux_init (GstHLSDemux * demux, GstHLSDemuxClass * klass)
{
  /* sink pad */
  demux->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
  gst_pad_set_chain_function (demux->sinkpad,
      GST_DEBUG_FUNCPTR (gst_hls_demux_chain));
  gst_pad_set_event_function (demux->sinkpad,
      GST_DEBUG_FUNCPTR (gst_hls_demux_sink_event));
  gst_element_add_pad (GST_ELEMENT (demux), demux->sinkpad);

  /* demux pad */
  demux->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
  gst_pad_set_event_function (demux->srcpad,
      GST_DEBUG_FUNCPTR (gst_hls_demux_src_event));
  gst_pad_set_query_function (demux->srcpad,
      GST_DEBUG_FUNCPTR (gst_hls_demux_src_query));
  gst_pad_set_element_private (demux->srcpad, demux);
  gst_element_add_pad (GST_ELEMENT (demux), demux->srcpad);

  /* fetcher pad */
  demux->fetcherpad =
      gst_pad_new_from_static_template (&fetchertemplate, "sink");
  gst_pad_set_chain_function (demux->fetcherpad,
      GST_DEBUG_FUNCPTR (gst_hls_demux_fetcher_chain));
  gst_pad_set_event_function (demux->fetcherpad,
      GST_DEBUG_FUNCPTR (gst_hls_demux_fetcher_sink_event));
  gst_pad_set_element_private (demux->fetcherpad, demux);
  gst_pad_activate_push (demux->fetcherpad, TRUE);

  /* Properties */
  demux->fragments_cache = DEFAULT_FRAGMENTS_CACHE;
  demux->bitrate_switch_tol = DEFAULT_BITRATE_SWITCH_TOLERANCE;

  demux->download = gst_adapter_new ();
  demux->fetcher_bus = gst_bus_new ();
  gst_bus_set_sync_handler (demux->fetcher_bus,
      gst_hls_demux_fetcher_bus_handler, demux);
  demux->thread_cond = g_cond_new ();
  demux->thread_lock = g_mutex_new ();
  demux->fetcher_cond = g_cond_new ();
  demux->fetcher_lock = g_mutex_new ();
  demux->queue = g_queue_new ();
  g_static_rec_mutex_init (&demux->task_lock);
  demux->task = gst_task_create ((GstTaskFunction) gst_hls_demux_loop, demux);
  gst_task_set_lock (demux->task, &demux->task_lock);
}
示例#13
0
static void
gst_sdp_demux_init (GstSDPDemux * demux, GstSDPDemuxClass * g_class)
{
  demux->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
  gst_pad_set_event_function (demux->sinkpad,
      GST_DEBUG_FUNCPTR (gst_sdp_demux_sink_event));
  gst_pad_set_chain_function (demux->sinkpad,
      GST_DEBUG_FUNCPTR (gst_sdp_demux_sink_chain));
  gst_element_add_pad (GST_ELEMENT (demux), demux->sinkpad);

  /* protects the streaming thread in interleaved mode or the polling
   * thread in UDP mode. */
  demux->stream_rec_lock = g_new (GStaticRecMutex, 1);
  g_static_rec_mutex_init (demux->stream_rec_lock);

  demux->adapter = gst_adapter_new ();
}
示例#14
0
Images::Images()
:
    external_decoder( 0 ),
    cache( 0 )
{
    g_static_rec_mutex_init( & mutex );

    Decoder * png  = ImageDecoders::make_png_decoder();
    Decoder * jpeg = ImageDecoders::make_jpeg_decoder();
    Decoder * tiff = ImageDecoders::make_tiff_decoder();
    Decoder * gif  = ImageDecoders::make_gif_decoder();

    // This is the default order of decoders. The most common
    // type should go first. This order may be affected
    // dynamically by "hints" - see below.

    decoders.push_back( png );
    decoders.push_back( jpeg );
    decoders.push_back( gif );
    decoders.push_back( tiff );

    // This maps the last 4 characters of a file name or mime type
    // to specific decoders. It lets us rearrange the decoders so
    // that we may hit the correct one sooner.

    hints[ ".tif" ] = tiff;
    hints[ ".TIF" ] = tiff;
    hints[ "tiff" ] = tiff;
    hints[ "TIFF" ] = tiff;

    hints[ ".png" ] = png;
    hints[ ".PNG" ] = png;
    hints[ "/png" ] = png;
    hints[ "/PNG" ] = png;

    hints[ ".jpg" ] = jpeg;
    hints[ ".JPG" ] = jpeg;
    hints[ "jpeg" ] = jpeg;
    hints[ "JPEG" ] = jpeg;

    hints[ ".gif" ] = gif;
    hints[ ".GIF" ] = gif;
    hints[ "/gif" ] = gif;
    hints[ "/GIF" ] = gif;
}
示例#15
0
static void
gst_identity_init (GstIdentity * identity, GstIdentityClass * g_class)
{
  identity->sleep_time = DEFAULT_SLEEP_TIME;
  identity->error_after = DEFAULT_ERROR_AFTER;
  identity->drop_probability = DEFAULT_DROP_PROBABILITY;
  identity->datarate = DEFAULT_DATARATE;
  identity->silent = DEFAULT_SILENT;
  identity->single_segment = DEFAULT_SINGLE_SEGMENT;
  identity->sync = DEFAULT_SYNC;
  identity->check_perfect = DEFAULT_CHECK_PERFECT;
  identity->check_imperfect_timestamp = DEFAULT_CHECK_IMPERFECT_TIMESTAMP;
  identity->check_imperfect_offset = DEFAULT_CHECK_IMPERFECT_OFFSET;
  identity->dump = DEFAULT_DUMP;
  identity->last_message = NULL;
  identity->signal_handoffs = DEFAULT_SIGNAL_HANDOFFS;
  g_static_rec_mutex_init (&identity->notify_lock);
}
示例#16
0
static GstStateChangeReturn
gst_qt_moov_recover_change_state (GstElement * element,
    GstStateChange transition)
{
  GstStateChangeReturn ret;
  GstQTMoovRecover *qtmr = GST_QT_MOOV_RECOVER_CAST (element);

  switch (transition) {
    case GST_STATE_CHANGE_NULL_TO_READY:
      qtmr->task = gst_task_create (gst_qt_moov_recover_run, qtmr);
      qtmr->task_mutex = g_new (GStaticRecMutex, 1);
      g_static_rec_mutex_init (qtmr->task_mutex);
      gst_task_set_lock (qtmr->task, qtmr->task_mutex);
      break;
    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
      gst_task_start (qtmr->task);
      break;
    default:
      break;
  }

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);

  switch (transition) {
    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
      gst_task_stop (qtmr->task);
      gst_task_join (qtmr->task);
      break;
    case GST_STATE_CHANGE_READY_TO_NULL:
      g_assert (gst_task_get_state (qtmr->task) == GST_TASK_STOPPED);
      gst_object_unref (qtmr->task);
      qtmr->task = NULL;
      g_static_rec_mutex_free (qtmr->task_mutex);
      break;
    default:
      break;
  }
  return ret;
}
static void
gst_identity_init (GstIdentity * identity, GstIdentityClass * g_class)
{
  identity->sleep_time = DEFAULT_SLEEP_TIME;
  identity->error_after = DEFAULT_ERROR_AFTER;
  identity->drop_probability = DEFAULT_DROP_PROBABILITY;
  identity->datarate = DEFAULT_DATARATE;
  identity->silent = DEFAULT_SILENT;
  identity->single_segment = DEFAULT_SINGLE_SEGMENT;
  identity->sync = DEFAULT_SYNC;
  identity->check_perfect = DEFAULT_CHECK_PERFECT;
  identity->check_imperfect_timestamp = DEFAULT_CHECK_IMPERFECT_TIMESTAMP;
  identity->check_imperfect_offset = DEFAULT_CHECK_IMPERFECT_OFFSET;
  identity->dump = DEFAULT_DUMP;
  identity->last_message = NULL;
  identity->signal_handoffs = DEFAULT_SIGNAL_HANDOFFS;

#if !GLIB_CHECK_VERSION(2,26,0)
  g_static_rec_mutex_init (&identity->notify_lock);
#endif

  gst_base_transform_set_gap_aware (GST_BASE_TRANSFORM_CAST (identity), TRUE);
}
示例#18
0
static void
gst_vader_init(GstVader * filter, GstVaderClass * g_class)
{
    filter->sinkpad =
        gst_pad_new_from_static_template(&vader_sink_factory, "sink");
    filter->srcpad =
        gst_pad_new_from_static_template(&vader_src_factory, "src");

    g_static_rec_mutex_init(&filter->mtx);

    filter->threshold_level = 256;
    filter->threshold_length = (guint64)(0.5 * GST_SECOND);
    filter->prior_sample = 0;
    filter->auto_threshold = FALSE;
    filter->silence_mean = 0;
    filter->silence_stddev = 0;
    filter->silence_frames = 0;
    filter->dumpdir = NULL;
    filter->dumpfile = NULL;
    filter->dumpidx = 0;

    memset(filter->window, 0, VADER_WINDOW * sizeof(*filter->window));
    filter->silent = TRUE;
    filter->silent_prev = TRUE;
    filter->silent_run_length = 0;

    filter->pre_buffer = NULL;
    filter->pre_length = (guint64)(0.5 * GST_SECOND);
    filter->pre_run_length = 0;

    gst_element_add_pad(GST_ELEMENT(filter), filter->sinkpad);
    gst_pad_set_chain_function(filter->sinkpad, gst_vader_chain);
    gst_pad_use_fixed_caps(filter->sinkpad);

    gst_element_add_pad(GST_ELEMENT(filter), filter->srcpad);
    gst_pad_use_fixed_caps(filter->srcpad);
}
示例#19
0
文件: core.c 项目: TDKPS/lgi
int
luaopen_lgi_corelgilua51 (lua_State* L)
{
  LgiStateMutex *mutex;

  /* Try to make itself resident.  This is needed because this dynamic
     module is 'statically' linked with glib/gobject, and these
     libraries are not designed to be unloaded.  Once they are
     unloaded, they cannot be safely loaded again into the same
     process.  To avoid problems when repeately opening and closing
     lua_States and loading lgi into them, we try to make the whole
     'core' module resident. */
  set_resident (L);

  /* Early GLib initializations. Make sure that following fundamental
     G_TYPEs are already initialized. */
  g_type_init ();
  volatile GType unused;
  unused = G_TYPE_DATE;
  unused = G_TYPE_REGEX;
  unused = G_TYPE_DATE_TIME;
  unused = G_TYPE_VARIANT_TYPE;
  unused = G_TYPE_STRV;
  unused = unused;

  /* Register 'guard' metatable. */
  luaL_newmetatable (L, UD_GUARD);
  lua_pushcfunction (L, guard_gc);
  lua_setfield (L, -2, "__gc");
  lua_pop (L, 1);

  /* Register 'module' metatable. */
  luaL_newmetatable (L, UD_MODULE);
  luaL_register (L, NULL, module_reg);
  lua_pop (L, 1);

  /* Register 'call-mutex' metatable. */
  lua_pushlightuserdata (L, &call_mutex_mt);
  lua_newtable (L);
  lua_pushcfunction (L, call_mutex_gc);
  lua_setfield (L, -2, "__gc");
  lua_rawset (L, LUA_REGISTRYINDEX);

  /* Create call mutex guard, keep it locked initially (it is unlocked
     only when we are calling out to GObject-C code) and store it into
     the registry. */
  lua_pushlightuserdata (L, &call_mutex);
  mutex = lua_newuserdata (L, sizeof (*mutex));
  mutex->mutex = &mutex->state_mutex;
  g_static_rec_mutex_init (&mutex->state_mutex);
  g_static_rec_mutex_lock (&mutex->state_mutex);
  lua_pushlightuserdata (L, &call_mutex_mt);
  lua_rawget (L, LUA_REGISTRYINDEX);
  lua_setmetatable (L, -2);
  lua_rawset (L, LUA_REGISTRYINDEX);

  /* Register 'lgi.core' interface. */
  lua_newtable (L);
  luaL_register (L, NULL, lgi_reg);

  /* Create repo and index table. */
  create_repo_table (L, "index", &repo_index);
  create_repo_table (L, "repo", &repo);

  /* Initialize modules. */
  lgi_buffer_init (L);
  lgi_gi_init (L);
  lgi_marshal_init (L);
  lgi_record_init (L);
  lgi_object_init (L);
  lgi_callable_init (L);

  /* Return registration table. */
  return 1;
}
示例#20
0
/**
 * oh_create_domain
 * @id: Required. 0 or SAHPI_UNSPECIFIED_DOMAIN_ID means default.
 * @entity_pattern: Required.
 * @nametag: Optional.
 * @tier_of: Optional. SAHPI_UNSPECIFIED_DOMAIN_ID means none.
 * @peer_of: Optional. SAHPI_UNSPECIFIED_DOMAIN_ID means none.
 * @capabilities:
 * @ai_timeout:
 *
 * 
 *
 * Returns: SA_OK if domain was created successfully.
 **/
SaErrorT oh_create_domain(SaHpiDomainIdT id,
                          oh_entitypath_pattern *entity_pattern,
                          char *tag,
                          SaHpiDomainIdT child_of,
                          SaHpiDomainIdT peer_of,
                          SaHpiDomainCapabilitiesT capabilities,
                          SaHpiTimeoutT ai_timeout)
{
        struct oh_domain *domain = g_new0(struct oh_domain,1);
        struct oh_global_param param = { .type = OPENHPI_DEL_SIZE_LIMIT };
        char filepath[SAHPI_MAX_TEXT_BUFFER_LENGTH*2];

        /* Fix id to int capable value */
        if (id == SAHPI_UNSPECIFIED_DOMAIN_ID)
                id = OH_DEFAULT_DOMAIN_ID;

        /* Input validation */
        if (!entity_pattern && peer_of == SAHPI_UNSPECIFIED_DOMAIN_ID)
                return SA_ERR_HPI_INVALID_PARAMS;
        else if (peer_of == id || child_of == id ||
                 (child_of == peer_of && child_of != SAHPI_UNSPECIFIED_DOMAIN_ID))
                return SA_ERR_HPI_INVALID_PARAMS;
        
        /* Check to see if domain id is already taken */
        domains_lock();
        if (g_hash_table_lookup(oh_domains.table, &id)) {
                domains_unlock();
                g_free(domain);
                dbg("Domain %u already exists; not creating twice.", id);
                return SA_ERR_HPI_INVALID_DOMAIN;
        }

        domain->id = id; /* Set domain id */
        if (entity_pattern) { /* Set entity pattern */
                memcpy(&domain->entity_pattern,
                       entity_pattern,
                       sizeof(oh_entitypath_pattern));
        }
        
        if (tag) { /* Set domain tag */
                oh_init_textbuffer(&domain->tag);
                oh_append_textbuffer(&domain->tag, tag);
        }
        domain->capabilities = capabilities;
        domain->ai_timeout = ai_timeout;

        /* Initialize Resource Precense Table */
        oh_init_rpt(&(domain->rpt));

        /* Initialize domain reference table timestamp to a valid value */
        domain->drt.update_timestamp = SAHPI_TIME_UNSPECIFIED;

        oh_get_global_param(&param); /* Get domain event log size limit */
        /* Initialize domain event log */
        domain->del = oh_el_create(param.u.del_size_limit);

        if (!domain->del) {
                domains_unlock();
                g_free(domain->del);
                g_free(domain);
                return SA_ERR_HPI_ERROR;
        }

        g_static_rec_mutex_init(&domain->lock);
        g_static_rec_mutex_init(&domain->refcount_lock);

        /* Get option for saving domain event log or not */
        param.type = OPENHPI_DEL_SAVE;
        oh_get_global_param(&param);

        if (param.u.del_save) {
                param.type = OPENHPI_VARPATH;
                oh_get_global_param(&param);
                snprintf(filepath,
                         SAHPI_MAX_TEXT_BUFFER_LENGTH*2,
                         "%s/del.%u", param.u.varpath, domain->id);
                oh_el_map_from_file(domain->del, filepath);
        }
	param.type = OPENHPI_DAT_SAVE;
	oh_get_global_param(&param);
	if (param.u.dat_save) {
		param.type = OPENHPI_VARPATH;
		oh_get_global_param(&param);
		memset(filepath, 0, SAHPI_MAX_TEXT_BUFFER_LENGTH*2);
		snprintf(filepath,
			 SAHPI_MAX_TEXT_BUFFER_LENGTH*2,
			 "%s/dat.%u", param.u.varpath, domain->id);
		oh_alarms_from_file(domain, filepath);
	}

        /* Need to put new domain in table before relating to other domains. */
        oh_domains.list = g_list_append(oh_domains.list, domain);
        g_hash_table_insert(oh_domains.table,
                            &domain->id,
                            g_list_last(oh_domains.list));

        /* Establish child-parent relationship */
        if (child_of != SAHPI_UNSPECIFIED_DOMAIN_ID &&
            connect2parent(domain, child_of)) {
                dbg("Error connecting domain %u to parent %u",
                    domain->id, child_of);
        }

        /* Establish peer relationships */
        if (peer_of != SAHPI_UNSPECIFIED_DOMAIN_ID &&
            connect2peer(domain, peer_of)) {
                dbg("Error connection domain %u to peer %u",
                    domain->id, peer_of);
        }
        
        domains_unlock();

        trace("Domain %u has been created.", id);

        return SA_OK;
}
示例#21
0
static struct oh_handler *new_handler(GHashTable *handler_config)
{       /* Return a new oh_handler instance */
        struct oh_plugin *plugin = NULL;
        struct oh_handler *handler = NULL;
        static unsigned int handler_id = 1;
        unsigned int *hidp;
        char *hid_strp;

        if (!handler_config) {
                dbg("ERROR creating new handler. Invalid parameter.");
                return NULL;
        }

        handler = (struct oh_handler *)g_malloc0(sizeof(struct oh_handler));
        if (!handler) {
                dbg("Out of Memory!");
                return NULL;
        }

        hidp = (unsigned int *)g_malloc(sizeof(unsigned int));
        if (!hidp) {
                dbg("Out of Memory!");
                g_free(handler);
                return NULL;
        }
        hid_strp = strdup("handler-id");
        if (!hid_strp) {
                dbg("Out of Memory!");
                g_free(handler);
                g_free(hidp);
                return NULL;
        }

        plugin = oh_get_plugin((char *)g_hash_table_lookup(handler_config, "plugin"));
        if(!plugin) {
                dbg("Attempt to create handler for unknown plugin %s",
                    (char *)g_hash_table_lookup(handler_config, "plugin"));
                goto cleanexit;
        }
        /* Initialize handler */
        handler->abi = plugin->abi;
        plugin->handler_count++; /* Increment # of handlers using the plugin */
        oh_release_plugin(plugin);
        g_static_rec_mutex_lock(&oh_handlers.lock);
        handler->id = handler_id++;
        g_static_rec_mutex_unlock(&oh_handlers.lock);
        *hidp = handler->id;
        g_hash_table_insert(handler_config, (gpointer)hid_strp,(gpointer)hidp);
        handler->plugin_name = (char *)g_hash_table_lookup(handler_config, "plugin");
        handler->config = handler_config;
        handler->dids = NULL;
        handler->refcount = 0;
        g_static_rec_mutex_init(&handler->lock);
        g_static_rec_mutex_init(&handler->refcount_lock);

        return handler;
cleanexit:
        g_free(hidp);
        g_free(hid_strp);
        g_free(handler);
        return NULL;
}
示例#22
0
/**
 * snmp_bc_open:
 * @handler_config: Pointer to hash table (passed by infrastructure)
 *
 * Open an SNMP BladeCenter/RSA plugin handler instance.
 *
 * Returns:
 * Plugin handle - normal operation.
 * NULL - on error.
 **/
void *snmp_bc_open(GHashTable *handler_config)
{
        struct oh_handler_state *handle;
        struct snmp_bc_hnd *custom_handle;
        char *hostname, *version, *sec_level, *authtype, *user, *pass, *community;
        char *root_tuple;

        root_tuple = (char *)g_hash_table_lookup(handler_config, "entity_root");
        if (!root_tuple) {
                dbg("Cannot find \"entity_root\" configuration parameter.");
                return NULL;
        }

        hostname = (char *)g_hash_table_lookup(handler_config, "host");
        if (!hostname) {
                dbg("Cannot find \"host\" configuration parameter.");
                return NULL;
        }

        handle = (struct oh_handler_state *)g_malloc0(sizeof(struct oh_handler_state));
        custom_handle = (struct snmp_bc_hnd *)g_malloc0(sizeof(struct snmp_bc_hnd));
        if (!handle || !custom_handle) {
                dbg("Out of memory.");
                return NULL;
        }

        handle->data = custom_handle;
        handle->config = handler_config;

        /* Initialize the lock */
        /* g_static_rec_mutex_init(&handle->handler_lock); */
	g_static_rec_mutex_init(&custom_handle->snmp_bc_hlock.lock);
	custom_handle->snmp_bc_hlock.count = 0;
	
        /* Initialize RPT cache */
        handle->rptcache = (RPTable *)g_malloc0(sizeof(RPTable));
        oh_init_rpt(handle->rptcache);
	 
        /* Initialize event log cache */
        handle->elcache = oh_el_create(BC_EL_MAX_SIZE);
	handle->elcache->gentimestamp = FALSE;

	/* Initialize simulator tables */
	if (is_simulator()) {
		custom_handle->ss = NULL;
		sim_init();
	}
	else {
		/* Initialize SNMP library */
		init_snmp("oh_snmp_bc");
		snmp_sess_init(&(custom_handle->session));
		custom_handle->session.peername = hostname;
		/* Set retries/timeouts - based on testing with BC/BCT MM SNMP V3 agent */
		custom_handle->session.retries = 3;
		custom_handle->session.timeout = 5000000; /* in microseconds */  
		version = (char *)g_hash_table_lookup(handle->config, "version");
		if (!version) {
			dbg("Cannot find \"version\" configuration parameter.");
			return NULL;
		}
		sec_level = (char *)g_hash_table_lookup(handle->config, "security_level");
		authtype = (char *)g_hash_table_lookup(handle->config, "auth_type");
		user = (char *)g_hash_table_lookup(handle->config, "security_name");
		pass = (char *)g_hash_table_lookup(handle->config, "passphrase");
		community = (char *)g_hash_table_lookup(handle->config, "community");
		
		/* Configure SNMP V3 session */
		if (!strcmp(version, "3")) {
			if (!user) {
				dbg("Cannot find \"security_name\" configuration parameter.");
				return NULL;
			}
			custom_handle->session.version = SNMP_VERSION_3;
			custom_handle->session.securityName = user;
			custom_handle->session.securityNameLen = strlen(user);
			custom_handle->session.securityLevel = SNMP_SEC_LEVEL_NOAUTH;
			
			if (!strncmp(sec_level, "auth", 4)) { /* If using password */
				if (!pass) {
					dbg("Cannot find \"passphrase\" configuration parameter.");
					return NULL;
				}
				
				custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
				if (!authtype || !strcmp(authtype,"MD5")) {
					custom_handle->session.securityAuthProto = usmHMACMD5AuthProtocol;
					custom_handle->session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
				} else if (!strcmp(authtype,"SHA")) {
					custom_handle->session.securityAuthProto = usmHMACSHA1AuthProtocol;
					custom_handle->session.securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
				} else {
					dbg("Unrecognized authenication type=%s.", authtype); 
					return NULL;
				}
				
				custom_handle->session.securityAuthKeyLen = USM_AUTH_KU_LEN;
				if (generate_Ku(custom_handle->session.securityAuthProto,
						custom_handle->session.securityAuthProtoLen,
						(u_char *) pass, strlen(pass),
						custom_handle->session.securityAuthKey,
						&(custom_handle->session.securityAuthKeyLen)) != SNMPERR_SUCCESS) {
					snmp_perror("snmp_bc");
					snmp_log(LOG_ERR,
						 "Error generating Ku from authentication passphrase.\n");
					dbg("Unable to establish SNMP authnopriv session.");
					return NULL;
				}
				
				if (!strcmp(sec_level, "authPriv")) { /* if using encryption */
					custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
					custom_handle->session.securityPrivProto = usmDESPrivProtocol;
					custom_handle->session.securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
					custom_handle->session.securityPrivKeyLen = USM_PRIV_KU_LEN;
					if (generate_Ku(custom_handle->session.securityAuthProto,
							custom_handle->session.securityAuthProtoLen,
							(u_char *) pass, strlen(pass),
							custom_handle->session.securityPrivKey,
							&(custom_handle->session.securityPrivKeyLen)) != SNMPERR_SUCCESS) {
						snmp_perror("snmp_bc");
						snmp_log(LOG_ERR,
							 "Error generating Ku from private passphrase.\n");
						dbg("Unable to establish SNMP authpriv session.");
						return NULL;
					}
					
				}
			}                                
                /* Configure SNMP V1 session */
		} else if (!strcmp(version, "1")) { 
			if (!community) {
				dbg("Cannot find \"community\" configuration parameter.");
				return NULL;
			}
			custom_handle->session.version = SNMP_VERSION_1;
			custom_handle->session.community = (u_char *)community;
			custom_handle->session.community_len = strlen(community);
		} else {
			dbg("Unrecognized SNMP version=%s.", version);
			return NULL;
		}
                
		/* Windows32 specific net-snmp initialization (noop on unix) */
		SOCK_STARTUP;

		custom_handle->sessp = snmp_sess_open(&(custom_handle->session));
		
		if (!custom_handle->sessp) {
			snmp_perror("ack");
			snmp_log(LOG_ERR, "Something horrible happened!!!\n");
		 	dbg("Unable to open SNMP session.");
			return NULL;
		}
		
		custom_handle->ss    = snmp_sess_session(custom_handle->sessp);

	}

	/* Determine platform type and daylight savings time */
	{
		const char *oid;
		struct snmp_value get_value;
		SaErrorT err;

		err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_RSA, &get_value, SAHPI_FALSE);
		if (err == SA_OK) {
			trace("Found RSA");
			custom_handle->platform = SNMP_BC_PLATFORM_RSA;
		}
		else {
			err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_BCT, &get_value, SAHPI_FALSE);
			if (err == SA_OK) {
				trace("Found BCT");
				custom_handle->platform = SNMP_BC_PLATFORM_BCT;
			}
			else {
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_BC, &get_value, SAHPI_FALSE);
				if (err == SA_OK) {
					trace("Found BC");
					custom_handle->platform = SNMP_BC_PLATFORM_BC;
				}
				else {
					dbg("Cannot read model type=%s; Error=%d.",
					      SNMP_BC_PLATFORM_OID_BCT, err);
					return NULL;
				}
			}
		}

		/* DST */
		if (custom_handle->platform == SNMP_BC_PLATFORM_RSA) { oid = SNMP_BC_DST_RSA; }
		else { oid = SNMP_BC_DST; }

		err = snmp_bc_snmp_get(custom_handle, oid, &get_value, SAHPI_TRUE);
		if (err == SA_OK) {
			strcpy(custom_handle->handler_timezone, get_value.string);
		}
		else {
			dbg("Cannot read DST=%s; Error=%d.", oid, get_value.type);
			return NULL;
		}
	}

	/* Initialize "String to Event" mapping hash table */
	if (errlog2event_hash_use_count == 0) {
		if (errlog2event_hash_init(custom_handle)) {
			dbg("Out of memory.");
			return NULL;
		}
	}
	errlog2event_hash_use_count++;
	
	/* Initialize "Event Number to HPI Event" mapping hash table */
	if (event2hpi_hash_init(handle)) {
		dbg("Out of memory.");
		return NULL;
	}
  
	if (is_simulator()) {
		sim_banner(custom_handle);
	}
	
        return handle;
}
示例#23
0
/**
 * snmp_bc_open:
 * @handler_config: Pointer to hash table (passed by infrastructure)
 *
 * Open an SNMP BladeCenter/RSA plugin handler instance.
 *
 * Returns:
 * Plugin handle - normal operation.
 * NULL - on error.
 **/
void *snmp_bc_open(GHashTable *handler_config)
{
        struct oh_handler_state *handle;
        struct snmp_bc_hnd *custom_handle;
        char *hostname, *version, *sec_level, 
		*authtype, *user, *pass, *community, 
		*context_name, *count_per_getbulk, 
		*privacy_passwd, *privacy_protocol;
        char *root_tuple;

	if (!handler_config) {
                dbg("INVALID PARM - NULL handler_config pointer.");
                return NULL;	
	}

        root_tuple = (char *)g_hash_table_lookup(handler_config, "entity_root");
        if (!root_tuple) {
                dbg("Cannot find \"entity_root\" configuration parameter.");
                return NULL;
        }

        hostname = (char *)g_hash_table_lookup(handler_config, "host");
        if (!hostname) {
                dbg("Cannot find \"host\" configuration parameter.");
                return NULL;
        }

        handle = (struct oh_handler_state *)g_malloc0(sizeof(struct oh_handler_state));
        custom_handle = (struct snmp_bc_hnd *)g_malloc0(sizeof(struct snmp_bc_hnd));
        if (!handle || !custom_handle) {
                dbg("Out of memory.");
                return NULL;
        }

        handle->data = custom_handle;
        handle->config = handler_config;

        /* Initialize the lock */
        /* g_static_rec_mutex_init(&handle->handler_lock); */
	g_static_rec_mutex_init(&custom_handle->snmp_bc_hlock.lock);
	custom_handle->snmp_bc_hlock.count = 0;
	
        /* Initialize resource masks */
	/* Set all masks and counts to zero's    */
	custom_handle->max_pb_supported = 0;		/* pb - processor blade */
	custom_handle->max_blower_supported = 0;	/* blower - fan/blower  */
	custom_handle->max_pm_supported = 0;		/* pm - power module    */
	custom_handle->max_sm_supported = 0;		/* sm - switch module   */
	custom_handle->max_mm_supported = 0;		/* mm - management module */
	custom_handle->max_mt_supported = 0;		/* mt - media tray        */
	
	memset(&custom_handle->installed_pb_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	memset(&custom_handle->installed_blower_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	memset(&custom_handle->installed_pm_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	memset(&custom_handle->installed_sm_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	memset(&custom_handle->installed_mm_mask, '\0', SNMP_BC_MAX_RESOURCES_MASK);
	custom_handle->installed_mt_mask = 0;

        /* Indicate this is the 1st discovery (T0 discovery) */
        /* Use to see if we need to create events for log entries.  */
	/* Do not report any event from event log entries, for      */
	/* entries that are created before this instance of OpenHPI */	
	custom_handle->isFirstDiscovery = SAHPI_TRUE;
	
        /* Initialize RPT cache */
        handle->rptcache = (RPTable *)g_malloc0(sizeof(RPTable));
        oh_init_rpt(handle->rptcache);
	 
        /* Initialize event log cache */
        handle->elcache = oh_el_create(BC_EL_MAX_SIZE);
	handle->elcache->gentimestamp = FALSE;

	/* Initialize simulator tables */
	if (is_simulator()) {
		custom_handle->ss = NULL;
		sim_init();
	}
	else {
		/* Initialize SNMP library */
		init_snmp("oh_snmp_bc");
		snmp_sess_init(&(custom_handle->session));
		custom_handle->session.peername = hostname;
		/* Set retries/timeouts - based on testing with BC/BCT MM SNMP V3 agent */
		custom_handle->session.retries = 3;
		custom_handle->session.timeout = 5000000; /* in microseconds */  
		version = (char *)g_hash_table_lookup(handle->config, "version");
		if (!version) {
			dbg("Cannot find \"version\" configuration parameter.");
			return NULL;
		}
		sec_level = (char *)g_hash_table_lookup(handle->config, "security_level");
		authtype = (char *)g_hash_table_lookup(handle->config, "auth_type");
		user = (char *)g_hash_table_lookup(handle->config, "security_name");
		pass = (char *)g_hash_table_lookup(handle->config, "passphrase");
		community = (char *)g_hash_table_lookup(handle->config, "community");
		context_name = (char *)g_hash_table_lookup(handle->config, "context_name");
		count_per_getbulk = (char *)g_hash_table_lookup(handle->config, "count_per_getbulk");
		privacy_passwd = (char *)g_hash_table_lookup(handle->config, "privacy_passwd");
		privacy_protocol = (char *)g_hash_table_lookup(handle->config, "privacy_protocol");
		
		
		/* Configure SNMP V3 session */
		if (!strcmp(version, "3")) {
			if (!user) {
				dbg("Cannot find \"security_name\" configuration parameter.");
				return NULL;
			}
			custom_handle->session.version = SNMP_VERSION_3;
			custom_handle->session.securityName = user;
			custom_handle->session.securityNameLen = strlen(user);
			custom_handle->session.securityLevel = SNMP_SEC_LEVEL_NOAUTH;
			
			if (!strncmp(sec_level, "auth", 4)) { /* If using password */
				if (!pass) {
					dbg("Cannot find \"passphrase\" configuration parameter.");
					return NULL;
				}
				
				custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;
				if (!authtype || !strcmp(authtype,"MD5")) {
					custom_handle->session.securityAuthProto = usmHMACMD5AuthProtocol;
					custom_handle->session.securityAuthProtoLen = USM_AUTH_PROTO_MD5_LEN;
				} else if (!strcmp(authtype,"SHA")) {
					custom_handle->session.securityAuthProto = usmHMACSHA1AuthProtocol;
					custom_handle->session.securityAuthProtoLen = USM_AUTH_PROTO_SHA_LEN;
				} else {
					dbg("Unrecognized authenication type=%s.", authtype); 
					return NULL;
				}
				
				custom_handle->session.securityAuthKeyLen = USM_AUTH_KU_LEN;
				if (generate_Ku(custom_handle->session.securityAuthProto,
						custom_handle->session.securityAuthProtoLen,
						(u_char *) pass, strlen(pass),
						custom_handle->session.securityAuthKey,
						&(custom_handle->session.securityAuthKeyLen)) != SNMPERR_SUCCESS) {
					snmp_perror("snmp_bc");
					snmp_log(LOG_ERR,
						 "Error generating Ku from authentication passphrase.\n");
					dbg("Unable to establish SNMP authnopriv session.");
					return NULL;
				}
				
				if (!strcmp(sec_level, "authPriv")) { /* if using encryption */
				
					if (!privacy_passwd) {
						dbg("Cannot find \"privacy_passwd\" configuration parameter.");
						return NULL;
					}
				
					custom_handle->session.securityLevel = SNMP_SEC_LEVEL_AUTHPRIV;
					custom_handle->session.securityPrivProto = usmDESPrivProtocol;
					custom_handle->session.securityPrivProtoLen = USM_PRIV_PROTO_DES_LEN;
					custom_handle->session.securityPrivKeyLen = USM_PRIV_KU_LEN;
					if (generate_Ku(custom_handle->session.securityAuthProto,
							custom_handle->session.securityAuthProtoLen,
							(u_char *) privacy_passwd, strlen(privacy_passwd),
							custom_handle->session.securityPrivKey,
							&(custom_handle->session.securityPrivKeyLen)) != SNMPERR_SUCCESS) {
						snmp_perror("snmp_bc");
						snmp_log(LOG_ERR,
							 "Error generating Ku from private passphrase.\n");
						dbg("Unable to establish SNMP authpriv session.");
						return NULL;
					}
					
				}
				
				if (count_per_getbulk != NULL) 
				{
					custom_handle->count_per_getbulk = atoi((char *)count_per_getbulk);
					if (custom_handle->count_per_getbulk <= 10) {
					 	custom_handle->count_per_getbulk = 10;
					}
							
				} else { 
					custom_handle->count_per_getbulk = SNMP_BC_BULK_DEFAULT;
				}

				if (context_name != NULL) 
				{
					custom_handle->session.contextName = (char *)context_name;
					custom_handle->session.contextNameLen = strlen(context_name);
				}
			}                                
                /* Configure SNMP V1 session */
		} else if (!strcmp(version, "1")) { 
			if (!community) {
				dbg("Cannot find \"community\" configuration parameter.");
				return NULL;
			}
			custom_handle->session.version = SNMP_VERSION_1;
			custom_handle->session.community = (u_char *)community;
			custom_handle->session.community_len = strlen(community);
		} else {
			dbg("Unrecognized SNMP version=%s.", version);
			return NULL;
		}
                
		/* Windows32 specific net-snmp initialization (noop on unix) */
		SOCK_STARTUP;

		custom_handle->sessp = snmp_sess_open(&(custom_handle->session));
		
		if (!custom_handle->sessp) {
			snmp_perror("ack");
			snmp_log(LOG_ERR, "Something horrible happened!!!\n");
		 	dbg("Unable to open SNMP session.");
			return NULL;
		}
		
		custom_handle->ss    = snmp_sess_session(custom_handle->sessp);

	}

	/* Determine BladeCenter chassis type */
	{
		const char *oid;
		struct snmp_value get_value;
		SaErrorT err;
		do {
			err = snmp_bc_snmp_get(custom_handle, SNMP_BC_CHASSIS_TYPE_OID, &get_value, SAHPI_FALSE);
			if (err == SA_OK) {
			        int chassis_type, chassis_subtype;
				
				chassis_type = get_value.integer;
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_CHASSIS_SUBTYPE_OID, &get_value, SAHPI_FALSE);
				if (err) {
					dbg("Cannot read model subtype");
					return NULL;
				}
				chassis_subtype = get_value.integer;

				if (chassis_type == SNMP_BC_CHASSIS_TYPE_BC &&
				    chassis_subtype == SNMP_BC_CHASSIS_SUBTYPE_ORIG) {
					trace("Found BC");
					custom_handle->platform = SNMP_BC_PLATFORM_BC;
					break;
				}

				if (chassis_type == SNMP_BC_CHASSIS_TYPE_BC &&
				    chassis_subtype == SNMP_BC_CHASSIS_SUBTYPE_H) {
					trace("Found BCH");
					custom_handle->platform = SNMP_BC_PLATFORM_BCH;
					break;
				}
				
				if (chassis_type == SNMP_BC_CHASSIS_TYPE_BCT &&
				    chassis_subtype == SNMP_BC_CHASSIS_SUBTYPE_ORIG) {
					trace("Found BCT");
					custom_handle->platform = SNMP_BC_PLATFORM_BCT;
					break;
				}

				dbg("Unknown BladeCenter model");
				return NULL;
			}
			else {  /* Older MM software doesn't support chassis type and subtype OIDs */
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_BCT, &get_value, SAHPI_FALSE);
				if (err == SA_OK) {
					trace("Found BCT");
					custom_handle->platform = SNMP_BC_PLATFORM_BCT;
					break;
				} 
				
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_BC, &get_value, SAHPI_FALSE);
				if (err == SA_OK) {
					trace("Found BC");
					custom_handle->platform = SNMP_BC_PLATFORM_BC;
					break;
				}
				
				err = snmp_bc_snmp_get(custom_handle, SNMP_BC_PLATFORM_OID_RSA, &get_value, SAHPI_FALSE);
				if (err == SA_OK) {
					trace("Found RSA");
					custom_handle->platform = SNMP_BC_PLATFORM_RSA;
					break;
				} 
				
				dbg("Unknown BladeCenter model");
				return NULL;
			}
		} while(0);
		
		/* Determine if daylight savings time (DST) is enabled */
		if (custom_handle->platform == SNMP_BC_PLATFORM_RSA) { oid = SNMP_BC_DST_RSA; }
		else { oid = SNMP_BC_DST; }

		err = snmp_bc_snmp_get(custom_handle, oid, &get_value, SAHPI_TRUE);
		if (err == SA_OK) {
			strcpy(custom_handle->handler_timezone, get_value.string);
		}
		else {
			dbg("Cannot read DST=%s; Error=%d.", oid, get_value.type);
			return NULL;
		}
	}

	/* Initialize "String to Event" mapping hash table */
	if (errlog2event_hash_use_count == 0) {
		if (errlog2event_hash_init(custom_handle)) {
			dbg("Out of memory.");
			return NULL;
		}
	}
	errlog2event_hash_use_count++;
	
	/* Initialize "Event Number to HPI Event" mapping hash table */
	if (event2hpi_hash_init(handle)) {
		dbg("Out of memory.");
		return NULL;
	}
  
	if (is_simulator()) {
		sim_banner(custom_handle);
	}
	
        return handle;
}
示例#24
0
void
VMTools_ConfigLogging(const gchar *defaultDomain,
                      GKeyFile *cfg,
                      gboolean force,
                      gboolean reset)
{
   gboolean allocDict = (cfg == NULL);
   gchar **list;
   gchar **curr;
   GPtrArray *oldDomains = NULL;
   LogHandler *oldDefault = NULL;
   GError *err = NULL;

   g_return_if_fail(defaultDomain != NULL);

   if (allocDict) {
      cfg = g_key_file_new();
   }

   /*
    * If not resetting the logging system, keep the old domains around. After
    * we're done loading the new configuration, we'll go through the old domains
    * and restore any data that needs restoring, and clean up anything else.
    */
   VMToolsResetLogging(reset);
   if (!reset) {
      oldDefault = gDefaultData;
      oldDomains = gDomains;
      gDomains = NULL;
      gDefaultData = NULL;
   }

   gLogDomain = g_strdup(defaultDomain);
   gErrorData = VMToolsGetLogHandler(SAFE_HANDLER,
                                     gLogDomain,
                                     G_LOG_LEVEL_MASK,
                                     cfg);

   /*
    * The syslog handler used for G_LOG_FLAG_FATAL.
    * This is only used if the default handler isn't type 'syslog'.
    */
   gErrorSyslog = VMToolsGetLogHandler("syslog",
                                       gLogDomain,
                                       G_LOG_FLAG_FATAL,
                                       cfg);

   /*
    * Configure the default domain first. See function documentation for
    * VMToolsConfigLogDomain() for the reason.
    */
   VMToolsConfigLogDomain(gLogDomain, cfg, oldDefault, oldDomains);

   list = g_key_file_get_keys(cfg, LOGGING_GROUP, NULL, NULL);

   for (curr = list; curr != NULL && *curr != NULL; curr++) {
      gchar *domain = *curr;

      /* Check whether it's a domain "declaration". */
      if (!g_str_has_suffix(domain, ".level")) {
         continue;
      }

      /* Trims ".level" from the key to get the domain name. */
      domain[strlen(domain) - 6] = '\0';

      /* Skip the default domain. */
      if (strcmp(domain, gLogDomain) == 0) {
         continue;
      }

      VMToolsConfigLogDomain(domain, cfg, oldDefault, oldDomains);
   }

   g_strfreev(list);

   gLogEnabled = g_key_file_get_boolean(cfg, LOGGING_GROUP, "log", NULL);

   /*
    * Need to set these so that the code below in this function
    * can also log messages.
    */
   gLogEnabled |= force;
   if (!gLogInitialized) {
      gLogInitialized = TRUE;
      g_static_rec_mutex_init(&gLogStateMutex);
   }

   gMaxCacheEntries = g_key_file_get_integer(cfg, LOGGING_GROUP,
                                             "maxCacheEntries", &err);
   if (err != NULL || gMaxCacheEntries < 0) {
      /*
       * Use default value in case of error.
       * A value '0' will turn off log caching.
       */
      gMaxCacheEntries = DEFAULT_MAX_CACHE_ENTRIES;
      if (err != NULL) {
         if (err->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND &&
             err->code != G_KEY_FILE_ERROR_GROUP_NOT_FOUND) {
            g_warning("Invalid value for maxCacheEntries key: Error %d.",
                      err->code);
         }
         g_clear_error(&err);
      }
   }

   if (gMaxCacheEntries > 0) {
      g_message("Log caching is enabled with maxCacheEntries=%d.",
                gMaxCacheEntries);
   } else {
      g_message("Log caching is disabled.");
   }

   if (g_key_file_has_key(cfg, LOGGING_GROUP, "enableCoreDump", NULL)) {
      gEnableCoreDump = g_key_file_get_boolean(cfg, LOGGING_GROUP,
                                               "enableCoreDump", NULL);
   }

   /* If needed, restore the old configuration. */
   if (!reset) {
      if (oldDomains != NULL) {
         g_ptr_array_free(oldDomains, TRUE);
      }
   }

   /*
    * If core dumps are enabled (default: TRUE), then set up the exception
    * filter on Win32. On POSIX systems, try to modify the resource limit
    * to allow core dumps, but don't complain if it fails. Core dumps may
    * still fail, e.g., if the current directory is not writable by the
    * user running the process.
    *
    * On POSIX systems, if the process is itself requesting a core dump (e.g.,
    * by calling Panic() or g_error()), the core dump routine will try to find
    * a location where it can successfully create the core file. Applications
    * can try to set up core dump filters (e.g., a signal handler for SIGSEGV)
    * that can then call any of the core dumping functions handled by this
    * library.
    *
    * On POSIX systems, the maximum size of a core dump can be controlled by
    * the "maxCoreSize" config option, where "0" means "no limit". By default,
    * it's set to 5MB.
    */
   if (gEnableCoreDump) {
#if defined(_WIN32)
      if (g_key_file_has_key(cfg, LOGGING_GROUP, "coreDumpFlags", NULL)) {
         guint coreDumpFlags;
         coreDumpFlags = g_key_file_get_integer(cfg, LOGGING_GROUP, "coreDumpFlags", &err);
         if (err != NULL) {
            coreDumpFlags = 0;
            g_clear_error(&err);
         }
         /*
          * For flag values and information on their meanings see:
          * http://msdn.microsoft.com/en-us/library/windows/desktop/ms680519(v=vs.85).aspx
          */
         coreDumpFlags &= MiniDumpValidTypeFlags;
         g_message("Core dump flags set to %u", coreDumpFlags);
         Panic_SetCoreDumpFlags(coreDumpFlags);
      }
      CoreDump_SetUnhandledExceptionFilter();
#else
      struct rlimit limit = { 0, 0 };

      getrlimit(RLIMIT_CORE, &limit);
      if (limit.rlim_max != 0) {
         limit.rlim_cur = (rlim_t) g_key_file_get_integer(cfg,
                                                          LOGGING_GROUP,
                                                          "maxCoreSize",
                                                          &err);
         if (err != NULL) {
            limit.rlim_cur = 5 * 1024 * 1024;
            g_clear_error(&err);
         } else if (limit.rlim_cur == 0) {
            limit.rlim_cur = RLIM_INFINITY;
         }

         limit.rlim_cur = MAX(limit.rlim_cur, limit.rlim_max);
         if (setrlimit(RLIMIT_CORE, &limit) == -1) {
            g_message("Failed to set core dump size limit, error %d (%s)\n",
                      errno, g_strerror(errno));
         } else {
            g_message("Core dump limit set to %d", (int) limit.rlim_cur);
         }
      }
#endif
   }

   if (allocDict) {
      g_key_file_free(cfg);
   }
}
示例#25
0
lcm_t * 
lcm_create (const char *url)
{
    if (!g_thread_supported ()) g_thread_init (NULL);

#ifdef WIN32
	WSADATA	wsd;
    int status = WSAStartup ( MAKEWORD ( 2, 0 ), &wsd );
    if ( status )
    {
		return NULL;
    }
#endif

    char * provider_str = NULL;
    char * network = NULL;
    GHashTable * args = g_hash_table_new_full (g_str_hash, g_str_equal,
            free, free);
    GPtrArray * providers = g_ptr_array_new ();
    lcm_t *lcm = NULL;

    // initialize the list of providers
    lcm_udpm_provider_init (providers);
    lcm_logprov_provider_init (providers);
    lcm_tcpq_provider_init (providers);
    if (providers->len == 0) {
        fprintf (stderr, "Error: no LCM providers found\n");
        goto fail;
    }

    if (!url || !strlen(url)) 
        url = getenv ("LCM_DEFAULT_URL");
    if (!url || !strlen(url))
        url = LCM_DEFAULT_URL;

    if (0 != lcm_parse_url (url, &provider_str, &network, args)) {
        fprintf (stderr, "%s:%d -- invalid URL [%s]\n",
                __FILE__, __LINE__, url);
        goto fail;
    }

    lcm_provider_info_t * info = NULL;
    /* Find a matching provider */
    for (unsigned int i = 0; i < providers->len; i++) {
        lcm_provider_info_t * pinfo = (lcm_provider_info_t *) g_ptr_array_index (providers, i);
        if (!strcmp (pinfo->name, provider_str)) {
            info = pinfo;
            break;
        }
    }
    if (!info) {
        fprintf (stderr, "Error: LCM provider \"%s\" not found\n",
                provider_str);
        g_ptr_array_free (providers, TRUE);
        free (provider_str);
        free (network);
        g_hash_table_destroy (args);
        return NULL;
    }

    lcm = (lcm_t *) calloc (1, sizeof (lcm_t));

    lcm->vtable = info->vtable;
    lcm->handlers_all = g_ptr_array_new();
    lcm->handlers_map = g_hash_table_new (g_str_hash, g_str_equal);

    g_static_rec_mutex_init (&lcm->mutex);
    g_static_rec_mutex_init (&lcm->handle_mutex);

    lcm->provider = info->vtable->create (lcm, network, args);
    lcm->in_handle = 0;

    free (provider_str);
    free (network);
    g_ptr_array_free (providers, TRUE);
    g_hash_table_destroy (args);

    if (!lcm->provider) {
        lcm_destroy (lcm);
        return NULL;
    }

    lcm->default_max_num_queued_messages = 30;

    return lcm;

fail:
    free (provider_str);
    free (network);
    if (args)
        g_hash_table_destroy (args);
    if (providers)
        g_ptr_array_free (providers, TRUE);
//    if (lcm)
//        lcm_destroy (lcm);
    return NULL;
}
示例#26
0
lcm_provider_t * 
lcm_udpm_create (lcm_t * parent, const char *network, const GHashTable *args)
{
    udpm_params_t params;
    memset (&params, 0, sizeof (udpm_params_t));

    g_hash_table_foreach ((GHashTable*) args, new_argument, &params);

    if (parse_mc_addr_and_port (network, &params) < 0) {
        return NULL;
    }

    lcm_udpm_t * lcm = (lcm_udpm_t *) calloc (1, sizeof (lcm_udpm_t));

    lcm->lcm = parent;
    lcm->params = params;
    lcm->recvfd = -1;
    lcm->sendfd = -1;
    lcm->thread_msg_pipe[0] = lcm->thread_msg_pipe[1] = -1;
    lcm->udp_low_watermark = 1.0;

    lcm->kernel_rbuf_sz = 0;
    lcm->warned_about_small_kernel_buf = 0;

    lcm->frag_bufs = NULL;

    // synchronization variables used when allocating receive resources
    lcm->creating_read_thread = 0;
    lcm->create_read_thread_mutex = NULL;
    lcm->create_read_thread_cond = NULL;

    // internal notification pipe
    if(0 != lcm_internal_pipe_create(lcm->notify_pipe)) {
        perror(__FILE__ " pipe(create)");
        lcm_udpm_destroy (lcm);
        return NULL;
    }
    fcntl (lcm->notify_pipe[1], F_SETFL, O_NONBLOCK);

    g_static_rec_mutex_init (&lcm->mutex);
    g_static_mutex_init (&lcm->transmit_lock);

    dbg (DBG_LCM, "Initializing LCM UDPM context...\n");
    dbg (DBG_LCM, "Multicast %s:%d\n", inet_ntoa(params.mc_addr), ntohs (params.mc_port));

    // setup destination multicast address
    memset (&lcm->dest_addr, 0, sizeof (lcm->dest_addr));
    lcm->dest_addr.sin_family = AF_INET;
    lcm->dest_addr.sin_addr = params.mc_addr;
    lcm->dest_addr.sin_port = params.mc_port;

    // test connectivity
    SOCKET testfd = socket (AF_INET, SOCK_DGRAM, 0);
    if (connect (testfd, (struct sockaddr*) &lcm->dest_addr, 
                sizeof (lcm->dest_addr)) < 0) {

        perror ("connect");
        lcm_udpm_destroy (lcm);
#ifdef __linux__
        linux_check_routing_table(lcm->dest_addr.sin_addr);
#endif
        return NULL;
    }
    lcm_close_socket(testfd);

    // create a transmit socket
    //
    // don't use connect() on the actual transmit socket, because linux then
    // has problems multicasting to localhost
    lcm->sendfd = socket (AF_INET, SOCK_DGRAM, 0);

    // set multicast TTL
    if (params.mc_ttl == 0) {
        dbg (DBG_LCM, "LCM multicast TTL set to 0.  Packets will not "
                "leave localhost\n");
    }
    dbg (DBG_LCM, "LCM: setting multicast packet TTL to %d\n", params.mc_ttl);
    if (setsockopt (lcm->sendfd, IPPROTO_IP, IP_MULTICAST_TTL,
                (char *) &params.mc_ttl, sizeof (params.mc_ttl)) < 0) {
        perror ("setsockopt(IPPROTO_IP, IP_MULTICAST_TTL)");
        lcm_udpm_destroy (lcm);
        return NULL;
    }

#ifdef WIN32
    // Windows has small (8k) buffer by default
    // increase the send buffer to a reasonable amount.
    int send_buf_size = 256 * 1024;
    setsockopt(lcm->sendfd, SOL_SOCKET, SO_SNDBUF, 
            (char*)&send_buf_size, sizeof(send_buf_size));
#endif

    // debugging... how big is the send buffer?
    int sockbufsize = 0;
    unsigned int retsize = sizeof(int);
    getsockopt(lcm->sendfd, SOL_SOCKET, SO_SNDBUF, 
            (char*)&sockbufsize, (socklen_t *) &retsize);
    dbg (DBG_LCM, "LCM: send buffer is %d bytes\n", sockbufsize);

    // set loopback option on the send socket
#ifdef __sun__
    unsigned char send_lo_opt = 1;
#else
    unsigned int send_lo_opt = 1;
#endif
    if (setsockopt (lcm->sendfd, IPPROTO_IP, IP_MULTICAST_LOOP, 
                (char *) &send_lo_opt, sizeof (send_lo_opt)) < 0) {
        perror ("setsockopt (IPPROTO_IP, IP_MULTICAST_LOOP)");
        lcm_udpm_destroy (lcm);
        return NULL;
    }

    // don't start the receive thread yet.  Only allocate resources for
    // receiving messages when a subscription is made.

    // However, we still need to setup sendfd in multi-cast group
    struct ip_mreq mreq;
    mreq.imr_multiaddr = lcm->params.mc_addr;
    mreq.imr_interface.s_addr = INADDR_ANY;
    dbg (DBG_LCM, "LCM: joining multicast group\n");
    if (setsockopt (lcm->sendfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
            (char*)&mreq, sizeof (mreq)) < 0) {
#ifdef WIN32
      // ignore this error in windows... see issue #60
#else
        perror ("setsockopt (IPPROTO_IP, IP_ADD_MEMBERSHIP)");
        lcm_udpm_destroy (lcm);
        return NULL;
#endif
    }

    return lcm;
}
static void
gst_decklink_src_init (GstDecklinkSrc * decklinksrc,
                       GstDecklinkSrcClass * decklinksrc_class)
{
    g_static_rec_mutex_init (&decklinksrc->task_mutex);
    decklinksrc->task = gst_task_create (gst_decklink_src_task, decklinksrc);
    gst_task_set_lock (decklinksrc->task, &decklinksrc->task_mutex);

    decklinksrc->audiosrcpad =
        gst_pad_new_from_static_template (&gst_decklink_src_audio_src_template,
                                          "audiosrc");
    gst_pad_set_getcaps_function (decklinksrc->audiosrcpad,
                                  GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_getcaps));
    gst_pad_set_setcaps_function (decklinksrc->audiosrcpad,
                                  GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_setcaps));
    gst_pad_set_acceptcaps_function (decklinksrc->audiosrcpad,
                                     GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_acceptcaps));
    gst_pad_set_fixatecaps_function (decklinksrc->audiosrcpad,
                                     GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_fixatecaps));
    gst_pad_set_activate_function (decklinksrc->audiosrcpad,
                                   GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_activate));
    gst_pad_set_activatepush_function (decklinksrc->audiosrcpad,
                                       GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_activatepush));
    gst_pad_set_activatepull_function (decklinksrc->audiosrcpad,
                                       GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_activatepull));
    gst_pad_set_link_function (decklinksrc->audiosrcpad,
                               GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_link));
    gst_pad_set_getrange_function (decklinksrc->audiosrcpad,
                                   GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_getrange));
    gst_pad_set_event_function (decklinksrc->audiosrcpad,
                                GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_event));
    gst_pad_set_query_function (decklinksrc->audiosrcpad,
                                GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_query));
    gst_pad_set_iterate_internal_links_function (decklinksrc->audiosrcpad,
            GST_DEBUG_FUNCPTR (gst_decklink_src_audio_src_iterintlink));
    gst_element_add_pad (GST_ELEMENT (decklinksrc), decklinksrc->audiosrcpad);



    decklinksrc->videosrcpad =
        gst_pad_new_from_template (gst_element_class_get_pad_template
                                   (GST_ELEMENT_CLASS (decklinksrc_class), "videosrc"), "videosrc");
    gst_pad_set_getcaps_function (decklinksrc->videosrcpad,
                                  GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_getcaps));
    gst_pad_set_setcaps_function (decklinksrc->videosrcpad,
                                  GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_setcaps));
    gst_pad_set_acceptcaps_function (decklinksrc->videosrcpad,
                                     GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_acceptcaps));
    gst_pad_set_fixatecaps_function (decklinksrc->videosrcpad,
                                     GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_fixatecaps));
    gst_pad_set_activate_function (decklinksrc->videosrcpad,
                                   GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_activate));
    gst_pad_set_activatepush_function (decklinksrc->videosrcpad,
                                       GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_activatepush));
    gst_pad_set_activatepull_function (decklinksrc->videosrcpad,
                                       GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_activatepull));
    gst_pad_set_link_function (decklinksrc->videosrcpad,
                               GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_link));
    gst_pad_set_getrange_function (decklinksrc->videosrcpad,
                                   GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_getrange));
    gst_pad_set_event_function (decklinksrc->videosrcpad,
                                GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_event));
    gst_pad_set_query_function (decklinksrc->videosrcpad,
                                GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_query));
    gst_pad_set_iterate_internal_links_function (decklinksrc->videosrcpad,
            GST_DEBUG_FUNCPTR (gst_decklink_src_video_src_iterintlink));
    gst_element_add_pad (GST_ELEMENT (decklinksrc), decklinksrc->videosrcpad);


    decklinksrc->cond = g_cond_new ();
    decklinksrc->mutex = g_mutex_new ();

    decklinksrc->copy_data = TRUE;
    decklinksrc->mode = GST_DECKLINK_MODE_NTSC;
    decklinksrc->connection = GST_DECKLINK_CONNECTION_SDI;
    decklinksrc->audio_connection = GST_DECKLINK_AUDIO_CONNECTION_AUTO;
    decklinksrc->subdevice = 0;

    decklinksrc->stop = FALSE;
    decklinksrc->dropped_frames = 0;
    decklinksrc->dropped_frames_old = 0;
    decklinksrc->frame_num = -1; /* -1 so will be 0 after incrementing */

#ifdef _MSC_VER
    decklinksrc->com_init_lock = g_mutex_new();
    decklinksrc->com_deinit_lock = g_mutex_new();
    decklinksrc->com_initialized = g_cond_new();
    decklinksrc->com_uninitialize = g_cond_new();
    decklinksrc->com_uninitialized = g_cond_new();

    g_mutex_lock (decklinksrc->com_init_lock);

    /* create the COM initialization thread */
    g_thread_create ((GThreadFunc)gst_decklink_src_com_thread,
                     decklinksrc, FALSE, NULL);

    /* wait until the COM thread signals that COM has been initialized */
    g_cond_wait (decklinksrc->com_initialized, decklinksrc->com_init_lock);
    g_mutex_unlock (decklinksrc->com_init_lock);
#endif /* _MSC_VER */
}
示例#28
0
/**
 * oh_load_plugin
 * @plugin_name: name of plugin to be loaded (e.g. "libdummy").
 *
 * Load plugin by name
 *
 * Returns: 0 on Success.
 **/
int oh_load_plugin(char *plugin_name)
{

        struct oh_plugin *plugin = NULL;
        struct oh_static_plugin *p = static_plugins;
        int err;

        if (!plugin_name) {
                err("ERROR. NULL plugin name passed.");
                return -1;
        }

        if (oh_init_ltdl()) {
                err("ERROR. Could not initialize ltdl for loading plugins.");
                return -1;
        }

        plugin = oh_get_plugin(plugin_name);
        if (plugin) {
                oh_release_plugin(plugin);
                dbg("Plugin %s already loaded. Not loading twice.",
                    plugin_name);
                return 0;
        }

        plugin = (struct oh_plugin *)g_malloc0(sizeof(struct oh_plugin));
        if (!plugin) {
                err("Out of memory.");
                return -1;
        }
        plugin->name = g_strdup(plugin_name);
        plugin->handler_count = 0;
        plugin->refcount = 0;
        g_static_rec_mutex_init(&plugin->lock);
        g_static_rec_mutex_init(&plugin->refcount_lock);

        /* first take search plugin in the array of static plugin */
        while (p->name) {
                if (!strcmp(plugin->name, p->name)) {
                        plugin->dl_handle = 0;
                        err = (*p->get_interface)((void **)&plugin->abi, UUID_OH_ABI_V2);

                        if (err < 0 || !plugin->abi || !plugin->abi->open) {
                                err("Can not get ABI V2");
                                goto cleanup_and_quit;
                        }

                        dbg("found static plugin %s", p->name);

                        g_static_rec_mutex_lock(&oh_plugins.lock);
                        oh_plugins.list = g_slist_append(oh_plugins.list, plugin);
                        g_static_rec_mutex_unlock(&oh_plugins.lock);

                        return 0;
                }
                p++;
        }

        plugin->dl_handle = lt_dlopenext(plugin->name);
        if (plugin->dl_handle == NULL) {
                err("Can not open %s plugin: %s", plugin->name, lt_dlerror());
                goto cleanup_and_quit;
        }

        err = oh_load_plugin_functions(plugin, &plugin->abi);

        if (err < 0 || !plugin->abi || !plugin->abi->open) {
                err("Can not get ABI");
                goto cleanup_and_quit;
        }
        g_static_rec_mutex_lock(&oh_plugins.lock);
        oh_plugins.list = g_slist_append(oh_plugins.list, plugin);
        g_static_rec_mutex_unlock(&oh_plugins.lock);

        return 0;
cleanup_and_quit:
        __delete_plugin(plugin);
        return -1;
}
示例#29
0
static void
gst_object_class_init (GstObjectClass * klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  parent_class = g_type_class_peek_parent (klass);

#ifndef GST_DISABLE_TRACE
  _gst_object_trace = gst_alloc_trace_register (g_type_name (GST_TYPE_OBJECT));
#endif

  gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_object_set_property);
  gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_object_get_property);

  g_object_class_install_property (gobject_class, ARG_NAME,
      g_param_spec_string ("name", "Name", "The name of the object",
          NULL,
          G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));

  /**
   * GstObject::parent-set:
   * @gstobject: a #GstObject
   * @parent: the new parent
   *
   * Emitted when the parent of an object is set.
   */
  gst_object_signals[PARENT_SET] =
      g_signal_new ("parent-set", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
      G_STRUCT_OFFSET (GstObjectClass, parent_set), NULL, NULL,
      g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_OBJECT);

  /**
   * GstObject::parent-unset:
   * @gstobject: a #GstObject
   * @parent: the old parent
   *
   * Emitted when the parent of an object is unset.
   */
  gst_object_signals[PARENT_UNSET] =
      g_signal_new ("parent-unset", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstObjectClass, parent_unset), NULL,
      NULL, g_cclosure_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_OBJECT);

#ifndef GST_DISABLE_LOADSAVE
  /**
   * GstObject::object-saved:
   * @gstobject: a #GstObject
   * @xml_node: the xmlNodePtr of the parent node
   *
   * Trigered whenever a new object is saved to XML. You can connect to this
   * signal to insert custom XML tags into the core XML.
   */
  /* FIXME This should be the GType of xmlNodePtr instead of G_TYPE_POINTER
   *       (if libxml would use GObject)
   */
  gst_object_signals[OBJECT_SAVED] =
      g_signal_new ("object-saved", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstObjectClass, object_saved), NULL,
      NULL, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER);

  klass->restore_thyself = gst_object_real_restore_thyself;
#endif

  /**
   * GstObject::deep-notify:
   * @gstobject: a #GstObject
   * @prop_object: the object that originated the signal
   * @prop: the property that changed
   *
   * The deep notify signal is used to be notified of property changes. It is
   * typically attached to the toplevel bin to receive notifications from all
   * the elements contained in that bin.
   */
  gst_object_signals[DEEP_NOTIFY] =
      g_signal_new ("deep-notify", G_TYPE_FROM_CLASS (klass),
      G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED |
      G_SIGNAL_NO_HOOKS, G_STRUCT_OFFSET (GstObjectClass, deep_notify), NULL,
      NULL, gst_marshal_VOID__OBJECT_PARAM, G_TYPE_NONE, 2, GST_TYPE_OBJECT,
      G_TYPE_PARAM);

  klass->path_string_separator = "/";
  klass->lock = g_new0 (GStaticRecMutex, 1);
  g_static_rec_mutex_init (klass->lock);

  klass->signal_object = g_object_new (gst_signal_object_get_type (), NULL);

  /* see the comments at gst_object_dispatch_properties_changed */
  gobject_class->dispatch_properties_changed
      = GST_DEBUG_FUNCPTR (gst_object_dispatch_properties_changed);

  gobject_class->dispose = gst_object_dispose;
  gobject_class->finalize = gst_object_finalize;
}
static gboolean
gst_ss_demux_sink_event (GstPad * pad, GstEvent * event)
{
  GstSSDemux *demux = GST_SS_DEMUX (gst_pad_get_parent (pad));
  GstQuery *query;
  gboolean ret;
  gchar *uri;

  switch (event->type) {
    case GST_EVENT_EOS: {
      int i = 0;
      if (demux->manifest == NULL) {
        GST_WARNING_OBJECT (demux, "Received EOS without a manifest.");
        break;
      }

      GST_DEBUG_OBJECT (demux, "Got EOS on the sink pad: mainifest file fetched");

      query = gst_query_new_uri ();
      ret = gst_pad_peer_query (demux->sinkpad, query);
      if (ret) {
        gst_query_parse_uri (query, &uri);
        demux->parser = gst_ssm_parse_new (uri);
        g_free (uri);
      } else {
        GST_ERROR_OBJECT (demux, "failed to query URI from upstream");
        return FALSE;
      }
      gst_query_unref (query);

      GST_LOG_OBJECT (demux, "data = %p & size = %d", GST_BUFFER_DATA(demux->manifest), GST_BUFFER_SIZE(demux->manifest));
      if (!gst_ssm_parse_manifest (demux->parser, (char *)GST_BUFFER_DATA(demux->manifest), GST_BUFFER_SIZE(demux->manifest))) {
        /* In most cases, this will happen if we set a wrong url in the
         * source element and we have received the 404 HTML response instead of
         * the playlist */
        GST_ELEMENT_ERROR (demux, STREAM, DECODE, ("Invalid playlist."),
            (NULL));
        return FALSE;
      }

      for( i = 0; i < SS_STREAM_NUM; i++) {
        if (gst_ssm_parse_check_stream (demux->parser, i)) {
          GstSSDemuxStream *stream = g_new0 (GstSSDemuxStream, 1);

          // Add pad emission of the stream
          gst_ss_demux_stream_init (demux, stream, i);
          g_static_rec_mutex_init (&stream->stream_lock);
          stream->stream_task = gst_task_create ((GstTaskFunction) gst_ss_demux_stream_loop, demux);
          gst_task_set_lock (stream->stream_task, &stream->stream_lock);
          demux->streams[i] = stream;
          g_print ("Starting stream - %d task loop...\n", i);
          gst_task_start (stream->stream_task);
        }
      }

      gst_event_unref (event);
      return TRUE;
    }
    case GST_EVENT_NEWSEGMENT:
      /* Swallow newsegments, we'll push our own */
      gst_event_unref (event);
      return TRUE;
    default:
      break;
  }

  return gst_pad_event_default (pad, event);
}