def deletesetting(self): section_name = self.leServer.currentText() self.parser.remove_section(section_name) with open(self.inifile, 'w') as configfile: self.parser.write(configfile) self.refresh() MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry removed!", \ "Server: {section} removed from File: {file} sucessfully.".format(section=section_name, file=self.inifile))
def get_data(session, url, user, userPass, certificateName): print("{nl}URL: {url}{nl1}".format(nl=os.linesep, url=url, nl1=os.linesep)) isSecureURL = True #print(url, user, userPass, certificateName) try: if len(certificateName.strip()) == 0: isSecureURL = False retry = Retry(connect=3, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) else: session.mount('https://', ForcedIPHTTPSAdapter()) headers = { 'content-type': 'application/x-www-form-urlencoded,application/json,text/html', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive' } if isSecureURL: response = session.get(url, auth=(user, userPass), headers=headers, timeout=5, verify=certificateName) else: response = session.get(url, auth=(user, userPass), headers=headers, timeout=5, verify=False) response.raise_for_status() items = response.json() response = {} return items except Exception as e: MessageBox.message(QMessageBox.Critical, "RabbitMQ REST Connection - Error", "REST API Error", "Unable to retreive data: {}".format(str(e))) return {}
def accept(self): fileName = self.leFileName.text() if len(fileName) > 0: with open(fileName, 'w') as json_file: #json_file.write(self.messages) json_file.write(self.leexportedMessages.toPlainText()) MessageBox.message( QMessageBox.Information, "RabbitMQ Export Message(s)", "Message(s) Exported!", "Message(s) exported to {file} sucessfully.".format( file=fileName)) self.closewin()
def connect(self, parent, commandUrl, userName, userPass, certName, vhost, connectionName=''): credentials = pika.PlainCredentials(username=userName, password=userPass) _commandUrl = commandUrl.split(":") #print(commandUrl) serverCN = _commandUrl[1].replace("//", "") commandPort = _commandUrl[2] ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) #ssl_context.verify_mode = ssl.CERT_REQUIRED ssl_context.load_verify_locations(certName) ssl_options = pika.SSLOptions(context=ssl_context, server_hostname=serverCN) parameters = pika.ConnectionParameters(host=serverCN, port=commandPort, virtual_host=vhost, connection_attempts=5, retry_delay=5, credentials=credentials, heartbeat=580, blocked_connection_timeout=600, ssl_options=ssl_options, client_properties={ 'connection_name': connectionName, }) try: return pika.BlockingConnection(parameters) except Exception as e: print(str(e)) MessageBox.message( QMessageBox.Critical, "RabbitMQ AMQP Connection - Error", "AMQP Error", "Unable to connect to RabbitMQ: {}".format(str(e))) return None
def accept(self): webUrl = self.leUrl.text().strip() commandUrl = self.le1Url.text().strip() user = self.leUserId.text().strip() userPass = self.lePassword.text().strip() vHost = self.leVhost.text().strip() certName = self.leCertificateName.text().strip() certPass = self.leCertificatePassword.text().strip() protocol = True if "https" in webUrl else False msg = "Please enter:{nl}Web Url{nl}Amqp Url{nl}User Id{nl}Password{nl}Passkey File and {nl}VHost.{nl}{nl}In case of https, please provide Certificate details.{nl}{nl}" \ "Please click update setting, before clicking Ok button.".format(nl=os.linesep) if webUrl and commandUrl and user and userPass and vHost: print(protocol, certName) if protocol and len(certName) != 0: self._webUrl.emit(webUrl) self._commandUrl.emit(commandUrl) self._userId.emit(user) self._password.emit(self.passKeyFile, userPass) self._vhost.emit(vHost) self._certName.emit(certName) self._certPass.emit(certPass) self._cancelled.emit(False) self.closewin() else: MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry issue!", msg) self._cancelled.emit(True) else: MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry issue!", msg) self._cancelled.emit(True)
def post_data(session, url, user, userPass, certificateName, body): print("{nl}URL: {url}{nl1}".format(nl=os.linesep, url=url, nl1=os.linesep)) isSecureURL = True try: if len(certificateName.strip()) == 0: isSecureURL = False retry = Retry(connect=3, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) else: session.mount('https://', ForcedIPHTTPSAdapter()) if isSecureURL: response = session.post(url, auth=(user, userPass), verify=certificateName, json=body) else: response = session.post(url, auth=(user, userPass), verify=False, json=body) response.raise_for_status() items = response.json() response = {} return items except Exception as e: MessageBox.message(QMessageBox.Critical, "RabbitMQ REST Connection - Error", "REST API Error", "Unable to retreive data: {}".format(str(e))) return {}
def buttonClicked(self): button = self.sender() #print(button.objectName()) if not button: return buttonObjectName = button.objectName() exTableModel = self.exargstablemodelview.model() qTableModel = self.qargstablemodelview.model() bindingTableModel = self.bindingargstablemodelview.model() if buttonObjectName == "addExArgsKey": data = [[]] self.addRow(exTableModel, data) self.exchangeadd = True elif buttonObjectName == "delExArgsKey": del exTableModel.arraydata[self.tableSelectedRow] exTableModel.changeData(exTableModel.arraydata) self.exArgsDelButton.setEnabled(False) elif buttonObjectName == "addQArgsKey": data1 = [[]] self.addRow(qTableModel, data1) self.queueadd = True elif buttonObjectName == "delQArgsKey": del qTableModel.arraydata[self.tableSelectedRow] qTableModel.changeData(qTableModel.arraydata) self.qArgsDelButton.setEnabled(False) elif buttonObjectName == "addBindArgsKey": data2 = [[]] self.addRow(bindingTableModel, data2) self.bindadd = True elif buttonObjectName == "delBindArgsKey": del bindingTableModel.arraydata[self.tableSelectedRow] bindingTableModel.changeData(bindingTableModel.arraydata) self.bindingArgsDelButton.setEnabled(False) elif buttonObjectName == "addExchange": #exchange_declare(exchange, exchange_type='direct', passive=False, durable=False, auto_delete=False, internal=False, arguments=None, callback=None) exchange = self.exName.text() exchange_type = str(self.exType.currentText()) durable = True if str( self.durability.currentText()) == "Durable" else False auto_delete = False if str( self.autoDelete.currentText()) == "No" else True internal = False if str( self.internal.currentText()) == "No" else True exTableModel.removeRowsWithEmptyColumns() arguments = dict(exTableModel.arraydata) if arguments == {}: arguments = None #print(exchange, exchange_type, durable, auto_delete, internal, arguments) try: channel = self.eqbConnection.channel() channel.exchange_declare(exchange=exchange, exchange_type=exchange_type, durable=durable, auto_delete=auto_delete, internal=internal, arguments=arguments) if channel.is_open: channel.close() MessageBox.message( QMessageBox.Information, "RabbitMQ Exchange", "Exchange Created!", "{exch} has been created.".format(exch=exchange)) self.elist = RestFunctions.exchange_list( RestFunctions, self, self.sessionAvailable, self.session, self._webUrl, self._userId, self._password, self._certName) for item in self.elist: name = item["name"] if len(name) == 0 or name.find( self._userId.lower().replace("_", "")) > -1: if (len(name) != 0): self.source.addItem(str(name)) self._refresh.emit(True) except Exception as e: error = str(e).strip().replace("(", "").replace(")", "").split(",") textandinfo = error[1].replace("\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace("\"", "").strip( ) + ". Check Queue naming policy with your administrator." MessageBox.message( QMessageBox.Critical, "RabbitMQ Exchange Creation - Error ({})".format(error[0]), text, infoText) elif buttonObjectName == "delExchange": #exchange_delete(exchange=None, if_unused=False, callback=None) try: channel = self.eqbConnection.channel() exchange = self.exName.text() exch_exist = channel.exchange_declare(exchange=exchange, passive=True) if exch_exist: channel.exchange_delete(exchange=exchange) MessageBox.message( QMessageBox.Information, "RabbitMQ Exchange", "Exchange Deleted!", "{exch} has been deleted.".format(exch=exchange)) self.elist = RestFunctions.exchange_list( RestFunctions, self, self.sessionAvailable, self.session, self._webUrl, self._userId, self._password, self._certName) for item in self.elist: name = item["name"] if len(name) == 0 or name.find( self._userId.lower().replace("_", "")) > -1: if (len(name) != 0): self.source.addItem(str(name)) self._refresh.emit(True) if channel.is_open: channel.close() except Exception as e: error = str(e).strip().replace("(", "").replace(")", "").split(",") textandinfo = error[1].replace("\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace("\"", "").strip() MessageBox.message( QMessageBox.Critical, "RabbitMQ Exchange Deletion - Error ({})".format(error[0]), text, infoText) elif buttonObjectName == "addQueue": queue = self.qName.text() durable = True if str( self.qDurability.currentText()) == "Durable" else False auto_delete = False if str( self.qAutoDelete.currentText()) == "No" else True qTableModel.removeRowsWithEmptyColumns() arguments = dict(qTableModel.arraydata) if arguments == {}: arguments = None try: channel = self.eqbConnection.channel() channel.queue_declare(queue=queue, durable=durable, auto_delete=auto_delete, arguments=arguments) if channel.is_open: channel.close() MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Queue Created!", "{que} has been added.".format(que=queue)) self.qlist = RestFunctions.queue_list( RestFunctions, self, self.sessionAvailable, self.session, self._webUrl, self._userId, self._password, self._certName) for item in self.qlist: name = item["name"] if len(name) == 0 or name.find( self._userId.lower().replace("_", "")) > -1: if (len(name) != 0): self.target.addItem(str(name)) self._refresh.emit(True) except Exception as e: error = str(e).strip().replace("(", "").replace(")", "").split(",") textandinfo = error[1].replace("\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace("\"", "").strip( ) + ". Check Queue naming policy with your administrator." MessageBox.message( QMessageBox.Critical, "RabbitMQ Queue Creation - Error ({})".format(error[0]), text, infoText) elif buttonObjectName == "delQueue": try: channel = self.eqbConnection.channel() queue = self.qName.text() queue_exist = channel.queue_declare(queue=queue, passive=True) if queue_exist: channel.queue_delete(queue=queue) MessageBox.message( QMessageBox.Information, "RabbitMQ Queue", "Queue Deleted!", "{que} has been deleted.".format(que=queue)) self.qlist = RestFunctions.queue_list( RestFunctions, self, self.sessionAvailable, self.session, self._webUrl, self._userId, self._password, self._certName) for item in self.qlist: name = item["name"] if len(name) == 0 or name.find( self._userId.lower().replace("_", "")) > -1: if (len(name) != 0): self.target.addItem(str(name)) self._refresh.emit(True) if channel.is_open: channel.close() except Exception as e: error = str(e).strip().replace("(", "").replace(")", "").split(",") textandinfo = error[1].replace("\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace("\"", "").strip() MessageBox.message( QMessageBox.Critical, "RabbitMQ Queue Deletion - Error ({})".format(error[0]), text, infoText) self._refresh.emit(True) elif buttonObjectName == "purgeQueue": try: channel = self.eqbConnection.channel() queue = self.qName.text() queue_exist = channel.queue_declare(queue=queue, passive=True) if queue_exist: channel.queue_purge(queue=queue) MessageBox.message( QMessageBox.Information, "RabbitMQ Queue", "Queue Purged!", "{que} has been purged.".format(que=queue)) self._refresh.emit(True) if channel.is_open: channel.close() except Exception as e: error = str(e).strip().replace("(", "").replace(")", "").split(",") textandinfo = error[1].replace("\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace("\"", "").strip() MessageBox.message( QMessageBox.Critical, "RabbitMQ Queue Purge - Error ({})".format(error[0]), text, infoText) elif buttonObjectName == "addBind": destination = self.target.currentText() source = self.source.currentText() routing_key = self.rkey.text() bindingTableModel.removeRowsWithEmptyColumns() arguments = dict(bindingTableModel.arraydata) if arguments == {}: arguments = None if self.exchange2exchange.isChecked(): if len(routing_key) == 0: routing_key = '' channel = self.eqbConnection.channel() channel.exchange_bind(destination=destination, source=source, routing_key=routing_key, arguments=arguments) MessageBox.message( QMessageBox.Information, "RabbitMQ Binding", "Exchange to Exchange Binding!", "Binding created between Exchange:{exch1} and Exchange:{exch2}." .format(exch1=destination, exch2=source)) self._refresh.emit(True) if channel.is_open: channel.close() elif self.exchange2queue.isChecked(): if len(routing_key) == 0: routing_key = None channel = self.eqbConnection.channel() channel.queue_bind(queue=destination, exchange=source, routing_key=routing_key, arguments=arguments) MessageBox.message( QMessageBox.Information, "RabbitMQ Binding", "Queue to Exchange Binding!", "Binding created between Queue:{que} and Exchange:{exch1}." .format(que=destination, exch1=source)) self._refresh.emit(True) if channel.is_open: channel.close() elif buttonObjectName == "unBind": destination = self.target.currentText() source = self.source.currentText() routing_key = self.rkey.text() bindingTableModel.removeRowsWithEmptyColumns() arguments = dict(bindingTableModel.arraydata) if arguments == {}: arguments = None if self.exchange2exchange.isChecked(): if len(routing_key) == 0: routing_key = '' channel = self.eqbConnection.channel() channel.exchange_unbind(destination=destination, source=source, routing_key=routing_key, arguments=arguments) MessageBox.message( QMessageBox.Information, "RabbitMQ UnBinding", "Exchange to Exchange UnBinding!", "Binding removed between Exchange:{exch1} and Exchange:{exch2}." .format(exch1=destination, exch2=source)) self._refresh.emit(True) if channel.is_open: channel.close() elif self.exchange2queue.isChecked(): if len(routing_key) == 0: routing_key = None channel = self.eqbConnection.channel() channel.queue_unbind(queue=destination, exchange=source, routing_key=routing_key, arguments=arguments) MessageBox.message( QMessageBox.Information, "RabbitMQ UnBinding", "Queue to Exchange UnBinding!", "Binding removed between Queue:{que} and Exchange:{exch1}." .format(que=destination, exch1=source)) self._refresh.emit(True) if channel.is_open: channel.close()
def editsetting(self): section_name = self.leServer.currentText() if self.webUrlModified: self.webUrlModified = False url = self.leUrl.text().split(":") protocol = url[0] consoleUrl = url[1].replace("/", "").strip() portBaseUrl = url[2].split("/") port = portBaseUrl[0] baseurl = "" if len(portBaseUrl) > 1: baseurl = "/" + portBaseUrl[1] + "/" self.parser.set(section_name, 'protocol', protocol) self.parser.set(section_name, 'console.url', consoleUrl) self.parser.set(section_name, 'console.port', port) self.parser.set(section_name, 'console.baseurl', baseurl) if self.amqpUrlModified: self.amqpUrlModified = False url = self.le1Url.text().split(":") protocol = url[0] amqpUrl = url[1].replace("/", "").strip() amqpPort = url[2] self.parser.set(section_name, 'amqp.protocol', protocol) self.parser.set(section_name, 'amqp.url', amqpUrl) self.parser.set(section_name, 'amqp.port', amqpPort) if self.userIdModified: self.userIdModified = False self.parser.set(section_name, 'username', self.leUserId.text().strip()) if self.passkeyFileModified: self.passkeyFileModified = False self.parser.set(section_name, 'passkey.file', self.lePassKey.text().strip()) if self.passwordModified: self.passwordModified = False passwd = self.lePassword.text() #passKeyFile = "{fpath}{file}".format(fpath = self.filePath, file=self.parser.get(section_name, 'passkey.file')) passKeyFile = self.lePassKey.text() encPass = "" if len(passKeyFile) != 0 and len(passwd) != 0: encPass = encrypt.encrypt_password(passKeyFile, passwd) self.parser.set(section_name, 'password', encPass) if self.vhostModified: self.vhostModified = False self.parser.set(section_name, 'vhost', self.leVhost.text()) if self.certNameModified: self.certNameModified = False self.parser.set(section_name, 'certificateName', self.leCertificateName.text()) if self.passkeyCertFileModified: self.passkeyCertFileModified = False self.parser.set(section_name, 'passkeycert.file', self.leCertificatePassKey.text().strip()) if self.certPassModified: self.certPassModified = False passwd = self.leCertificatePassword.text() #passKeyFile = "{fpath}{file}".format(fpath = self.filePath, file=self.parser.get(section_name, 'passkeycert.file')) #passKeyFile = ".{file}".format(file=self.parser.get(section_name, 'passkeycert.file')) passKeyFile = self.leCertificatePassKey.text() encPass = "" if len(passKeyFile) != 0 and len(passwd) != 0: encPass = encrypt.encrypt_password(passKeyFile, passwd) self.parser.set(section_name, 'certificatePassword', encPass) with open(self.inifile, 'w') as configfile: self.parser.write(configfile) self.refresh() #index = self.leServer.findText(section_name, Qt.MatchFixedString) #if index >= 0: # self.leServer.setCurrentIndex(index) MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry updated!", \ "Server: {section} update in File: {file} sucessfully.".format(section=section_name, file=self.inifile))
def buttonClicked(self): button = self.sender() #print(button.objectName()) if not button: return buttonObjectName = button.objectName() if buttonObjectName == "add_setting": section_name = self.leAddServer.text() self.parser.add_section(section_name) self.parser.set(section_name, 'protocol', self.wprotocolCombo.currentText().strip()) self.parser.set(section_name, 'console.url', self.whost.text().strip()) self.parser.set(section_name, 'console.port', self.wport.text().strip()) self.parser.set(section_name, 'console.baseurl', self.wbaseurl.text().strip()) self.parser.set(section_name, 'amqp.protocol', self.amqpCombo.currentText().strip()) self.parser.set(section_name, 'amqp.url', self.amqphost.text().strip()) self.parser.set(section_name, 'amqp.port', self.amqpport.text().strip()) self.parser.set(section_name, 'username', self.leUserId.text().strip()) passKeyFile = self.lePassKey.text().strip() self.parser.set(section_name, 'passkey.file', passKeyFile) passwd = self.lePassword.text() encPass = "" if len(passKeyFile) != 0 and len(passwd) != 0: encPass = encrypt.encrypt_password(passKeyFile, passwd) self.parser.set(section_name, 'password', encPass) self.parser.set(section_name, 'vhost', self.leVhost.text().strip()) self.parser.set(section_name, 'certificateName', self.leCertificateName.text().strip()) certPasskeyFile = self.leCertificatePassKey.text().strip() self.parser.set(section_name, 'passkeycert.file', certPasskeyFile) certpasswd = self.leCertificatePassword.text() encCertPass = "" if len(certPasskeyFile) != 0 and len(certpasswd) != 0: encCertPass = encrypt.encrypt_password(certPasskeyFile, certpasswd) self.parser.set(section_name, 'certificatePassword', encCertPass) with open(self.inifile, 'w') as configfile: self.parser.write(configfile) #self.refresh() MessageBox.message(QMessageBox.Information, "RabbitMQ Queue", "Configuration entry added!", \ "Server: {section} added to File: {file} sucessfully.".format(section=section_name, file=self.inifile)) self.resetWidget() elif buttonObjectName == "edit_setting": pass elif buttonObjectName == "cancel_setting": self.resetWidget()
def importConfig(self, parent, sessionAvailable, amqpConnection, exchange_list, queue_list): if sessionAvailable: #print("Importing...") fileData = self.getFileForImport(parent) if fileData is not None: #print(self.connection) if amqpConnection is None: MessageBox.message( QMessageBox.Warning, "RabbitMQ Import Configuration", "AMQP Connection Error!", "AMQP connection is not available.{nl}Please check". format(nl=os.linesep)) return for vhosts in fileData: #print(vhosts) for vh in fileData[vhosts]: vhost = fileData[vhosts][vh] exchanges = vhost["exchanges"] queues = vhost["queues"] bindings = vhost["bindings"] #print(exchanges) #print(queues) #print(bindings) channel = amqpConnection.channel() for exchange in exchanges: if exchange not in exchange_list: exch = exchanges[exchange] etype = exch["type"] durable = exch["durable"] auto_delete = exch["auto_delete"] internal = exch["internal"] arguments = exch["arguments"] try: channel.exchange_declare( exchange=exchange, exchange_type=etype, durable=durable, auto_delete=auto_delete, internal=internal, arguments=arguments) MessageBox.message( QMessageBox.Information, "RabbitMQ Exchange", "Exchange Created!", "Exchange:{exch} of type:{etype} created." .format(exch=exchange, etype=etype)) except Exception as e: error = str(e).strip().replace( "(", "").replace(")", "").split(",") #print(error) textandinfo = error[1].replace( "\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace( "\"", "" ).strip( ) + ". Check Queue naming policy with your administrator." MessageBox.message( QMessageBox.Critical, "RabbitMQ Exchange Creation - Error ({})" .format(error[0]), text, infoText) else: MessageBox.message( QMessageBox.Warning, "RabbitMQ Exchange", "Exchange Exists!", "Exchange:{exch} already exists.".format( exch=exchange)) if channel.is_open: channel.close() channel = amqpConnection.channel() for queue in queues: if queue not in queue_list: qu = queues[queue] durable = qu["durable"] auto_delete = qu["auto_delete"] arguments = qu["arguments"] try: channel.queue_declare( queue=queue, durable=durable, auto_delete=auto_delete, arguments=arguments) MessageBox.message( QMessageBox.Information, "RabbitMQ Queue", "Queue Created!", "{que} has been added.".format( que=queue)) except Exception as e: error = str(e).strip().replace( "(", "").replace(")", "").split(",") #print(error) textandinfo = error[1].replace( "\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace( "\"", "" ).strip( ) + ". Check Queue naming policy with your administrator." MessageBox.message( QMessageBox.Critical, "RabbitMQ Queue Creation - Error ({})". format(error[0]), text, infoText) else: MessageBox.message( QMessageBox.Warning, "RabbitMQ Create Queue", "Queue Exists!", "Queue:{qu} already exists.".format( qu=queue)) if channel.is_open: channel.close() channel = amqpConnection.channel() for binding in bindings: bind = bindings[binding] source = binding.split("_")[0] destination = bind["destination"] routing_key = bind["routing_key"] arguments = bind["arguments"] destination_type = bind["destination_type"] if destination_type == "exchange": #print("e2e", destination, source, routing_key, arguments) try: channel.exchange_bind( destination=destination, source=source, routing_key=routing_key, arguments=arguments) msg = "Exchange to Exchange binding created.{nl}------------------------------{nl}destination:{destination}{nl}source:{source}{nl}routing_key:{routing_key}{nl}arguments:{arguments}{nl}------------------------------{nl}" \ .format(nl=os.linesep, destination=destination, source=source, routing_key=routing_key, arguments=arguments) MessageBox.message( QMessageBox.Information, "RabbitMQ Binding", "Exchange to Exchange Binding!", msg) except Exception as e: error = str(e).strip().replace( "(", "").replace(")", "").split(",") textandinfo = error[1].replace( "\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace( "\"", "" ).strip( ) + ". Check Queue naming policy with your administrator." MessageBox.message( QMessageBox.Critical, "RabbitMQ Exchange Binding - Error ({})" .format(error[0]), text, infoText) elif destination_type == "queue": #print("q2q", destination, source, routing_key, arguments) try: channel.queue_bind(queue=destination, exchange=source, routing_key=routing_key, arguments=arguments) msg = "Exchange to Queue binding created.{nl}------------------------------{nl}queue:{queue}{nl}exchange:{exchange}{nl}routing_key:{routing_key}{nl}arguments:{arguments}{nl}------------------------------{nl}" \ .format(nl=os.linesep, queue=destination, exchange=source, routing_key=routing_key, arguments=arguments) MessageBox.message( QMessageBox.Information, "RabbitMQ Binding", "Exchange to Queue Binding!", msg) except Exception as e: error = str(e).strip().replace( "(", "").replace(")", "").split(",") textandinfo = error[1].replace( "\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace( "\"", "" ).strip( ) + ". Check Queue naming policy with your administrator." MessageBox.message( QMessageBox.Critical, "RabbitMQ Queue Binding - Error ({})". format(error[0]), text, infoText) if channel.is_open: channel.close()
def patchconfig(self): erows = self.getdatafromtable(self.exchangeListTablemodelview, self.exchangeListTablemodel) qrows = self.getdatafromtable(self.queueListTablemodelview, self.queueListTablemodel) e2erows = self.getdatafromtable(self.bindingE2EListTablemodelview, self.bindingE2EListTablemodel) e2qrows = self.getdatafromtable(self.bindingE2QListTablemodelview, self.bindingE2QListTablemodel) #-------------- exchange ------------------ ex_array = {} e = 0 for row in erows: exname = row[1] extype = row[2] durable = row[3] auto_delete = row[4] internal = row[5] arguments = row[6] data = {} data["type"] = extype data["durable"] = "true" if durable else "false" data["auto_delete"] = "true" if auto_delete else "false" data["internal"] = "true" if internal else "false" data["arguments"] = {} if arguments is None else arguments ex_array[exname + "_" + str(e)] = data e = e + 1 #---------- queue ----------------------------------- q_array = {} q = 0 for row in qrows: qname = row[1] durable = row[2] auto_delete = row[3] arguments = row[4] data = {} data["durable"] = "true" if durable else "false" data["auto_delete"] = "true" if auto_delete else "false" data["arguments"] = {} if arguments is None else arguments qdata[resources(qname)] = data q_array[qname + "_" + str(q)] = data q = q + 1 #------------- binding - exchange2exchange / exchange2queue ---------------- binding_array = {} i = 0 for qb in e2erows: source = qb[0] destination = qb[1] destination_type = "exchange" routing_key = qb[2] arguments = qb[3] qbData = {} qbData["destination"] = destination #qbData["destination"] = source #qbData["source"] = source qbData["destination_type"] = destination_type qbData["routing_key"] = routing_key qbData["arguments"] = arguments binding_array[source + "_" + str(i)] = qbData i = i + 1 ####### for qb in e2qrows: source = qb[0] destination = qb[1] destination_type = "queue" routing_key = qb[2] arguments = qb[3] qbData = {} qbData["destination"] = destination #qbData["destination"] = source #qbData["source"] = source qbData["destination_type"] = destination_type qbData["routing_key"] = routing_key qbData["arguments"] = arguments binding_array[source + "_" + str(i)] = qbData i = i + 1 eqs = {} eqs.update({"exchanges": ex_array}) eqs.update({"queues": q_array}) eqs.update({"bindings": binding_array}) vhost = {"/": eqs} #print(vhost) output = {} #output["version"] = "0.1" #output["broker"] = "rmq-1" #output["user"] = "******" output["vhosts"] = vhost print(output) #fileName = "C:\\Users\\vais\Documents\\Scripts\\python\\RabbitMQ\\mend.json" fileName = self.leFileName.toPlainText() if len(fileName) > 0: with open(fileName, 'w') as json_file: #json_file.write(self.leMessages.toPlainText()) json_file.write(json.dumps(output, indent=2)) MessageBox.message( QMessageBox.Information, "RabbitMQ Mend Config", "Exchange(s), Queue(s) and Binding(s) Exported!", "Please see file: {file} for details.".format( file=fileName)) s = open(fileName).read() s = s.replace("[", "") s = s.replace("]", "") s = s.replace("\"{", "{") s = s.replace("}\"", "}") s = s.replace("'", "\"") f = open(fileName, 'w') f.write(s) f.close()
def generate(self): self.selectedExchanges = {} self.selectedQueues = {} exchanges = self.exchangeListTablemodelview.selectedIndexes() queues = self.queueListTablemodelview.selectedIndexes() erows = sorted( set(index.row() for index in self.exchangeListTablemodelview.selectedIndexes())) qrows = sorted( set(index.row() for index in self.queueListTablemodelview.selectedIndexes())) ex_array = {} q_array = {} eqb_array = {} exmodel = self.exchangeListTablemodelview.model() qmodel = self.queueListTablemodelview.model() for row in erows: #print('ERow %d is selected' % row) exname = exmodel.arraydata[row][0] extype = exmodel.arraydata[row][1] durable = exmodel.arraydata[row][2] auto_delete = exmodel.arraydata[row][3] internal = exmodel.arraydata[row][4] arguments = exmodel.arraydata[row][5] data = {} data["type"] = extype data["durable"] = durable data["auto_delete"] = auto_delete data["internal"] = internal data["arguments"] = arguments exdata = {} exdata[exname] = data exbindings = RestFunctions.exchange_bindings( RestFunctions, self, self.session, self._webUrl, exname, self._userId, self._password, self._certName) #print(exbindings) i = 0 for eb in exbindings: source = eb[1] destination = eb[4] destination_type = eb[5] routing_key = eb[6] arguments = eb[9] #print(destination, source, destination_type, routing_key, arguments) exbData = {} exbData["destination"] = destination #exbData["source"] = source exbData["destination_type"] = destination_type exbData["routing_key"] = routing_key exbData["arguments"] = arguments #print(exbData) eqb_array[source + "_" + str(i)] = exbData i = i + 1 ex_array.update(exdata) for row in qrows: #print('QRow %d is selected' % row) qname = qmodel.arraydata[row][0] durable = qmodel.arraydata[row][1] auto_delete = qmodel.arraydata[row][2] arguments = qmodel.arraydata[row][3] data = {} data["durable"] = durable data["auto_delete"] = auto_delete data["arguments"] = arguments qdata = {} qdata[qname] = data q_array.update(qdata) eqs = {} eqs["exchanges"] = ex_array eqs["queues"] = q_array eqs["bindings"] = eqb_array vhost = {"/": eqs} #print(vhost) output = {} #output["version"] = "0.1" #output["broker"] = "rmq-1" #output["user"] = "******" output["vhosts"] = vhost print(output) #print(json.dumps(output)) jstr = json.dumps(output, indent=2) self.leMessages.setPlainText(jstr) fileName = self.leFileName.text() if len(fileName) > 0: with open(fileName, 'w') as json_file: json_file.write(self.leMessages.toPlainText()) MessageBox.message( QMessageBox.Information, "RabbitMQ Export", "Exchange(s), Queue(s) and Binding(s) Exported!", "Please see file: {file} for details.".format( file=fileName))
def deleteMessages(self, queue, msgdataToBeDeleted, sessionAvailable, amqpConnection, allOthers): if sessionAvailable: #print("Deleting...") if amqpConnection is None: MessageBox.message(QMessageBox.Warning, "RabbitMQ Delete Message", "AMQP Connection Error!", "AMQP connection is not available.{nl}Please check".format(nl=os.linesep)) return print(amqpConnection) channel = amqpConnection.channel() messagesToBeDeleted = json.loads(msgdataToBeDeleted) messagesToBeNAcked = json.loads(allOthers) #print(messagesToBeDeleted, messagesToBeNAcked) tobeNAckedMessages = [] for key in messagesToBeNAcked: #print("nack:{}".format(key)) message = messagesToBeNAcked[key]['body'] tobeNAckedMessages.append(message) tobeDeletedMessages = [] for key in messagesToBeDeleted: #print("rej:{}".format(key)) message = messagesToBeDeleted[key]['body'] tobeDeletedMessages.append(message) encoding = 'utf-8' message_delete_count = 0 # Get ten messages and break out for method_frame, properties, body in channel.consume(queue): # Display the message parts #print(properties) #print(method_frame, body, type(body), tobeNAckedMessages, tobeDeletedMessages) '''if str(body, encoding) in tobeNAckedMessages: # NAck the message and set requeue to True, so the message gets requeued print(method_frame, body, tobeNAckedMessages, tobeDeletedMessages) channel.basic_nack(method_frame.delivery_tag, requeue=True)''' if str(body, encoding) in tobeDeletedMessages: # Reject the message and set requeue to False, so the message gets deleted #print(method_frame, body, tobeNAckedMessages, tobeDeletedMessages) channel.basic_reject(method_frame.delivery_tag, requeue=False) #print("Message with delivery tag:{tag} deleted.".format(tag=method_frame.delivery_tag)) MessageBox.message(QMessageBox.Information, "RabbitMQ Delete Message", "Message Deleted!", \ "Message with delivery tag:{tag} deleted.".format(tag=method_frame.delivery_tag)) message_delete_count = message_delete_count + 1 if message_delete_count == len(tobeDeletedMessages): # Cancel the consumer and return any pending messages requeued_messages = channel.cancel() #print('Requeued %i messages' % requeued_messages) channel.close()
def shovelMessages(self, exchange, routingKey, props, msgdata, sessionAvailable, amqpConnection, textContents): if sessionAvailable: #print("Importing...") if not exchange: MessageBox.message(QMessageBox.Warning, "RabbitMQ Shovel Message", "Missing Input!", "Please select an exchange") return if not routingKey or not props: MessageBox.message( QMessageBox.Warning, "RabbitMQ Shovel Message", "Missing Input!", "Please select a Routing Key or provide properties or headers." ) return if amqpConnection is None: MessageBox.message( QMessageBox.Warning, "RabbitMQ Shovel Message", "AMQP Connection Error!", "AMQP connection is not available.{nl}Please check".format( nl=os.linesep)) return channel = amqpConnection.channel() #print(msgdata) #messages = json.loads(json.dumps(msgdata)) messages = json.loads(msgdata) #print(messages) for key in messages: #print(messages[key]) if "message_" not in key: MessageBox.message( QMessageBox.Warning, "RabbitMQ Shovel Message", "Message Shoveling Error!", "Key should contain " "message_*" " where * indicates message number.{nl}Please check". format(nl=os.linesep)) return message = messages[key]['body'] hasMessageId = False if props != {}: if not hasMessageId: hasMessageId = props.get('message_id') is not None if not hasMessageId: print("Adding message_id ...") props['message_id'] = uuid.uuid4().hex if props.get('content_type') is None: print("Adding content_type ...") props['content_type'] = "application/json" #print(message, props) properties = pika.BasicProperties() for pKey in props: if props.get(pKey) is not None: setattr(properties, pKey, props.get(pKey)) print(pKey, props.get(pKey)) #print(properties) if len(routingKey.strip()) == 0: routingKey = "" try: #channel.confirm_delivery() exch_exist = channel.exchange_declare(exchange=exchange, passive=True) if exch_exist: channel.basic_publish(exchange=exchange, routing_key=routingKey, body=message, properties=properties) MessageBox.message(QMessageBox.Information, "RabbitMQ Shovel Message", "Message Copied!", \ "Message published to Exchange: {exch}.".format(exch=exchange)) else: MessageBox.message( QMessageBox.Warning, "RabbitMQ Shovel Message", "Exchange Does not exist!", "Exchange:{exch} aldoes not exists.".format( exch=exchange)) except Exception as e: error = str(e).strip().replace("(", "").replace(")", "").split(",") textandinfo = error[1].replace("\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace("\"", "").strip() MessageBox.message( QMessageBox.Critical, "RabbitMQ Shovel Message - Error ({})".format( error[0]), text, infoText) if channel.is_open: channel.close()
def importMessages(self, parent, sessionAvailable, amqpConnection): if sessionAvailable: #print("Importing...") fileData = self.getFileForImport(parent) if fileData is not None: #print(amqpConnection) if amqpConnection is None: MessageBox.message( QMessageBox.Warning, "RabbitMQ Import Message", "AMQP Connection Error!", "AMQP connection is not available.{nl}Please check". format(nl=os.linesep)) return channel = amqpConnection.channel() for key in fileData: #print(fileData[key]) if "message_" not in key: MessageBox.message( QMessageBox.Warning, "RabbitMQ Import Message", "Import Error!", "Invalid JSON file.{nl}Please check".format( nl=os.linesep)) return exchange = fileData[key]['exchange'] routingKey = fileData[key]['routing_key'] message = fileData[key]['body'] props = fileData[key]['properties'] headers = {} if props.get('headers') is not None: headers = props['headers'] hasMessageId = False if headers != {}: if not hasMessageId: hasMessageId = headers.get( 'JMSMessageID') is not None if not hasMessageId: hasMessageId = headers.get( 'message_id') is not None if not hasMessageId: hasMessageId = headers.get('msg_id') is not None if props != {}: if not hasMessageId: hasMessageId = props.get('message_id') is not None if not hasMessageId: print("Adding message_id ...") props['message_id'] = uuid.uuid4().hex if props.get('content_type') is None: print("Adding content_type ...") props['content_type'] = "application/json" #print(exchange, routingKey, message, props) properties = pika.BasicProperties() for pKey in props: if props.get(pKey) is not None: setattr(properties, pKey, props.get(pKey)) #print(pKey, props.get(pKey)) #print(properties) if len(routingKey.strip()) == 0: routingKey = "" try: #channel.confirm_delivery() exch_exist = channel.exchange_declare( exchange=exchange, passive=True) #print("exch_exist: {}".format(exch_exist)) if exch_exist: channel.basic_publish(exchange=exchange, routing_key=routingKey, body=message, properties=properties) MessageBox.message(QMessageBox.Information, "RabbitMQ Import Message", "Message Imported!", \ "Message published to Exchange: {exch}.".format(exch=exchange)) else: MessageBox.message( QMessageBox.Warning, "RabbitMQ Import Message", "Exchange Does not exist!", "Exchange:{exch} aldoes not exists.".format( exch=exchange)) except Exception as e: error = str(e).strip().replace("(", "").replace( ")", "").split(",") textandinfo = error[1].replace("\"", "").split("-") text = textandinfo[0].replace("\"", "").strip() infoText = textandinfo[1].replace("\"", "").strip() MessageBox.message( QMessageBox.Critical, "RabbitMQ Import Message - Error ({})".format( error[0]), text, infoText) if channel.is_open: channel.close()