Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions tests/templates/kuttl/upgrade/04-assert.yaml.j2
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ kind: TestAssert
timeout: 300
commands:
- script: kubectl exec -n $NAMESPACE test-nifi-0 -- python /tmp/test_nifi.py -u admin -p supersecretpassword -n $NAMESPACE -c 3
- script: kubectl exec -n $NAMESPACE test-nifi-0 -- sh -c "python /tmp/flow.py > /tmp/old_input"
# This tests if the output contains an Error or zero flow files are queued, which also indicates that something went wrong
- script: kubectl exec -n $NAMESPACE test-nifi-0 -- sh -c "python /tmp/flow.py run > /tmp/old_input"
# flow.py itself fails on errors. This additionally catches zero (or no) queued flow files, which also indicates that something went wrong
- script: kubectl exec -n $NAMESPACE test-nifi-0 -- sh -c "cat /tmp/old_input | grep -Eov 'Error|\b0\b'"
10 changes: 10 additions & 0 deletions tests/templates/kuttl/upgrade/06-assert.yaml.j2
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ metadata:
status:
readyReplicas: 3
replicas: 3
# `readyReplicas` alone is not sufficient: During a rolling update it returns to 3 after every
# single pod has been replaced, so the assertion would already succeed when just one of the three
# pods runs the new version. `updatedReplicas` counts the pods which were created from the
# StatefulSet's current `updateRevision`. It drops below 3 as soon as the operator patches the
# StatefulSet and only reaches 3 again once every pod runs the new revision.
#
# Both fields are also 3 *before* the rotation starts, so this assertion on its own would still
# succeed against the old version. The sleep in 06-sleep.yaml gives the operator time to patch
# the StatefulSet first and is therefore required.
updatedReplicas: 3
---
apiVersion: nifi.stackable.tech/v1alpha1
kind: NifiCluster
Expand Down
2 changes: 1 addition & 1 deletion tests/templates/kuttl/upgrade/06-sleep.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ kind: TestStep
commands:
# Sleep for a little while to ensure the pod rotation of the NiFi cluster has started. Otherwise,
# the assertion in 06 will immediately succeed because it is run _before_ the pod rotation has
# started.
# started. See the comment on `updatedReplicas` in 06-assert.yaml.j2.
- script: sleep 15
4 changes: 2 additions & 2 deletions tests/templates/kuttl/upgrade/07-assert.yaml.j2
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ metadata:
timeout: 300
commands:
- script: kubectl exec -n $NAMESPACE test-nifi-0 -- python /tmp/test_nifi.py -u admin -p supersecretpassword -n $NAMESPACE -c 3
- script: kubectl exec -n $NAMESPACE test-nifi-0 -- sh -c "python /tmp/flow.py -e https://test-nifi-node-default-0.test-nifi-node-default-headless.$NAMESPACE.svc.cluster.local:8443 query > /tmp/new_input"
# This tests if the output contains an Error or zero flow files are queued, which also indicates that something went wrong
- script: kubectl exec -n $NAMESPACE test-nifi-0 -- sh -c "python /tmp/flow.py query > /tmp/new_input"
# flow.py itself fails on errors. This additionally catches zero (or no) queued flow files, which also indicates that something went wrong
- script: kubectl exec -n $NAMESPACE test-nifi-0 -- sh -c "cat /tmp/new_input | grep -Eov 'Error|\b0\b'"
# This tests that the number of input records stays the same after the upgrade.
- script: kubectl exec -n $NAMESPACE test-nifi-0 -- diff /tmp/old_input /tmp/new_input
117 changes: 79 additions & 38 deletions tests/templates/kuttl/upgrade/flow.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
#!/usr/bin/env python3
# This script is used to create a process group, run it for a couple of seconds, stop it and then
# query the number of queued flow files.
# query the number of queued flow files ("run"), or to just query the number of queued flow files
# of an already existing process group ("query").
#
# The informational output is written to stderr so that stdout only contains the number of queued
# flow files. This way the output of two invocations can be compared with diff.

import argparse
import os
import sys
import time
from dataclasses import dataclass

import nipyapi
import urllib3
from nipyapi.canvas import (
get_root_pg_id,
schedule_process_group,
list_all_controllers,
schedule_controller,
recurse_flow,
schedule_controller,
schedule_process_group,
)
from nipyapi.security import service_login
from nipyapi.nifi.api_client import ApiClient

