Commit Graph

215 Commits (611a2aca9fe273ee8d0cc3701fdfbe04daa8db11)

Author SHA1 Message Date
Victor Julien 46cee88ef8 threads: add management API
Currently management threads do their own thread setup and handling. This
patch introduces a new way of handling management threads.

Functionality that needs to run as a management thread can now register
itself as a regular 'thread module' (TmModule), where the 'Management'
callback is registered.
12 years ago
Ken Steele 28ccea51d3 Add error checking for pthread_setspecific() and pthread_key_create(). 12 years ago
Victor Julien 4fdd1a7a71 Fix compilation on systems that use the fallback SC_ATOMIC_ API. 13 years ago
Victor Julien 86aad660a2 threading setup: fix small mem leak on failure
[src/tm-threads.c:1058]: (error) Memory leak: slot
13 years ago
Victor Julien 7ebd1e6433 Counters: fix delayed-detect counter registration
Make sure we register the detect.alerts counter before packet runtime starts
even in delayed detect mode. The registration of new counters at packet
runtime is not supported by the counters api and might lead to crashes as there
is no proper locking to allow for this operation.

This changes how delayed detect works a bit. Now we call the ThreadInit
callback twice. The first call will only register the counter. The 2nd call
will do all the other setup. This way the counter is registered before the
counters api starts operating in the packet runtime.

Fixes the segv reported in ticket #1018.
13 years ago
Victor Julien 677cd03e52 Counters: more unused code removal 13 years ago
Eric Leblond 7bcacc712a log: change default log level to notice
This patch updates the log level of meaningful start messages to
notice. It also sets the default log level to notice.
13 years ago
Ken Steele 592d48aab7 Use Spin locks on Tile
On Tile, replace pthread_mutex_locks with queued spin locks (ticket
locks) for dataplane processing code. This is safe when running on
dataplane cores with one thread per core. The condition variables are
no-ops when the thread is spinning anyway.

For control plane threads, unix-manager, stats-logs, thread startup,
use pthread_mutex_locks. For these locks replaced SCMutex with SCCtrlMutex
and SCCond with SCCtrlCond.
13 years ago
Victor Julien 8080494e9a counters: consolidate counters after all ThreadInit functions of a thread have run. This prevents duplicate and overwriting memory allocations. 13 years ago
Victor Julien 6d34834623 Runmode fixes and cleanups
Bug #939: thread name buffers are sized inconsistently
These buffers are now all fixed at 16 bytes.

Bug #914: Having a high number of pickup queues (216+) makes suricata crash
Fixed so that we can now have 256 pickup queues, which is the current built-in
maximum. Improved the error reporting.

Bug #928: Max number of threads
Error reporting improved. Issue was the same as #914.
13 years ago
Ken Steele 5532af4621 Create SCMUTEX_INITIALIZER to abstract out PTHREAD_MUTEX_INITIALIZER
This allows replacing pthread mutexes with other types of mutex.
13 years ago
Victor Julien 1373a20e8a Thread: remove thread id 14 years ago
Victor Julien 46af6b7e0f Add a per threadvars thread local thread id, that starts at 0 and increments for each thread. 14 years ago
Anoop Saldanha 34a9c047fc updated to fix unix shutdown sequence
Should fix crashes occuring from unix mode shutdown/cleanup phase.
14 years ago
Victor Julien 34d063adea Fix double definition of CPU_* macro's for Darwin/OSX. Bug 701. 14 years ago
Eric Leblond 20a8b9dbe5 unix-manager: add unix command socket and associated script
This patch introduces a unix command socket. JSON formatted messages
can be exchanged between suricata and a program connecting to a
dedicated socket.
The protocol is the following:
 * Client connects to the socket
 * It sends a version message: { "version": "$VERSION_ID" }
 * Server answers with { "return": "OK|NOK" }
If server returns OK, the client is now allowed to send command.

The format of command is the following:
 {
   "command": "pcap-file",
   "arguments": { "filename": "smtp-clean.pcap", "output-dir": "/tmp/out" }
 }
The server will try to execute the "command" specified with the
(optional) provided "arguments".
The answer by server is the following:
 {
   "return": "OK|NOK",
   "message": JSON_OBJECT or information string
 }

A simple script is provided and is available under scripts/suricatasc. It
is not intended to be enterprise-grade tool but it is more a proof of
concept/example code.  The first command line argument of suricatasc is
used to specify the socket to connect to.

Configuration of the feature is made in the YAML under the 'unix-command'
section:
  unix-command:
    enabled: yes
    filename: custom.socket
