In this post, I will show another way to call scripts or shell commands via Groovy. This time using Java’s ProcessBuilder, using the InputStreamReader to collect returns, but using the Stream, that is, as the script being executed returns prints/logs/messages, etc., it is possible to show these returns in the pipeline, for example.

To simulate this return stream, I will use a very simple python script, it takes a Json as an input parameter and returns prints every 2 seconds.

receive_json.py

import sys
import time
import json

str_Json = str(sys.argv[1])
inputs = json.loads(str_Json.strip("'<>() ").replace('\'', '\"'))
print(time.strftime('%Y-%m-%d %H:%M:%S') + ' - ' + str(inputs))
sys.stdout.flush()
time.sleep(2)
print(time.strftime('%Y-%m-%d %H:%M:%S') + ' - ' + str(inputs['group']))
sys.stdout.flush()
time.sleep(2)
print(time.strftime('%Y-%m-%d %H:%M:%S') + ' - ' + str(inputs['tech']))
sys.stdout.flush()
time.sleep(2)
print(time.strftime('%Y-%m-%d %H:%M:%S') + ' - ' + str(inputs['service']))
sys.stdout.flush()

The Groovy script below creates the process and makes the script call, captures InputStreamReader and prints it every time the python script returns.

def str_Json = '''
{
  "version": 1,
  "group": "infrastructure",
  "tech": "dns",
  "service": "devops-db.info",
  "zones": [
    {
      "host": "ldap",
      "class": "IN",
      "type": "A",
      "destination": "172.21.5.150"
    },
    {
      "host": "registry",
      "class": "IN",
      "type": "A",
      "destination": "172.21.5.151"
    }
  ]
}
'''

// List<String> commands = Arrays.asList("/bin/bash", "-c", "counter=0; until [ \$counter -gt 5 ]; do echo \$(date '+%d/%m/%Y %H:%M:%S'); ((counter++)); sleep 1; done")
List<String> commands = Arrays.asList("python3", "receive_json.py", "'" + str_Json + "'")

try {
    Process process = new java.lang.ProcessBuilder(commands)
        .redirectErrorStream(true)
        .start()

    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}

Return:

2024-05-22 10:20:55 - {'version': 1, 'group': 'infrastructure', 'tech': 'dns', 'service': 'devops-db.info', 'zones': [{'host': 'ldap', 'class': 'IN', 'type': 'A', 'destination': '172.21.5.150'}, {'host': 'registry', 'class': 'IN', 'type': 'A', 'destination': '172.21.5.151'}]}
2024-05-22 10:20:57 - infrastructure
2024-05-22 10:20:59 - dns
2024-05-22 10:21:01 - devops-db.info

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.