from typing import Union
from dataclasses import dataclass

import os
import time
import urllib3
from nipyapi.security import service_login

ENDPOINT = f"https://test-nifi-node-default-0.test-nifi-node-default-headless.{os.environ['NAMESPACE']}.svc.cluster.local:8443"
USERNAME = "admin"
Expand All @@ -42,36 +46,56 @@ def schedule(pg_id: str, toggle: bool) -> bool:
return schedule_process_group(pg_id, scheduled=toggle)


def flow_files_queued(connection_name: str) -> Union[str, Error]:
"""Returns the current input record number for the given component"""
flow = recurse_flow()

if flow.process_group_flow.flow.process_groups:
inner_flow = recurse_flow(flow.process_group_flow.flow.process_groups[0].id)
conn = [
conn
for conn in inner_flow.process_group_flow.flow.connections
if conn.status.name == connection_name
]
if conn:
return conn[0].status.aggregate_snapshot.flow_files_queued
else:
return Error(f"No connection named '{connection_name}' found.")
else:
def flow_files_queued(connection_name: str) -> int | Error:
"""Returns the number of queued flow files for the given connection"""
process_groups = recurse_flow().process_group_flow.flow.process_groups

# All flow files must be queued in a single process group, otherwise comparing the counts
# before and after the upgrade is meaningless. More than one process group means that the
# upload ran twice, which happens when kuttl retries the assertion in step 4 after the upload
# already succeeded. Such a run cannot recover, so report it instead of returning the count of
# an arbitrary copy.
if len(process_groups) != 1:
return Error(
f"Expected exactly one process group, found {len(process_groups)}."
)

flow = recurse_flow(process_groups[0].id)
connections = [
conn
for conn in flow.process_group_flow.flow.connections
if conn.status.name == connection_name
]
if not connections:
return Error(f"No connection named '{connection_name}' found.")

return connections[0].status.aggregate_snapshot.flow_files_queued

def main():

def parse_args(args: list[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Set up a flow and query its status.")
subparsers = parser.add_subparsers(dest="subcommand", required=True)
subparsers.add_parser(
"run",
help="Upload the process group, run it for a couple of seconds, stop it and query the number of queued flow files.",
)
subparsers.add_parser(
"query",
help="Query the number of queued flow files of the already uploaded process group.",
)
return parser.parse_args(args)


def login() -> None:
nipyapi.config.nifi_config.host = f"{ENDPOINT}/nifi-api"
nipyapi.config.nifi_config.verify_ssl = False

print(f"Logging in as {USERNAME}")
print(f"Logging in as {USERNAME}", file=sys.stderr)
service_login(username=USERNAME, password=PASSWORD)
print("Logged in")
print("Logged in", file=sys.stderr)

pg_id = get_root_pg_id()
print(f"Got root process group id: {pg_id}")

def upload_process_group(pg_id: str) -> None:
if not nipyapi.config.nifi_config.api_client:
nipyapi.config.nifi_config.api_client = ApiClient()

Expand All @@ -85,7 +109,7 @@ def main():
)
)

print("Uploading process group")
print("Uploading process group", file=sys.stderr)
nipyapi.config.nifi_config.api_client.call_api(
"/process-groups/{pg_id}/process-groups/upload",
"POST",
Expand All @@ -102,13 +126,30 @@ def main():
files={"file": FLOWFILE},
auth_settings=["tokenAuth"],
)
print("Process group uploaded")
print("Process group uploaded", file=sys.stderr)


def main():
args = parse_args(sys.argv[1:])

login()

if args.subcommand == "run":
pg_id = get_root_pg_id()
print(f"Got root process group id: {pg_id}", file=sys.stderr)

upload_process_group(pg_id)

schedule(pg_id, True) # Start the flow
time.sleep(5) # Let the flow run for 5 seconds
schedule(pg_id, False) # Stop the flow

schedule(pg_id, True) # Start the flow
time.sleep(5) # Let the flow run for 5 seconds
schedule(pg_id, False) # Stop the flow
queued = flow_files_queued(CONNECTION_NAME)
if isinstance(queued, Error):
print(queued.message, file=sys.stderr)
sys.exit(1)

print(flow_files_queued(CONNECTION_NAME))
print(queued)


if __name__ == "__main__":
Expand Down