├── LICENSE ├── README.md └── nifi-client-python.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # THIS IS DEPRECATED AND YOU SHOULD DEFINITELY USE https://github.com/Chaffelson/nipyapi 2 | 3 | 4 | # nifi-api-client-python 5 | 6 | **Work in progress, but this can be used** 7 | 8 | This is a simple Python client used to make requests to the NiFi REST API (**1.x**). The goal is to ease the monitoring and management of NiFi throught scripted calls. 9 | 10 | The client support non-secured installation and secured (with login/password) installation. Be aware that, at the moment, there is no certificate check when making requests over SSL. 11 | 12 | Due to problems with the ``requests`` Python module when making requests over SSL, the client is performing calls using the ``curl`` command. 13 | 14 | ## Usage 15 | 16 | ```shell 17 | $ python nifi-client-python.py -h 18 | usage: nifi-client-python.py [-h] [--login LOGIN] [--password PASSWORD] 19 | [--debug] --url URL --action 20 | {list-processors,list-connections,list-input-processors,stop-input-processors,start-input-processors,status,bulletins,cluster,node,disconnect,connect,decommission,remove} 21 | [--node NODE] 22 | 23 | Python client to call NiFi REST API. 24 | 25 | optional arguments: 26 | -h, --help show this help message and exit 27 | --login LOGIN Login to use if NiFi is secured 28 | --password PASSWORD Password to use if NiFi is secured 29 | --debug Enables debug mode 30 | 31 | Required arguments: 32 | --url URL NiFi API endpoint, Ex: http://localhost:8080/nifi-api 33 | --action {list-processors,list-connections,list-input-processors,stop-input-processors,start-input-processors,status,bulletins,cluster,node,disconnect,connect,decommission} 34 | Action to execute 35 | 36 | Arguments for node related actions: 37 | --node NODE Node address to use for the action 38 | ``` 39 | 40 | If debug mode is enabled with ``--debug``, the commands sent to NiFi will be displayed as well as received responses. 41 | 42 | ## Actions 43 | ### List processors 44 | This will return the list of all the processors ID on the canvas (recursively). 45 | ```shell 46 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action list-processors 47 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action list-processors 48 | ``` 49 | 50 | ### List connections 51 | This will return the list of all the connections ID on the canvas (recursively). 52 | ```shell 53 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action list-connections 54 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action list-connections 55 | ``` 56 | 57 | ### List input processors 58 | This will return the list of all the processors ID on the canvas (recursively) considered as **input** processors, meaning processors with no input relationship, in other words processors that are *probably* responsible for getting data into NiFi. 59 | ```shell 60 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action list-input-processors 61 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action list-input-processors 62 | ``` 63 | 64 | ### Stop input processors 65 | This will stop all the input processors listed by the action *list-input-processors* 66 | ```shell 67 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action stop-input-processors 68 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action stop-input-processors 69 | ``` 70 | 71 | ### Start input processors 72 | This will start all the input processors listed by the action *list-input-processors* 73 | ```shell 74 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action start-input-processors 75 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action start-input-processors 76 | ``` 77 | 78 | ### Status 79 | This will display the current status of NiFi based on the following conditions: NiFi is OK if there is no back pressure enabled in any of the connections AND there is no bulletin available. Otherwise, NiFi is considered as NOK (meaning, a manual check could be a good idea). 80 | ```shell 81 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action status 82 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action status 83 | ``` 84 | 85 | ### Bulletins 86 | This will list the bulletins that can be retrieved in the bulletins board though the NiFi UI. 87 | ```shell 88 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action bulletins 89 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action bulletins 90 | ``` 91 | 92 | ### Cluster 93 | This will display a summary status of the NiFi cluster. 94 | ```shell 95 | $ python nifi-client-python.py --url http://localhost:8080/nifi-api --action cluster 96 | $ python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action cluster 97 | d403e2c0-44a7-4c1c-aaa4-fed2ee3d6993 node-1 CONNECTED 3,777 / 0 bytes 98 | 59f7d393-8676-4d40-bf0f-df353c761cdf node-2 CONNECTED 13,000 / 900.68 KB 99 | 26233020-b9ea-41c5-a58a-86026cfac8e4 node-3 CONNECTED 0 / 0 bytes 100 | ``` 101 | 102 | ### Node 103 | This will display a JSON representing the status of the given node. 104 | ```shell 105 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action node --node node-1 106 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action node --node node-1 107 | ``` 108 | 109 | ### Disconnect 110 | This will disconnect the given node from the cluster. 111 | ```shell 112 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action disconnect --node node-1 113 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action disconnect --node node-1 114 | ``` 115 | 116 | ### Connect 117 | This will connect the given node to the cluster. 118 | ```shell 119 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action connect --node node-1 120 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action connect --node node-1 121 | ``` 122 | 123 | ### Decommission 124 | The objective of this command is to disconnect a node, stop the input processors on the disconnected node alone (see above) and wait long enough to have all the queued flow files processed by this node. Once done, this would typically followed by a NiFi shutdown for administration tasks (upgrade, configuration change, custom NAR deployment, etc). If the number of queued flow files is unchanged longer than 60 seconds, the command will stop with a warning message. 125 | ```shell 126 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action decommission --node node-1 127 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action decommission --node node-1 128 | ``` 129 | 130 | ### Remove 131 | This will remove the given node from the cluster. The node needs to be disconnected first. 132 | ```shell 133 | python nifi-client-python.py --url http://localhost:8080/nifi-api --action remove --node node-1 134 | python nifi-client-python.py --url https://localhost:9443/nifi-api --login test --password test --action remove --node node-1 135 | ``` 136 | 137 | ## Contributions 138 | I'm not used to Python and there is a lot of possible improvements. Contributions through pull requests / issues are greatly welcomed. 139 | -------------------------------------------------------------------------------- /nifi-client-python.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python 2 | # 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # 20 | 21 | import json 22 | import argparse 23 | import subprocess 24 | import datetime 25 | import os 26 | import re 27 | import urllib 28 | import time 29 | 30 | _endpoint_pg_root = "/flow/process-groups/root" 31 | _endpoint_pg_id = "/flow/process-groups/" 32 | _endpoint_connection_id = "/connections/" 33 | _endpoint_processor_id = "/processors/" 34 | _endpoint_token = "/access/token" 35 | _endpoint_bulletins = "/flow/bulletin-board" 36 | _endpoint_cluster = "/controller/cluster" 37 | _endpoint_node = "/controller/cluster/nodes/" 38 | _endpoint_flow_status = "/flow/status" 39 | 40 | 41 | def getToken( url ): 42 | endpoint = url + _endpoint_token 43 | data = urllib.urlencode({"username":login, "password":password}) 44 | p = subprocess.Popen("curl -k -X POST " + endpoint + " -H 'application/x-www-form-urlencoded' --data \"" + data + "\"", 45 | shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 46 | out, err = p.communicate() 47 | if p.returncode == 0: 48 | return out 49 | else: 50 | print "Failed to get token" 51 | print err 52 | print out 53 | return None 54 | 55 | 56 | 57 | def execRequest( url, token, type = "GET", data = None): 58 | if( type == "GET" ): 59 | curl = "curl -k " + url + " -H 'Authorization: Bearer " + token + "'" 60 | 61 | elif( type == "POST" ): 62 | if( data is None): 63 | curl = "curl -k -X POST " + url + " -H 'Accept: application/json' -H 'Authorization: Bearer " + token + "'" 64 | else: 65 | curl = "curl -k -X POST " + url + " -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Authorization: Bearer " + token + "' --data '" + data + "'" 66 | 67 | elif( type == "PUT" ): 68 | if( data is None): 69 | curl = "curl -k -X PUT " + url + " -H 'Accept: application/json' -H 'Authorization: Bearer " + token + "'" 70 | else: 71 | curl = "curl -k -X PUT " + url + " -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Authorization: Bearer " + token + "' --data '" + data + "'" 72 | 73 | elif( type == "DELETE" ): 74 | if( data is None): 75 | curl = "curl -k -X DELETE " + url + " -H 'Accept: application/json' -H 'Authorization: Bearer " + token + "'" 76 | else: 77 | curl = "curl -k -X DELETE " + url + " -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Authorization: Bearer " + token + "' --data '" + data + "'" 78 | 79 | else: 80 | print "Type " + type + " not supported" 81 | 82 | if( debug ): 83 | curl = curl + " -v" 84 | print "CURL---------------------------" 85 | print curl 86 | print "CURL---------------------------" 87 | 88 | p = subprocess.Popen(curl, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 89 | out, err = p.communicate() 90 | 91 | if( debug ): 92 | print "OUT---------------------------" 93 | print out 94 | print "OUT---------------------------" 95 | print "ERR---------------------------" 96 | print err 97 | print "ERR---------------------------" 98 | 99 | if p.returncode == 0: 100 | return out 101 | else: 102 | print "Failed to request " + url 103 | print err 104 | print out 105 | return None 106 | 107 | 108 | 109 | def getIds( jData, component ): 110 | ids = [] 111 | for processor in jData['processGroupFlow']['flow'][component]: 112 | ids.append(processor['id']) 113 | return ids 114 | 115 | 116 | 117 | def listIds( url, token, component, parent = None, isRecursive = False ): 118 | endpoint = None 119 | if( parent is None ): 120 | endpoint = _endpoint_pg_root 121 | else: 122 | endpoint = _endpoint_pg_id + parent 123 | 124 | response = execRequest(url + endpoint, token, "GET") 125 | jData = json.loads(response) 126 | ids = getIds(jData, component) 127 | 128 | if( isRecursive ): 129 | pgIds = getIds(jData, "processGroups") 130 | for id in pgIds: 131 | ids.extend(listIds(url, token, component, id, True)) 132 | return ids 133 | else: 134 | return ids 135 | 136 | 137 | 138 | def getProcessorFromConnection( url, token, connectionId, position): 139 | endpoint = _endpoint_connection_id + connectionId 140 | response = execRequest(url + endpoint, token, "GET") 141 | jData = json.loads(response) 142 | 143 | if( position == "source" ): 144 | if ( jData['sourceType'] == "PROCESSOR" ): 145 | return jData['sourceId'] 146 | else: 147 | if ( jData['destinationType'] == "PROCESSOR" ): 148 | return jData['destinationId'] 149 | 150 | 151 | 152 | def listInputProcessorId( url, token, parent = None, isRecursive = False ): 153 | connectionsId = listConnectionsId(url, token, parent, isRecursive) 154 | processorsId = listProcessorsId(url, token, parent, isRecursive) 155 | 156 | for connection in connectionsId: 157 | destinationId = getProcessorFromConnection( url, token, connection, "destination" ) 158 | if(destinationId in processorsId): 159 | processorsId.remove(destinationId) 160 | return processorsId 161 | 162 | 163 | 164 | def listProcessorsId( url, token, parent = None, isRecursive = False ): 165 | return listIds(url, token, "processors", parent, isRecursive) 166 | 167 | 168 | 169 | def listConnectionsId( url, token, parent = None, isRecursive = False ): 170 | return listIds(url, token, "connections", parent, isRecursive) 171 | 172 | 173 | 174 | def updateProcessor( url, token, processorId, action ): 175 | endpoint = _endpoint_processor_id + processorId 176 | response = execRequest(url + endpoint, token, "PUT", json.dumps({"revision":getProcessorRevision(url, token, processorId), "component":{"id":processorId, "state":action}})) 177 | print "Updated processor " + processorId + " to " + action 178 | 179 | 180 | 181 | def updateInputProcessors( url, token, action, parent = None, isRecursive = False ): 182 | processorsId = listInputProcessorId(url, token, parent, isRecursive) 183 | for processor in processorsId: 184 | updateProcessor(url, token, processor, action) 185 | 186 | 187 | 188 | def getProcessorRevision( url, token, processorId ): 189 | endpoint = _endpoint_processor_id + processorId 190 | response = execRequest(url + endpoint, token, "GET") 191 | jData = json.loads(response) 192 | return jData['revision'] 193 | 194 | 195 | 196 | def isBackpressureEnabled( url, token, connectionId ): 197 | endpoint = _endpoint_connection_id + connectionId 198 | response = execRequest(url + endpoint, token, "GET") 199 | jData = json.loads(response) 200 | return jData['status']['aggregateSnapshot']['percentUseCount'] == "100" or jData['status']['aggregateSnapshot']['percentUseBytes'] == "100" 201 | 202 | 203 | 204 | def getPgRootId( url, token ): 205 | response = execRequest(url + _endpoint_pg_root, token, "GET") 206 | jData = json.loads(response) 207 | return jData['processGroupFlow']['id'] 208 | 209 | 210 | 211 | def getBulletins( url, token, processGroupId ): 212 | response = execRequest(url + _endpoint_pg_id + processGroupId, token, "GET") 213 | jData = json.loads(response) 214 | return jData['bulletins'] 215 | 216 | 217 | 218 | def getBulletinsBoard( url, token ): 219 | response = execRequest(url + _endpoint_bulletins + "?after=0", token, "GET") 220 | return json.loads(response) 221 | 222 | 223 | def getNiFiStatus( url, token ): 224 | # check if back pressure is enabled on a connection 225 | connections = listConnectionsId(url, token, None, True) 226 | warning = False 227 | for connectionId in connections: 228 | if( isBackpressureEnabled(url, token, connectionId) ): 229 | print "WARNING: back pressure is enabled on connection " + connectionId 230 | warning = True 231 | 232 | # check if there are bulletins 233 | jData = getBulletinsBoard(url, token) 234 | nbBulletins = len(jData['bulletinBoard']['bulletins']) 235 | if( nbBulletins != 0 ): 236 | warning = True 237 | print "WARNING: there are bulletins, use 'bulletins' command to display bulletins" 238 | 239 | if( warning ): 240 | print "NiFi is NOK" 241 | else: 242 | print "NiFi is OK" 243 | 244 | 245 | 246 | def showBulletins( url, token ): 247 | data = getBulletinsBoard(url, token) 248 | for bulletin in data['bulletinBoard']['bulletins']: 249 | if ( "sourceId" in bulletin.keys() ): 250 | print bulletin['sourceId'] + "\t" + bulletin['timestamp'] + "\t" + bulletin['bulletin']['message'] 251 | else: 252 | print "\t\t\t\t" + bulletin['timestamp'] + "\t" + bulletin['bulletin']['message'] 253 | 254 | 255 | 256 | def showCluster( url, token ): 257 | response = execRequest(url + _endpoint_cluster, token, "GET") 258 | jData = json.loads(response) 259 | for node in jData['cluster']['nodes']: 260 | print node['nodeId'] + "\t" + node['address'] + "\t" + node['status'] + "\t" + node['queued'] 261 | 262 | 263 | 264 | def getNodeId( url, token, nodeAddress ): 265 | response = execRequest(url + _endpoint_cluster, token, "GET") 266 | jData = json.loads(response) 267 | for node in jData['cluster']['nodes']: 268 | if( node['address'] == nodeAddress): 269 | return node['nodeId'] 270 | return None 271 | 272 | 273 | 274 | def showNode( url, token, nodeAddress ): 275 | response = execRequest(url + _endpoint_node + getNodeId(url, token, nodeAddress), token, "GET") 276 | jData = json.loads(response) 277 | print jData 278 | return jData 279 | 280 | 281 | 282 | def disconnect( url, token, nodeAddress ): 283 | nodeId = getNodeId(url, token, nodeAddress) 284 | endpoint = _endpoint_node + nodeId 285 | response = execRequest(url + endpoint, token, "PUT", json.dumps({"node":{"nodeId": nodeId, "status": "DISCONNECTING"}})) 286 | print "Disconnected node " + nodeAddress + " (" + nodeId + ")" 287 | 288 | 289 | 290 | def connect( url, token, nodeAddress ): 291 | nodeId = getNodeId(url, token, nodeAddress) 292 | endpoint = _endpoint_node + nodeId 293 | response = execRequest(url + endpoint, token, "PUT", json.dumps({"node":{"nodeId": nodeId, "status": "CONNECTING"}})) 294 | print "Connected node " + nodeAddress + " (" + nodeId + ")" 295 | 296 | 297 | 298 | def getQueuedFlowFiles( url, token ): 299 | response = execRequest(url + _endpoint_flow_status, token, "GET") 300 | jData = json.loads(response) 301 | return jData['controllerStatus']['flowFilesQueued'] 302 | 303 | 304 | 305 | def decommission( url, token, nodeAddress ): 306 | # check that url is not using the node we want to disconnect 307 | if ( nodeAddress in url ): 308 | print "Please do not use the node to disconnect in the URL" 309 | return 310 | 311 | # disconnecting node to decommission 312 | disconnect(url, token, nodeAddress) 313 | 314 | # get API URL of the node we disconnected 315 | nodeUrl = re.search('.*://(.*):.*', url) 316 | if ( nodeUrl ): 317 | node = nodeUrl.group(1) 318 | urlNode = url.replace(node, nodeAddress) 319 | 320 | # get token on node to disconnect 321 | tokenNode = getToken(urlNode) 322 | 323 | # stop input processors 324 | updateInputProcessors(urlNode, tokenNode, "STOPPED", None, True) 325 | 326 | # wait until not more queued flow file 327 | currentNb = getQueuedFlowFiles(urlNode, tokenNode) 328 | previousNb = 0 329 | idleTime = 0 330 | it = 1 331 | while (currentNb != 0): 332 | time.sleep(it) 333 | previousNb = currentNb 334 | currentNb = getQueuedFlowFiles(urlNode, tokenNode) 335 | print "Current number of queued flow files = " + str(currentNb) 336 | if(currentNb >= previousNb): 337 | idleTime = idleTime + it 338 | else: 339 | idleTime = 0 340 | if(idleTime > 60): 341 | print "WARNING - Number of queued flow files unchanged or increased after 60 seconds - process stopped" 342 | return 343 | print "Node " + nodeAddress + " successfully decommissioned" 344 | return 345 | 346 | 347 | 348 | def removeNode( url, token, nodeAddress ): 349 | nodeId = getNodeId(url, token, nodeAddress) 350 | endpoint = _endpoint_node + nodeId 351 | response = execRequest(url + endpoint, token, "DELETE") 352 | print "Deleted node " + nodeAddress + " (" + nodeId + ")" 353 | 354 | 355 | 356 | 357 | ################################################################################################### 358 | ################################################################################################### 359 | ################################################################################################### 360 | 361 | possibleActions = ["list-processors", "list-connections", "list-input-processors", "stop-input-processors", 362 | "start-input-processors", "status", "bulletins", "cluster", "node", "disconnect", 363 | "connect", "decommission", "remove"] 364 | 365 | parser = argparse.ArgumentParser(description='Python client to call NiFi REST API.') 366 | 367 | parser.add_argument('--login', help='Login to use if NiFi is secured') 368 | parser.add_argument('--password', help='Password to use if NiFi is secured') 369 | parser.add_argument('--debug', help='Enables debug mode', action='store_true') 370 | 371 | requiredNamed = parser.add_argument_group('Required arguments') 372 | requiredNamed.add_argument('--url', help='NiFi API endpoint, Ex: http://localhost:8080/nifi-api', required=True) 373 | requiredNamed.add_argument('--action', choices=possibleActions, help='Action to execute', required=True) 374 | 375 | nodeArgs = parser.add_argument_group('Arguments for node related actions') 376 | nodeArgs.add_argument('--node', help='Node address to use for the action', required=False) 377 | 378 | args = parser.parse_args() 379 | 380 | url = args.url 381 | action = args.action 382 | login = args.login 383 | password = args.password 384 | node = args.node 385 | debug = args.debug 386 | 387 | if( url.startswith('https') ): 388 | token = getToken(url) 389 | 390 | if( action == "list-processors" ): 391 | print listProcessorsId(url, token, None, True) 392 | elif( action == "list-connections" ): 393 | print listConnectionsId(url, token, None, True) 394 | elif( action == "list-input-processors" ): 395 | print listInputProcessorId(url, token, None, True) 396 | elif( action == "stop-input-processors" ): 397 | updateInputProcessors(url, token, "STOPPED", None, True) 398 | elif( action == "start-input-processors" ): 399 | updateInputProcessors(url, token, "RUNNING", None, True) 400 | elif( action == "status" ): 401 | getNiFiStatus(url, token) 402 | elif( action == "bulletins" ): 403 | showBulletins(url, token) 404 | elif( action == "cluster" ): 405 | showCluster(url, token) 406 | elif( action == "node" ): 407 | showNode(url, token, node) 408 | elif( action == "disconnect" ): 409 | disconnect(url, token, node) 410 | elif( action == "connect" ): 411 | connect(url, token, node) 412 | elif( action == "decommission" ): 413 | decommission(url, token, node) 414 | elif( action == "remove" ): 415 | removeNode(url, token, node) 416 | else: 417 | print "ERROR, unknown action " + action 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | --------------------------------------------------------------------------------