splunk-sdk-python icon indicating copy to clipboard operation
splunk-sdk-python copied to clipboard

Custom search command script run in four different processes.

Open matutter opened this issue 10 years ago • 15 comments

I've been writing a custom search command using the GeneratingCommand base. However I've noticed a lot of weird activity because my actual app does some async-things. I've finally determined that every time I run the command it runs the script in 4 separate processes but only returns the results from the last process to be spawned. Running the command in 4 times for 1 use is unexpected behavior and really is causing some issues developing new apps.

splunk --version Splunk 6.5.0 (build 59c8927def0f) uname -a Linux vm 3.10.0-327.36.2.el7.x86_64 #1 SMP Mon Oct 10 23:08:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Below I'll paste a modified version of your sample GenerateTextCommand, anything I'm not including is just directly from this SDK.

generatetext.py

from __future__ import absolute_import, division, print_function, unicode_literals
import app

from console import Console as TTY

from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option, validators
import sys
import time

console = TTY()

@Configuration(streaming=True)
class GenerateTextCommand(GeneratingCommand):

  count = Option(require=True, validate=validators.Integer(0))
  text = Option(require=True)

  def __init__(self):
    console.log('GenerateTextCommand.__init__')
    super(GenerateTextCommand, self).__init__()

  def generate(self):
    text = self.text + console.pid
    console.log('GenerateTextCommand.generate')
    for i in range(1, self.count + 1):
      console.log('GenerateTextCommand.generate[yield]')
      yield {'_serial': i, '_time': time.time(), '_raw': unicode(i) + '. ' + text}

dispatch(GenerateTextCommand, sys.argv, sys.stdin, sys.stdout, __name__)

There is one small custom class I wrote to see the pids and log directly to my terminal's TTY because initially I thought it was a weird artifact with the SDK's use of logging.

import sys, os, datetime

dateFmt = "%l:%M:%S"
logFile = '/dev/pts/2'

class Console:

  def __init__(self):
    self.fd = open(logFile, 'a+')
    self.pid = str(os.getpid())

  def log(self, *argv):
    msg = " ".join([str(p) for p in argv]) +'\n'
    ts = datetime.datetime.now().strftime(dateFmt)
    pid = self.pid
    if self.fd:
      self.fd.write(pid + '|' + ts + ' | ' + msg)

I'm running it with the following shell script

#!/bin/bash
splunk search "| generatetext count=2 text=xxx" -preview true -app searchcommands_app

The output is below, notice all the different PIDS

22218|10:08:50 | GenerateTextCommand.__init__
22218|10:08:50 | GenerateTextCommand.generate
22218|10:08:50 | GenerateTextCommand.generate[yield]
22218|10:08:50 | GenerateTextCommand.generate[yield]
22224|10:08:50 | GenerateTextCommand.__init__
22224|10:08:50 | GenerateTextCommand.generate
22224|10:08:50 | GenerateTextCommand.generate[yield]
22224|10:08:50 | GenerateTextCommand.generate[yield]
22230|10:08:50 | GenerateTextCommand.__init__
22230|10:08:50 | GenerateTextCommand.generate
22230|10:08:50 | GenerateTextCommand.generate[yield]
22230|10:08:50 | GenerateTextCommand.generate[yield]
22243|10:08:50 | GenerateTextCommand.__init__
22243|10:08:50 | GenerateTextCommand.generate
22243|10:08:50 | GenerateTextCommand.generate[yield]
22243|10:08:50 | GenerateTextCommand.generate[yield]
1. xxx22243
2. xxx22243

Is this expected behavior? If so why would Splunk need to run the command 4 times and only output the results of 1.

matutter avatar Nov 01 '16 02:11 matutter

Mat,

Would it be possible for you to send a zipped/tarred copy of your sample app? It will make it easier for me to test a theory I’ve got about this.

Thanks, David Noble Splunk Seattle

On Oct 31, 2016, at 7:16 PM, Mat Utter <[email protected]mailto:[email protected]> wrote:

generatetext.py

from future import absolute_import, division, print_function, unicode_literals import app

from console import Console as TTY

from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option, validators import sys import time

console = TTY()

@Configuration(streaming=True) class GenerateTextCommand(GeneratingCommand):

count = Option(require=True, validate=validators.Integer(0)) text = Option(require=True)

def init(self): console.log('GenerateTextCommand.init') super(GenerateTextCommand, self).init()

def generate(self): text = self.text + console.pid console.log('GenerateTextCommand.generate') for i in range(1, self.count + 1): console.log('GenerateTextCommand.generate[yield]') yield {'_serial': i, '_time': time.time(), '_raw': unicode(i) + '. ' + text}