The path specified in 'filename' is not absolute and is relative to the
state directory.

A new running mode called 'unix-socket' is also added.
When starting in this mode, only a unix socket manager
is started. When it receives a 'pcap-file' command, the manager
start a 'pcap-file' running mode which does not really leave at
the end of file but simply exit. The manager is then able to start
a new running mode with a new file.

To start this mode, Suricata must be started with the --unix-socket
 option which has an optional argument which fix the file name of the
socket. The path is not absolute and is relative to the state directory.

THe 'pcap-file' command adds a file to the list of files to treat.
For each pcap file, a pcap file running mode is started and the output
directory is changed to what specified in the command. The running
mode specified in the 'runmode' YAML setting is used to select which
running mode must be use for the pcap file treatment.

This requires modification in suricata.c file where initialisation code
is now conditional to the fact 'unix-socket' mode is not used.

Two other commands exists to get info on the remaining tasks:
 * pcap-file-number: return the number of files in the waiting queue
 * pcap-file-list: return the list of waiting files
'pcap-file-list' returns a structured object as message. The
structure is the following:
 {
  'count': 2,
  'files': ['file1.pcap', 'file2.pcap']
 }
14 years ago
Eric Leblond 6be63bdc4f tm-threads: add TM_ECODE_DONE state
This patch adds a nex return state which can be used by threads
to warn that a task has been done. In this case, suricata does not
leave.
14 years ago
Eric Leblond 28b4bed141 tm-threads: fix potential access to NULL pointer. 14 years ago
Last G 8ae11f73b2 Added parentheses to fix Eclipse static code analysis
Fixed bug in action priority (REJECT_DST had lowest prio)
14 years ago
Victor Julien 9140aa6ac5 cygwin supports the thread cpu affinity code now 14 years ago
Victor Julien 84bad6db77 Silence compiler warnings found by clang 14 years ago
Victor Julien 472e061c6d build: more checking for includes 14 years ago
Eric Leblond ffbbff9d6c tm-thread: detect thread death
When a thread is dead at init the THV_INIT_DONE flag is not set
and the spawn function can freeze (see bug #553 for an example).
In this case THV_RUNNING_DONE is set and we can also check on this
state for leaving the function. This should fix #bug553
14 years ago
Eric Leblond e176be6fcc Use unlikely for error treatment.
When handling error case on SCMallog, SCCalloc or SCStrdup
we are in an unlikely case. This patch adds the unlikely()
expression to indicate this to gcc.

This patch has been obtained via coccinelle. The transformation
is the following:

@istested@
identifier x;
statement S1;
identifier func =~ "(SCMalloc|SCStrdup|SCCalloc)";
@@

x = func(...)
... when != x
- if (x == NULL) S1
+ if (unlikely(x == NULL)) S1
14 years ago
Eric Leblond d51dd6a30e Fix warning about unused return of SC_ATOMIC func. 14 years ago
Eric Leblond a7afa845a6 Fix coverity warnings 718636 and 718635
The result of the swap was not checked.
14 years ago
Eric Leblond 073b251df7 affinity: drop capability after setting thread prio
Setting thread priority can require privilege if a low nice value
has to be set up.
14 years ago
Eric Leblond efc3faaa0a affinity: add log message 14 years ago
Eric Leblond 16bdcbeb0e tm-thread: suppress rarely used variable. 14 years ago
Eric Leblond 7e09cdc265 Delay Detect threads initialization
This patch modifies the init of Detect threads. They are now started
with a dummy function and their initialisation is done after the
signatures are loaded. Just after this, the dummy function is switched
to normal one.

In IPS mode, this permit to route packets without waiting for the
signature to start and should fix #488.

Offline mode such as pcap file don't use this mode to be sure to
analyse all packets in the file.

The patch introduces a "delayed-detect" configuration variable
under detect-engine. It can be used to activate the feature
(set to "yes" to have signature loaded after capture is started).
14 years ago
Anoop Saldanha 5f198e3a1d Suricata shutdown updates + minor cleanup 14 years ago
Eric Leblond 452d3c4308 tm-thread: exit loop if suri want to quit 14 years ago
Eric Leblond f389a1201f tm-thread: run thread init function sequentially.
On some setup you want to run each thread init function sequentially.
For example, if I use flow_cpu load balancing on AF_PACKET, my target
is to have CPU 0 (first socket in the group) to be link with the
thread 0 in detect cpu set (first thread to be initialised). A good
way to achieve this is to run only one thread init function at a time
to avoid any possible race condition.
14 years ago
Anoop Saldanha 34f0897163 check if all packets are processed before disabling detect threads + kill all threads <= detect after FFR + other minor fixes 15 years ago
Anoop Saldanha ba5f757c47 sc_atomic_cas replaced with sc_atomic_set 15 years ago
Eric Leblond 0227a87fcb cleaning: fix warning when building with clang.
clang was issuing some warnings related to unused return in function.
This patch adds some needed error treatment and ignore the rest of the
warnings by adding a cast to void.
15 years ago
Anoop Saldanha 2bc7d0792d update clean up of old detection engine contexts for live rule swap 15 years ago
Anoop Saldanha 31eb5fa2f6 Introduce util-signal.[ch]. Move our signal setup functions here 15 years ago
Anoop Saldanha ecad4a24fa live rule support added
To reload ruleset during engine runtime, send the USR2 signal to the engine, and the ruleset would be reloaded from the same yaml file supplied at engine startup
15 years ago
Anoop Saldanha 5e02cb2365 slot_data updated as an atomic var no 15 years ago
Anoop Saldanha 081b0e05a2 restructure disabling receive threads. Introduce new flag to indicate that threads have finised running 15 years ago
Anoop Saldanha fea6a426a5 cleanup killing threads. As a consequence fixes invalid read/writes in tmqh flow 15 years ago
Anoop Saldanha 5ffb050ada Adapt flow tmqh counters to be atomic vars. Remove support for active flows q handler. Introduce SC_ATOMIC_SET 15 years ago
Victor Julien d908e707d7 profiling: add per lock location profiling
Add profiling per lock location in the code. Accounts how often a
lock is requested, how often it was contended, the max number of
ticks spent waiting for it, avg number of ticks waiting for it and
the total ticks for that location.

Added a new configure flag --enable-profiling-locks to enable this
feature.
15 years ago
Victor Julien 979edf0b97 Add way to profile mutex/spin locks per thread module. 15 years ago
Victor Julien d72b82fae0 Misc fixes. 15 years ago
Victor Julien e237841a8e Fix compilation with profiling enabled. Minor unittest fixes. 15 years ago
Victor Julien 372ab9c433 Another batch of minor fixed for issues found by Coverity. 15 years ago
Victor Julien 11bdf4838f Various improvements to error handling found by Coverity. 15 years ago
Victor Julien cdba2f50d1 Various fixes and improvements based on feedback by Coverity analyzer. 15 years ago
Victor Julien cd987ae7a5 Threading: do not keep a slots post_pq locked while processing the packets. 15 years ago
Anoop Saldanha 420befb180 Changed my email address to anoopsaldanha at gmail dot com from my current one 15 years ago
Eric Leblond 5cec22ac37 threads: Add sanity check. 15 years ago
Victor Julien 1be65e7b68 Fixes for building in Cygwin. 15 years ago
Victor Julien 404868c28b Get rid of strcasestr call as win32 doesn't have it. 15 years ago
Anoop Saldanha d23e775ae2 fix threading bug. Main thread's restart TV code waiting on a failed TV. Now main thread sets the de_init flag before waiting on the failed thread. Thanks to Eric Leblond for reporting it 15 years ago
Anoop Saldanha d68f182ebd introduce SCPerfSyncCounters/SCPerfSyncCounters macro to synchronize counters 15 years ago
pilcrow ed69eeab14 Safer macro parenthesization and do/while use 15 years ago
Victor Julien 1ab6443e44 Fix compilation when profiling is enabled. 15 years ago
Anoop Saldanha 7c729d2d53 some more code cleanup + comments added 15 years ago
Anoop Saldanha 3f1c4efceb Add new flags var to tm module. TMs can now set flags to identify special properties. Also use these to identify receive TMs 15 years ago
Anoop Saldanha 54f6e4ff4d Merge thread kill functions. Merge slot's tm_id with the one used by packet profiling. Remove some junk unused code from ms sync pts. Timeout setup cleanup as well. packet q dbg_maxlen now u32 var. 15 years ago
Anoop Saldanha 6c95526423 Introduce a new wrapper macro that wait loops till the flag(s) in question have been set 15 years ago
Anoop Saldanha a7acf9ea8f Remove all code introduced earlier concerned with ms sync points 15 years ago
Anoop Saldanha b0a588beeb Introduce another solution to solve stream timeout shutdown issue using thread flags. No more MSSyncPts 15 years ago
Anoop Saldanha f2bcf9ea2c modify post_pq packet handling.
- Lock the q just once, once we have detected the presence of packet(s)
  in the queue.  Unlock it when we consume all packets from the q.
15 years ago
Anoop Saldanha 9256c7bf0a always keep queue locked till we exit flowprune. Should prevent potential threading issues 15 years ago
Anoop Saldanha a559bfc165 signal the post pq if possible, whenever pseudo packets are injected into engine flow. Also carry out post pq processing irrespective of packet retrieval from the flow. 15 years ago
Anoop Saldanha 8363533a02 support for forced stream reassembly for to be pruned flows 15 years ago
Anoop Saldanha 15359dc47e Slot structure now holds the TV it belongs to 15 years ago
Anoop Saldanha c365bafbf6 We now inspect timed out streams + streams not processed as yet, at engine shutdown 15 years ago
Anoop Saldanha 56432cee16 Single thread kill also checks if inq is cleared before shutting down 15 years ago
Anoop Saldanha 8fa923c5ac - All threads also check to see if their inq is cleared before they shutdown. 15 years ago
Anoop Saldanha a844eecb0e - Updated all runmodes to use synchronization points, right before each thread(slot function) tries to de-init the thread. - Main thread now first disables receive thread(s) before it kills receive and rest of the threads. 15 years ago
Anoop Saldanha e567c2d002 Introduce master-slave synchronization support for ThreadVars 15 years ago
Anoop Saldanha 94c5ecb069 introduce inline function version of TmThreadsSlotProcessPkt macro. Retain the macro as well 15 years ago
Anoop Saldanha 3fb65f5ec2 fix local var usage for slot in tm-threads.c 15 years ago
Anoop Saldanha acbcee69ff support post pq packet processing in var slot 15 years ago
Victor Julien baddfcaa1a Extend packet profiling to other thread 'slot' functions. 15 years ago
Victor Julien 820b0ded82 Add per packet profiling.
Per packet profiling uses tick based accounting. It has 2 outputs, a summary
and a csv file that contains per packet stats.

Stats per packet include:
 1) total ticks spent
 2) ticks spent per individual thread module
 3) "threading overhead" which is simply calculated by subtracting (2) of (1).

