ginsfsm / ginsfsm / gaplic.py

The default branch has multiple heads

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
# -*- encoding: utf-8 -*-
""" Container of gobjs.


.. autoclass:: GAplic
    :members: create_gobj, destroy_gobj,
        register_unique_gobj, deregister_unique_gobj, find_unique_gobj,
        mt_process, mt_subprocess

.. autofunction:: setup_gaplic_thread

.. autoclass:: GAplicThreadWorker
    :members:

.. autofunction:: setup_gaplic_process

.. autoclass:: GAplicProcessWorker
    :members:

.. autofunction:: gaplic_factory

"""
import time
import threading
import logging
from collections import deque

from ginsfsm.globals import (
    set_global_main_gaplic,
    set_global_app,
    add_global_thread,
    add_global_subprocess,
    get_gaplic_by_thread_ident,
)
from ginsfsm.compat import (
    string_types,
    iterkeys_,
)
from ginsfsm.deferred import (
    DeferredList,
    Deferred,
)
from ginsfsm.c_sock import (
    poll_loop,
    close_all_sockets,
    _poll,
    GSock,
)
from ginsfsm.gobj import (
    GObj,
)


class DuplicateUniqueGObjError(Exception):
    """ Raised when an unique named gobj is duplicated."""


class NotUniqueNamedGObjError(Exception):
    """ Raised when an principal gobj is not a unique named gobj."""


def _start_timer(seconds):
    """ Start a timer of :param:`seconds` seconds.
    The returned value must be used to check the end of the timer
    with _test_timer() function.
    """
    timer = time.time()
    timer = timer + seconds
    return timer


def _test_timer(value):
    """ Check if timer :param:`value` has ended.
    Return True if the timer has elapsed, False otherwise.
    WARNING: it will fail when system clock has been changed.
    TODO: check if system clock has been changed.
    """
    timer_actual = time.time()
    if timer_actual >= value:
        return True
    else:
        return False


class _XTimer(object):
    """  Group attributes for timing.
    :param:`got_timer` callback will be executed :param:`sec` seconds.
    The callback will be called with :param:`param1` parameter.
    If :param:`autostart` is True, the timer will be cyclic.
    """
    def __init__(self, sec, got_timer_func, param1, autostart):
        self.sec = sec
        self.got_timer_func = got_timer_func
        self.param1 = param1
        self.autostart = autostart


def ac_deferred_callback(self, event):
    deferred_ref = event.deferred_ref
    self.deferred_list(deferred_ref, ext_event=event)
    self.deferred_list.delete(deferred_ref)

GAPLIC_FSM = {
    'event_list': ('EV_DEFERRED_CALLBACK',),
    'state_list': ('ST_IDLE',),
    'machine': {
        'ST_IDLE':
        (
            ('EV_DEFERRED_CALLBACK', ac_deferred_callback, 'ST_IDLE'),
        ),
    }
}

GAPLIC_GCONFIG = {
    'ini_settings': [dict, {}, 0, None,
        'The ini settings will be set to all new created gobj'
        ' by overwrite_parameters() function'],
    # trace_mach is inherited from SMachine.
    'trace_mach': [bool, False, 0, None, 'Display simple machine activity'],
    # logger is inherited from SMachine.
    'logger': [None, None, 0, None, ''],
}