dispatch(GenerateTextCommand, sys.argv, sys.stdin, sys.stdout, name)

David-Noble-at-work avatar Nov 02 '16 18:11 David-Noble-at-work

Sure, attached is the modified searchcommands_app example. example-app.tar.gz

matutter avatar Nov 03 '16 01:11 matutter

Hi, I was wondering if there's any progress on this / was able to reproduce?

I've noticed that when I invoke the command from Splunk Web the command is run from the "main" Splunkd process once and then 4 times by the same child process. So 5 times from splunk web, and again the CLI search yields 4 processes running the command each spawned from the same Splunkd process which is a child of the "main" splunkd process.

I was poking at this a bit more recently, and found this in the docs ,

With the Version 2 protocol, external programs process through an entire set of Splunk search results in one invocation. The external program is invoked once for the entire search, greatly reducing runtime overhead.

matutter avatar Nov 18 '16 23:11 matutter

I am migrating a custom command from SCP1 to SCP2 and am now facing the exact same issue, I get 4 instances of the script running.

gmichels avatar Dec 22 '16 20:12 gmichels

I am experiencing this issue with a custom generating command using SCP2 on Splunk 6.5.2 and SDK version 1.6.2.

Looking at search.log it looks like Splunk is executing the script multiple times but only returning results from one execution.

This script hits an external API and that call should only happen once per search. Instead the script is being run three times per search.

From search.log:

06-14-2017 11:04:32.604 INFO ChunkedExternProcessor - Running process: /opt/splunk/bin/python /path/to/custom_script.py 06-14-2017 11:04:32.698 INFO ChunkedExternProcessor - Custom search command is a generating command. [...] 06-14-2017 11:04:32.699 INFO ChunkedExternProcessor - Running process: /opt/splunk/bin/python /path/to/custom_script.py 06-14-2017 11:04:32.796 INFO ChunkedExternProcessor - Custom search command is a generating command. [...] 06-14-2017 11:04:32.858 INFO ChunkedExternProcessor - Running process: /opt/splunk/bin/python /path/to/custom_script.py 06-14-2017 11:04:32.952 INFO ChunkedExternProcessor - Custom search command is a generating command.

chrisnestrud avatar Jun 14 '17 16:06 chrisnestrud

Which part of the script is being executed? Note that we may execute the overall Python script several times during initialization at different stages (e.g. as we try to figure out what kind of command it is, etc) - this is what we call the GETINFO portion of the protocol. The log portion you have above seems to indicate that is when it is happening.

Which part of your code is being called multiple times? Is the generate function being invoked each time the script is executed?

itay avatar Jun 14 '17 16:06 itay

@itay if @chrisnestrud is experiencing the same issue as me it is the generate function.

matutter avatar Jun 14 '17 17:06 matutter

The generate function is being called three separate times. This function calls an API to retrieve data and I can see multiple calls. However it looks like only events from one call are returned.

chrisnestrud avatar Jun 14 '17 17:06 chrisnestrud

Same problem. From what I understanding, the chunked command only need one process for communicating with splunk. However, every time I run a custom command, I always found there are 3+ processes created.

liketic avatar Jun 15 '17 08:06 liketic

This commands.conf work for my Reporting command "gcluster".

[gcluster]
filename = gcluster.py
chunked = false
streaming = false
maxinputs = 0
run_in_preview = false
requires_preop= false
enableheader = true 
outputheader = true 
requires_srinfo = true 
supports_getinfo = true 
supports_multivalues = false

nikolaiav avatar Jun 20 '17 21:06 nikolaiav

Gustavo Michels liked your email Spark by Readdle

gmichels avatar Jun 20 '17 21:06 gmichels

Are you in a distributed environment? I unexp[ectitly see the command run on the search head and all indexer peers. See https://github.com/splunk/splunk-sdk-python/issues/155 and https://github.com/splunk/splunk-sdk-python/pull/173

datasearchninja avatar Jun 20 '17 23:06 datasearchninja

I changed commands.conf as suggested by @nikolaiav and the custom command is now only run once. This downgrades from version 2 of the protocol to version 1, so I hope this is a temporary workaround.

chrisnestrud avatar Jun 21 '17 19:06 chrisnestrud

fixed in #181

snickers2029 avatar Feb 23 '18 18:02 snickers2029

Old but I had the same issue, and nikolaiav's solution did not work for me as-is. I fixed it by setting chunked = false and local = true, which runs my command only on the seachhead. Not sure if my issue was exactly the same as what is listed, but wanted to share anyway incase someone else has the same experience.

calvinmcelroy avatar Jul 29 '22 19:07 calvinmcelroy