A number of changes were made to integrate the new code in a clean way:
a number of generic enums are now placed in tm-threads-common.h so we can
include them from any part of the engine.

Code depends on --enable-profiling just like the rule profiling code.

New yaml parameters:

profiling:
  # packet profiling
  packets:

    # Profiling can be disabled here, but it will still have a
    # performance impact if compiled in.
    enabled: yes
    filename: packet_stats.log
    append: yes

    # per packet csv output
    csv:

      # Output can be disabled here, but it will still have a
      # performance impact if compiled in.
      enabled: no
      filename: packet_stats.csv

Example output of summary stats:

IP ver   Proto   cnt        min      max          avg
------   -----   ------     ------   ----------   -------
 IPv4       6     19436      11448      5404365     32993
 IPv4     256         4      11511        49968     30575

Per Thread module stats:

Thread Module              IP ver   Proto   cnt        min      max          avg
------------------------   ------   -----   ------     ------   ----------   -------
TMM_DECODEPCAPFILE          IPv4       6     19434       1242        47889      1770
TMM_DETECT                  IPv4       6     19436       1107       137241      1504
TMM_ALERTFASTLOG            IPv4       6     19436         90         1323       155
TMM_ALERTUNIFIED2ALERT      IPv4       6     19436        108         1359       138
TMM_ALERTDEBUGLOG           IPv4       6     19436         90         1134       154
TMM_LOGHTTPLOG              IPv4       6     19436        414      5392089      7944
TMM_STREAMTCP               IPv4       6     19434        828      1299159     19438