class GAplic(GObj):
    """ Container of gobj's running under the same process or thread.

    :param name: name of the gaplic, default is ``None``.
    :param ini_settings: keyword arguments,
        with the parameters from a ini configfile.
        The ini settings will be set to all new created gobj
        by :func:`ginsfsm.gobj.GObj.overwrite_parameters` function.


        .. note::

           The parameters can be dot named to include
           the :term:`named-gobj`'s destination of the parameters.


    GAplic is the main boss.
    Manage the timer's, event queues, etc.
    Supplies register, deregister and search or named-events.

    Example::

        if __name__ == "__main__":
            ga = GAplic(name='Example1')
            ga.create_gobj('test_aplic', GPrincipal, None)
            try:
                ga.mt_process()
            except KeyboardInterrupt:
                print('Program stopped')

    """
    def __init__(self, name=None, **ini_settings):
        GObj.__init__(self, GAPLIC_FSM)
        self.name = name
        self.ini_settings = ini_settings.copy()
        # Call shutdown() to stop gaplic
        self.do_exit = multiprocessing.Event()
        """ threading.Event() or multiprocessing.Event() object
        to signal the shutdown of gaplic."""
        self.loop_timeout = 0.5     # timeout to select(),poll() function.
        """ Loop timeout. Default 0.5 seconds.
            It's the minimun timer resolution you can have.
        """
        self._impl_poll = _poll()   # Used by gsock. epoll() implementation.
        self._socket_map = {}       # Used by gsock. Dict {fd:Gobj}
        self._gotter_timers = {}    # Dict with timers  {_XTimer:timer value}
        self._qevent = deque()      # queue for post events.
        self._callbacks = []        # callbacks compatible with tornado.io_loop
        self._inside = 0            # to tab machine trace.
        self._unique_named_gobjs = {}
        self._thread_ident = None
        self._thread_name = 0
        self.gaplic = self
        self.deferred_list = DeferredList()

        logger = ini_settings.get('logger', None)
        if logger is None:
            # TODO use package caller
            self.logger = logging.getLogger(__name__)
        else:
            if isinstance(logger, string_types):
                self.logger = logging.getLogger(logger)
            else:
                self.logger = logger
        self.logger and self.logger.info('GAplic (%s) initiated' % self.name)

    def _increase_inside(self):
        self._inside += 1

    def _decrease_inside(self):
        self._inside -= 1

    def _tab(self):
        if self._inside <= 0:
            spaces = 1
        else:
            spaces = self._inside * 2
        pad = ' ' * spaces
        return pad

    def create_gobj(self, name, gclass, parent, **kw):
        """ Factory function to create gobj's instances.

        :param name: Name of the gobj.
            If the key `__unique_name__` passed in *kw* is True,
            then the gobj will be a :term:`unique-named-gobj` and.
            the :meth:`GObj.register_unique_gobj` will be called.
            If :meth:`GObj.register_unique_gobj` fails, a
            :exc:DuplicateUniqueGObjError exception will be raised.

        :param gclass: `gclass` is the GObj type used to create the new gobj.
            It's must be a derived class of :class:`ginsfsm.gobj.GObj`.

        :param parent: parent of the new :term:`gobj`.
            If `None`, the gobj will be a :term:`principal` gobj.

        :param kw: Attributes that are added to the new :term:`gobj`.
            All the keyword arguments used in the function
            **are added as attributes** to the created :term:`gobj`,
            except: `__unique_name__` and `__random_name__`.
            You must consult the attributes supported
            by each `gclass` type.
            The attributes must be defined in the gclass GCONFIG,
            otherwise they are ignored.

        :rtype: new gobj instance.

        When a :term:`gobj` is created by the factory function, it's added to
        their parent child list :attr:`ginsfsm.gobj.GObj.dl_childs`,
        and several attributes are created:

        * **parent**: the parent :term:`gobj` of the created :term:`gobj`.
        * **gaplic**: the :term:`gaplic` of the created :term:`gobj`.

        If the `gclass` is subclass of :class:`ginsfsm.c_sock.GSock`
        two private attributes are added to the created  :term:`gobj`:

        * **_socket_map**: dictionary of open sockets.
        * **_impl_poll**: poll implementation: can be epoll, select, KQueue..
          the best found option.

        It's the base of the asynchronous behavior.
        """
        __unique_name__ = kw.pop('__unique_name__', False)
        __random_name__ = kw.pop('__random_name__', False)  # TODO
        if __random_name__:
            name = '???'  # TODO eliminate create_random_named_gobj()
                          # but is it necessary???

        _gaplic_kw = {
            'gaplic': self,
            'logger': self.logger,
            'ini_settings': self.ini_settings,
            'create_gobj': self.create_gobj,
            'destroy_gobj': self.destroy_gobj,
            'enqueue_event': self.enqueue_event,
            '_increase_inside': self._increase_inside,
            '_decrease_inside': self._decrease_inside,
            '_tab': self._tab,
        }

        if issubclass(gclass, GSock):
            _gaplic_kw.update({
                '_socket_map': self._socket_map,
                '_impl_poll': self._impl_poll
            })

        kw.update(_gaplic_kw)

        gobj = GObj.create_gobj(self, name, gclass, parent, **kw)

        if __unique_name__:
            registered = self.register_unique_gobj(gobj)
            if not registered:
                raise DuplicateUniqueGObjError(
                    '''ERROR create_gobj():'''
                    ''' cannot register_unique_gobj '%s' ''' % (name))
            self.__unique_name__ = True
        else:
            self.__unique_name__ = False
        return gobj

    def destroy_gobj(self, gobj):
        """ Destroy a gobj
        """
        if self.__unique_name__:
            self.deregister_unique_gobj(gobj)
        GObj.destroy_gobj(self, gobj)

    def get_unique_named_gobjs(self):
        """ Return the list of :term:`unique-named-gobj`'s.
        """
        return [name for name in iterkeys_(self._unique_named_gobjs)]

    def register_unique_gobj(self, gobj):
        """ Register a :term:`unique-named-gobj`.
        """
        named_gobj = self._unique_named_gobjs.get(gobj.name, None)
        if named_gobj is not None:
            self.logger and self.logger.info(
                'ERROR register_unique_gobj() "%s" ALREADY REGISTERED' %
                gobj.name)
            return False
        self._unique_named_gobjs[gobj.name] = gobj
        gobj.__unique_name__ = True
        return True

    def deregister_unique_gobj(self, gobj):
        """ Deregister a :term:`unique-named-gobj`.
        """
        named_gobj = self._unique_named_gobjs.get(gobj.name, None)
        if named_gobj is not None:
            del self._unique_named_gobjs[gobj.name]
            return True
        return False

    def find_unique_gobj(self, gobj_name):
        """ Find a :term:`named-gobj`.
        """
        named_gobj = self._unique_named_gobjs.get(gobj_name, None)
        return named_gobj

    def delete_all_references(self, gobj):
        """ Delete all references of gobj in timer and event queues.
        """
        # TODO: by the moment, be care with your event generation

    def _loop(self):
        """ process event queue, timer queue, and epoll.
        Return True if there is some remain event for be proccessed.
        Useful for testing purposes.
        """
        if not self._thread_ident:
            self._thread_ident = threading.current_thread().ident
            self._thread_name = threading.current_thread().name

        timeout = self.loop_timeout  # iniatially wait loop_timeout seconds
        remain = False  # some work pending.

        # Callbacks compatible with tornado.io_loop
        # Prevent IO event starvation by delaying new callbacks
        # to the next iteration of the event loop.
        callbacks = self._callbacks
        if callbacks:
            remain = True
            self._callbacks = []
            for callback in callbacks:
                self._run_callback(callback)

        if self._callbacks:
            # If any callbacks or timeouts called add_callback,
            # we don't want to wait in poll() before we run them.
            timeout = 0.0

        remain |= self._process_qevent()
        if remain:
            # They are remain events,
            # we don't want to wait in poll() before we run them.
            # wait some time, t
            # o avoid recursive send events that puts 100% cpu.
            # TODO: try set 0.0.
            timeout = 0.1

        poll_loop(self._socket_map, self._impl_poll, timeout)

        #
        remain |= self._process_timer()  # don't remove or the tests will fail.

        # oportunity for subclass.
        self.mt_subprocess()

        return remain

    def mt_process(self):
        self.start()

    def start(self):
        """ Infinite loop function to be called by thread or process.
        It's call ``start`` to be used by pasterdeploy
        """
        while True:
            # with do_exit Event set (being thread or process),
            # wait to event set to exit, ignoring KeyboardInterrupt.
            try:
                if self.do_exit.is_set():
                    close_all_sockets(self._socket_map)
                    break
                self._loop()
            except (KeyboardInterrupt, SystemExit):
                close_all_sockets(self._socket_map)
                raise

    def shutdown(self):
        """ Signalize the worker to shutdown """
        self.do_exit.set()

    def mt_subprocess(self):
        """ Subclass :class:`GAplic` class and override this function
        to do extra work in the infinite loop.
        """

    def enqueue_event(self, event):
        """ Post the event in the next :term:`gaplic` loop cycle,
        not right now.

        :param event: :term:`event` to send.
        :param destination: destination :term:`gobj` of the event.
        :param kw: keyword argument with data associated to event.

            .. note::
                All the keyword arguments **are added as attributes** to
                the sent :term:`event`.

        Same as :meth:`send_event` function but the event is sent in the
        next :term:`gaplic` loop cycle, not right now.

        It **does not return** the return of the executed action because the
        action it's executed later, in the next loop cycle.

        It's mandatory use this function, if the `destination`
        :term:`gobj` is not local.

        .. note:: It **DOES NOT** return the return of the executed action
            because the action it's executed later, in the next loop cycle,
            so you **CANNOT** receive valid direct data from the action.

        .. warning:: If you use :meth:`post_event` without a :term:`gaplic`
            then a :exc:`GAplicError` exception will be raised.

        ``destination`` must be a `string` or :class:`GObj` types, otherwise a
        :exc:`GObjError` will be raised.

        ``event`` must be a `string` or :class:`Event` types, otherwise a
        :exc:`EventError` will be raised.

        If ``event`` is an :class:`Event` instance, a new :class:`Event`
        duplicated instance is returned, but it will be updated with
        the new ``destination`` and ``kw`` keyword arguments.

        .. note::
            All the keyword arguments used in the factory function
            **are added as attributes** to the created :term:`event` instance.
            You must consult the attributes supported by each machine's event.
        """
        self._qevent.append(event)

    def _process_qevent(self):
        """ Return True if remains events.
        """
        # ln = len(self._qevent)
        # print "qevent...........%d" % (ln)
        it = 0
        maximum = 10
        while True:
            if it > maximum:
                # balance the work
                return True
            try:
                event = self._qevent.popleft()
            except IndexError:
                break
            else:
                it += 1
                #TODO consider names of another gaplics
                try:
                    destination = self._resolv_destination(event.destination)
                    cur_ident = threading.current_thread().ident
                    if cur_ident != self._thread_ident:
                        logging.error("??????????????????")

                    dst_ident = destination.gaplic._thread_ident
                    if cur_ident == dst_ident:
                        self.send_event(
                            destination,
                            event.event_name,
                            **event.kw)
                    else:
                        # Yeah, send to another gaplic
                        gaplic = get_gaplic_by_thread_ident(dst_ident)
                        if gaplic:
                            gaplic.enqueue_event(event)
                except Exception:
                    logging.error("Exception gaplic.__process_qevent",
                                  exc_info=True)

        return False

    def _process_timer(self):
        # don't use iteritems() items(),
        # some xtimer can be removed during processing timers
        some_event = False
        try:
            for xtimer in iterkeys_(self._gotter_timers):
                try:
                    value = self._gotter_timers[xtimer]
                except KeyError:
                    # timer deleted while loop.
                    continue
                some_event = True
                if value and _test_timer(value):
                    if xtimer.autostart:
                        self._gotter_timers[xtimer] = _start_timer(xtimer.sec)
                    else:
                        self._gotter_timers[xtimer] = 0
                    if xtimer.param1 is None:
                        xtimer.got_timer_func()
                    else:
                        xtimer.got_timer_func(xtimer.param1)
                    if not xtimer.autostart:
                        self._gotter_timers.pop(xtimer)
        except RuntimeError:
            # timer deleted while loop.
            some_event = True
        return some_event

    def _setTimeout(self, sec, got_timer_func, param1=None, autostart=False):
        """ Set a callback to be executed in ``sec`` seconds.
        Function used by :class:`GTimer` gobj. Not for general use.
        Return an object to be used in :func:`clearTimeout`.
        """
        xtimer = _XTimer(sec, got_timer_func, param1, autostart)
        self._gotter_timers[xtimer] = _start_timer(sec)
        return xtimer

    def _clearTimeout(self, xtimer):
        """ Clear callback timeout.
        Function used by :class:`GTimer` gobj. Not for general use.
        """
        t = self._gotter_timers.get(xtimer, None)
        if t:
            # prevent timer cleared in proces_timer loop
            self._gotter_timers[xtimer] = 0
            self._gotter_timers.pop(xtimer)

    def add_timeout(self, deadline, callback):
        """ Compatible with tornado.io_loop

        ``deadline`` only seconds please.

        Calls the given callback at the time deadline from the I/O loop.

        Returns a handle that may be passed to remove_timeout to cancel.

        ``deadline`` may be a number denoting a unix timestamp (as returned
        by ``time.time()`` or a ``datetime.timedelta`` object for a deadline
        relative to the current time.

        Note that it is not safe to call `add_timeout` from other threads.
        Instead, you must use `add_callback` to transfer control to the
        IOLoop's thread, and then call `add_timeout` from there.
        """
        timer_id = self._setTimeout(deadline, callback)
        return timer_id

    def remove_timeout(self, timeout):
        """ Compatible with tornado.io_loop

        Cancels a pending timeout.

        The argument is a handle as returned by add_timeout.
        """
        # Removing from a heap is complicated, so just leave the defunct
        # timeout object in the queue (see discussion in
        # http://docs.python.org/library/heapq.html).
        # If this turns out to be a problem, we could add a garbage
        # collection pass whenever there are too many dead timeouts.
        timeout.callback = None
        self._clearTimeout(timeout)

    def add_callback(self, func, *args, **kwargs):
        """ Compatible with tornado.io_loop

        Calls the given callback on the next I/O loop iteration.

        It is safe to call this method from any thread at any time.
        Note that this is the *only* method in IOLoop that makes this
        guarantee; all other interaction with the IOLoop must be done
        from that IOLoop's thread.  add_callback() may be used to transfer
        control from other threads to the IOLoop's thread.
        """
        list_empty = not self._callbacks
        deferred = Deferred(0, func, *args, **kwargs)
        self._callbacks.append(deferred)
        if list_empty:
            if threading.current_thread().ident != self._thread_ident:
                # If we're in the IOLoop's thread, we know it's not currently
                # polling.  If we're not, and we added the first callback to an
                # empty list, we may need to wake it up (it may wake up on its
                # own, but an occasional extra wake is harmless).  Waking
                # up a polling IOLoop is relatively expensive, so we try to
                # avoid it when we can.
                pass
                # TODO: study this from tornado
                # self._waker.wake()

    def _run_callback(self, deferred):
        try:
            deferred()
        except Exception:
            self.handle_callback_exception(deferred)

    def handle_callback_exception(self, callback):
        """This method is called whenever a callback run by the IOLoop
        throws an exception.

        By default simply logs the exception as an error.  Subclasses
        may override this method to customize reporting of exceptions.

        The exception itself is not passed explicitly, but is available
        in sys.exc_info.
        """
        logging.error("Exception in callback %r", callback, exc_info=True)