The proto 256 is a counter for handling of pseudo/tunnel packets.

Example output of csv:

pcap_cnt,ipver,ipproto,total,TMM_DECODENFQ,TMM_VERDICTNFQ,TMM_RECEIVENFQ,TMM_RECEIVEPCAP,TMM_RECEIVEPCAPFILE,TMM_DECODEPCAP,TMM_DECODEPCAPFILE,TMM_RECEIVEPFRING,TMM_DECODEPFRING,TMM_DETECT,TMM_ALERTFASTLOG,TMM_ALERTFASTLOG4,TMM_ALERTFASTLOG6,TMM_ALERTUNIFIEDLOG,TMM_ALERTUNIFIEDALERT,TMM_ALERTUNIFIED2ALERT,TMM_ALERTPRELUDE,TMM_ALERTDEBUGLOG,TMM_ALERTSYSLOG,TMM_LOGDROPLOG,TMM_ALERTSYSLOG4,TMM_ALERTSYSLOG6,TMM_RESPONDREJECT,TMM_LOGHTTPLOG,TMM_LOGHTTPLOG4,TMM_LOGHTTPLOG6,TMM_PCAPLOG,TMM_STREAMTCP,TMM_DECODEIPFW,TMM_VERDICTIPFW,TMM_RECEIVEIPFW,TMM_RECEIVEERFFILE,TMM_DECODEERFFILE,TMM_RECEIVEERFDAG,TMM_DECODEERFDAG,threading
1,4,6,172008,0,0,0,0,0,0,47889,0,0,48582,1323,0,0,0,0,1359,0,1134,0,0,0,0,0,8028,0,0,0,49356,0,0,0,0,0,0,0,14337

First line of the file contains labels.

2 example gnuplot scripts added to plot the data.
15 years ago
Eric Leblond a8b21066df tm-thread: fix documentation string 15 years ago
Victor Julien 7e1d911215 Small optimizations to pkt acq loop code. 15 years ago
Victor Julien b753ecce50 Implement a pkt acq loop infra with support for pcap-file. 15 years ago
Anoop Saldanha ff7284e7b7 Fix code that allows the engine to restart threads that have exited on failure 15 years ago
Anoop Saldanha 524af82b1a code cleanup in tm-threads.c 15 years ago
Anoop Saldanha 4f7df1029d Unify the use of slots to a single struct for threading API. Remove separate slot append functions for 1slot and varslot 15 years ago
Gerardo Iglesias Galvan f545df3ea7 Fix potential issue in TmThreadsSlot1NoIn 16 years ago
Victor Julien 92ea1f68d4 Exit on thread restart limit reached. 16 years ago
Eric Leblond 4e9231266a Compilation fix for OpenBSD and win32.
This patch fixes compilation on OpenBSD platform. It is running
fine on a pcap file. The patch should also fix compilation on
WIN32 platform but this is not tested.
16 years ago
Pablo Rincon 35c168ab03 Fix CPU_* macros for Mac OS X 16 years ago
Eric Leblond f9e453e14c affinity: Use configured 'threads' value if set
This patch modifies runmodes to make them use the new 'threads'
variable.

Signed-off-by: Eric Leblond <eric@regit.org>
16 years ago
Eric Leblond 789d46cc3c Add per-cpu prio handling
This patch updates affinity setting to add a support for per cpu
priority setting. In exclusive mode a thread is dedicated to a CPU.
This patch adds the ability to set the thread prio for all threads
of a family running on a given CPU.

With this patch we can write
    - detect_cpu_set:
        cpu: [ "all" ]
        mode: "exclusive" # run detect threads in these cpus
        low_prio: [ 0 ]
        medium_prio: [ "1-2" ]
        high_prio: [ 3 ]
With this configuration, detect threads assigned to cpu 0 will
have a low priority. Detect threads on cpus 1 and 2 will have
prio medium...

The previous configuration is equivalent to:
    - detect_cpu_set:
        cpu: [ "all" ]
        mode: "exclusive" # run detect threads in these cpus
        low_prio: [ 0 ]
        high_prio: [ 3 ]
        prio: "medium"
because the prio value is used a default.

Signed-off-by: Eric Leblond <eric@regit.org>
16 years ago
Eric Leblond ea566d6601 Handle management thread with corresponding affinity
This patch implement the setting of each management threads in
the corresponding thread affinity. This is done by modifiying
thread creation function.

Signed-off-by: Eric Leblond <eric@regit.org>
16 years ago
Eric Leblond 0809deafc4 Implement function needed for affinity in tm-threads
This patch features the implementation of affinity related
changes in tm-threads. In place code has been used but some
refactoring has been done to avoid code duplication.

Signed-off-by: Eric Leblond <eric@regit.org>
16 years ago
Victor Julien bfb6aac495 Sleep after checking for a thread flag in TmThreadWaitOnThreadInit now that the check is so much cheaper. 16 years ago
Victor Julien 9634389b9e Fix TmThreadsUnsetFlag not unsetting flag if __sync_fetch_and_nand was used. 16 years ago
Pablo Rincon fcff1ce7f4 Converting threadvar flags to atomic vars to avoid using the old spinlock 16 years ago
Anoop Saldanha 33f4beb0bc batching of packets support for cuda b2g mpm. Supported for both 32 and 64 bit platforms 17 years ago
Victor Julien 1d74797b17 Attempt to work around NULL packets we're seeing ending up in queues when the compiler has optimized our code. 17 years ago
Victor Julien 37eb2290b0 Add some checks for 'impossible' conditions that become possible after enabling optimizations :-/ 17 years ago