#===============================================================
#                   Thread wrapper for gaplic
#===============================================================
class GAplicThreadWorker(threading.Thread):
    """ Class derived from :class:`threading.Thread` to run gaplic."""
    def __init__(self, gaplic):
        threading.Thread.__init__(self)
        self.daemon = True
        self.gaplic = gaplic

    def run(self):
        self.gaplic.mt_process()

    def join(self, timeout=10.0):   # wait until 10 seconds for thread killed.
        """ Wait for worker to shutdown, until ``timeout`` seconds."""
        super(GAplicThreadWorker, self).join(timeout)


def setup_gaplic_thread(gaplic):
    """ Run gaplic as thread.
    Return the worker.
    You must call worker.start() to run the thread.
    """
    worker = GAplicThreadWorker(gaplic)
    add_global_thread(worker)
    return worker

#===============================================================
#                   Process wrapper for gaplic
#===============================================================
import multiprocessing


class GAplicProcessWorker(multiprocessing.Process):
    """ Class derived from :class:`multiprocessing.Process` to run gaplic."""
    def __init__(self, gaplic):
        multiprocessing.Process.__init__(self)
        self.daemon = True
        self.gaplic = gaplic

    def run(self):
        self.gaplic.mt_process()

    def join(self, timeout=10.0):   # wait until 10 seconds for process killed.
        """ Wait for worker to shutdown, until ``timeout`` seconds."""
        super(GAplicProcessWorker, self).join(timeout)


def setup_gaplic_process(gaplic):
    """ Run gaplic as process.
    Return the worker.
    You must call worker.start() to run the subprocess.
    """
    worker = GAplicProcessWorker(gaplic)
    add_global_subprocess(worker)
    return worker


def gaplic_factory(loader, global_conf, **local_conf):
    """ To use with PasteDeploy in composite.

        Items of *composite* section:

        :main: name of a section that must return a :term:`gaplic`
               instance. It will be the **principal** :term:`gaplic`.

        :threads: name of sections that must return :term:`gaplic`
               instances. They will run in threads.

        :subprocesses: name of sections that must return :term:`gaplic`
               instances. They will run in subprocesses.

        :wsgi: name of sections that must return a *app paste factory*.
            Wsgi applications are saved as global apps (set_global_app()).


        Example::

            [composite:main]
            use = call:ginsfsm.gaplic:gaplic_factory
            main = wsgi-server
            wsgi = wsgi-application

            [app:wsgi-server]
            use = call:ginsfsm.examples.wsgi.simple_wsgi_server:main
            host = 0.0.0.0
            port = 8000
            application = wsgi-application
            GSock.trace_dump = true
            GObj.trace_mach = true

            [app:wsgi-application]
            use=call:ginsfsm.examples.wsgi.simple_wsgi_server:paste_app_factory


    The prototype for ``wsgi`` (paste app factory) is::

        def paste_app_factory(global_conf, **local_conf):
            return wsgi-application

    The prototype for ``main``, ``threads`` and ``subprocesses`` is::

        def main(global_conf, **local_config):
            return gaplic-instance

    """
    main = local_conf.get('main')
    wsgis = local_conf.get('wsgi', '').split()
    threads = local_conf.get('threads', '').split()
    subprocesses = local_conf.get('subprocesses', '').split()

    # Firstly create main gaplic, to can pass it to wsgi's
    main_gaplic = loader.get_app(main, global_conf=global_conf)
    set_global_main_gaplic(main_gaplic)

    for thread in threads:
        gaplic = loader.get_app(thread, global_conf=global_conf)
        worker = GAplicThreadWorker(gaplic)
        worker.start()

    for subprocess in subprocesses:
        gaplic = loader.get_app(subprocess, global_conf=global_conf)
        worker = GAplicProcessWorker(gaplic)
        worker.start()

    for wsgi in wsgis:
        app = loader.get_app(wsgi, global_conf=global_conf)
        set_global_app(wsgi, app)

    return main_gaplic
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.