Nginx server with uwsgi,flask and sleekxmpp - nginx

I'm trying to handling some messages by using nginx server with uwsgi, flask and sleekxmpp.
Here is the code.
import ssl, json, logging, threading, time
from flask import Flask
from sleekxmpp import ClientXMPP
from sleekxmpp.exceptions import IqError, IqTimeout
smsg = """{
"version":1,
"type":"request",
"messageId":"xxyyzz",
"payload":
{
"deviceType":"ctlr",
"command":"getDeviceInfo"
}
}"""
class XMPP(ClientXMPP):
rosterList=[]
def __init__(self, jid, password):
ClientXMPP.__init__(self, jid, password)
self.add_event_handler('session_start', self.session_start, threaded = True)
self.add_event_handler('message', self.message, threaded=True)
self.ssl_version = ssl.PROTOCOL_SSLv23
def session_start(self, event):
self.send_presence(pshow='online')
try:
self.rosterList.append(self.get_roster())
except IqError as err:
print 'Error: %' % err.iq['error']['condition']
except IqTimeout:
print 'Error: Request time out'
def message(self, msg):
data = msg['body'][12:]
dictData = json.loads(data)
print data
if 'payload' in dictData.keys():
for lists in dictData['payload']['indexes']:
print lists
elif 'message' in dictData.keys():
print 'Request accepted'
app = Flask(__name__)
#logging.basicConfig(level = logging.DEBUG)
xmpp = XMPP('jid', 'password')
class XmppThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
if xmpp.connect(('server', '5222')):
xmpp.process(block=True)
xt = XmppThread()
xt.start()
#app.route('/')
def send():
xmpp.send_message(mto='receiver', mbody=smsg, mtype='chat')
return '<h1>Send</h1>'
I run the code by uwsgi with these options.
[uwsgi]
uid = uwsgi
gid = uwsgi
pidfile = /run/uwsgi/uwsgi.pid
emperor = /etc/uwsgi.d
stats = /run/uwsgi/stats.sock
chmod-socket = 660
emperor-tyrant = true
cap = setgid,setuid
[uwsgi]
plugin = python
http-socket = :8080
wsgi-file = /var/www/uwsgi/flask_uwsgi.py
callable = app
module = app
enable-threads = True
logto = /var/www/uwsgi/flask_uwsgi.log
When I run uwsgi by typing command, like '/usr/sbin/uwsgi --ini uwsgi.ini', it works well. I can send and recieve the messages. But, when I run this on CentOS 7's service, recieve is working, but send is not working.
Did i need some more options or missing something?

Related

I keep getting an empty task list APScheduler

I am writing a website on a Flask, I use it to run uwsgi + nginx. It was necessary to write a timer to periodically execute tasks. For this I used uwsgidecorators. The task should check the status of the scheduler tasks. To get a list of tasks, I used get_jobs(). But the list I keep getting empty.
webapp/__init__.py:
# -*- coding: utf-8 -*-
from gevent import monkey
monkey.patch_all()
import grpc.experimental.gevent
grpc.experimental.gevent.init_gevent()
from flask import Flask, session, request
from config import DevelopConfig, MqttConfig, MailConfig, ProductionConfig
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_script import Manager
from flask_socketio import SocketIO
from flask_mqtt import Mqtt
from flask_login import LoginManager
from flask_babel import Babel
from flask_babel_js import BabelJS
from flask_babel import lazy_gettext as _l
from apscheduler.schedulers.gevent import GeventScheduler
app = Flask(__name__)
app.config.from_object(ProductionConfig)
app.config.from_object(MqttConfig)
app.config.from_object(MailConfig)
db = SQLAlchemy(app)
migrate = Migrate(app, db, render_as_batch=True)
mail = Mail(app)
mqtt = Mqtt(app)
manager = Manager(app, db)
login_manager = LoginManager(app)
login_manager.login_view = 'auth'
login_manager.login_message = _l("Необходимо авторизоваться для доступа к закрытой странице")
login_manager.login_message_category = "error"
scheduler = GeventScheduler()
scheduler.start()
scheduler.add_job(publish_async, args=["Hello"], id="job", trigger='interval', seconds=2)
socketio = SocketIO(app, async_mode='gevent_uwsgi') # Production Version
babel = Babel(app)
babeljs = BabelJS(app=app, view_path='/translations/')
import webapp.views
#babel.localeselector
def get_locale():
# if the user has set up the language manually it will be stored in the session,
# so we use the locale from the user settings
try:
language = session['language']
except KeyError:
language = None
if language is not None:
print(language)
return language
return request.accept_languages.best_match(app.config['LANGUAGES'].keys())
from webapp import models
def publish_async(message):
print(message)
webapp/tasks.py:
from uwsgidecorators import timer
#timer(10, target='spooler')
def check_run_tasks(args):
_list_schedulers = _scheduler_method.get_jobs()
print(_list_schedulers)
wsgi.ini:
[uwsgi]
env = PYTHONIOENCODING=UTF-8
module = wsgi:app
master = true
# processes = 5
enable-threads = true
gevent = 1024
gevent-monkey-patch = true
buffer-size=32768
# lazy-apps = true
socket = /home/sammy/projectnew/projectnew.sock
socket-timeout = 30
chmod-socket = 664
thunder-lock = true
spooler = /home/sammy/projectnew/webapp/mytasks
import = webapp/tasks.py
vacuum = true
die-on-term = true
wsgi.py:
# -*- coding: utf-8 -*-
from webapp import app, socketio
if __name__ == '__main__':
socketio.run(app, use_reloader=False)

How to set OpenStack API configuration in Centos 7?

Please tell me which SDK is better to call OpenStack APIs.
I haven't found much information or tutorials on this subject.
If you are using the CLI; the official Openstack client is the obvious choice. If you are trying to make programmatic API calls you can use anything from simple http request to a client library like shade for Python, or gophercloud for Golang.
pip install openstacksdk
Conneect to the cloud:
"""
Connect to an OpenStack cloud.
For a full guide see TODO(etoews):link to docs on developer.openstack.org
"""
import argparse
import os
import openstack
from openstack.config import loader
import sys
openstack.enable_logging(True, stream=sys.stdout)
#: Defines the OpenStack Config loud key in your config file,
#: typically in $HOME/.config/openstack/clouds.yaml. That configuration
#: will determine where the examples will be run and what resource defaults
#: will be used to run the examples.
TEST_CLOUD = os.getenv('OS_TEST_CLOUD', 'devstack-admin')
config = loader.OpenStackConfig()
cloud = openstack.connect(cloud=TEST_CLOUD)
class Opts(object):
def __init__(self, cloud_name='devstack-admin', debug=False):
self.cloud = cloud_name
self.debug = debug
# Use identity v3 API for examples.
self.identity_api_version = '3'
def _get_resource_value(resource_key, default):
return config.get_extra_config('example').get(resource_key, default)
SERVER_NAME = 'openstacksdk-example'
IMAGE_NAME = _get_resource_value('image_name', 'cirros-0.3.5-x86_64-disk')
FLAVOR_NAME = _get_resource_value('flavor_name', 'm1.small')
NETWORK_NAME = _get_resource_value('network_name', 'private')
KEYPAIR_NAME = _get_resource_value('keypair_name', 'openstacksdk-example')
SSH_DIR = _get_resource_value(
'ssh_dir', '{home}/.ssh'.format(home=os.path.expanduser("~")))
PRIVATE_KEYPAIR_FILE = _get_resource_value(
'private_keypair_file', '{ssh_dir}/id_rsa.{key}'.format(
ssh_dir=SSH_DIR, key=KEYPAIR_NAME))
EXAMPLE_IMAGE_NAME = 'openstacksdk-example-public-image'
def create_connection_from_config():
return openstack.connect(cloud=TEST_CLOUD)
def create_connection_from_args():
parser = argparse.ArgumentParser()
config = loader.OpenStackConfig()
config.register_argparse_arguments(parser, sys.argv[1:])
args = parser.parse_args()
return openstack.connect(config=config.get_one(argparse=args))
def create_connection(auth_url, region, project_name, username, password):
return openstack.connect(
auth_url=auth_url,
project_name=project_name,
username=username,
password=password,
region_name=region,
app_name='examples',
app_version='1.0',
)
Complete guide

When calling a function, how to feed variable as an arg

I have the code below that works, but instead of calling the function with "www.google.com", i need to be able to pass as arg:
python certexp.py www.google.com:
import ssl
import OpenSSL
import time
def get_SSL_Expiry_Date(host, port):
cert = ssl.get_server_certificate((host, 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
raw_date = x509.get_notAfter()
decoded_date = raw_date.decode("utf-8")
print (decoded_date)
dexpires = time.strptime(decoded_date, "%Y%m%d%H%M%Sz")
print (dexpires.tm_mon,"/",dexpires.tm_mday,"/",dexpires.tm_year)
get_SSL_Expiry_Date("google.com", 443)
Thank you
In python the sys module handles command line arguments.
This gives you an array of command line parameters, with sys.argv[0] being the name of the executable, then any subsequent elements being user parameters.
This makes your code:
import ssl
import OpenSSL
import time
import sys
def get_SSL_Expiry_Date(host, port):
cert = ssl.get_server_certificate((host, 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
raw_date = x509.get_notAfter()
decoded_date = raw_date.decode("utf-8")
print (decoded_date)
dexpires = time.strptime(decoded_date, "%Y%m%d%H%M%Sz")
print (dexpires.tm_mon,"/",dexpires.tm_mday,"/",dexpires.tm_year)
if (len(sys.argv) == 1):
sys.stderr.write("%s: Give hostname as an argument, optionally a port too" % (sys.argv[0]))
sys.exit(1)
hostname = sys.argv[1]
port = 443
if (len(sys.argv) == 3):
port = int(sys.argv[2])
get_SSL_Expiry_Date(hostname, port)
Obviously you could do that for the port too. There's other command line parsing modules too, so you can say --port= etc.

PyQt4 display dialog box on all displays windows 10

First off thanks for the help, I am a unix admin and don't know much about QT or windows 10
I have to display a qt popup menu/app on all displays on windows 10 using winexe to access a remote box, the behavior should be like the below winexe command:
winexe -U 'ad/user%xxxxxxx' --system --interactive=1 //10.14.6.133 'msg * hello jello'
below is my command line for the PyQt4 script:
winexe -U 'ad/user%xxxxxxx' --system --interactive=1 //10.14.6.133 'cmd /c c:\python26\python.exe c:\scripts\bobo3.py'
It just sits there and does nothing visible. My guess is it needs to be displayed to all active displays and I have no idea how to do this.
Here is the code, it works when run from a cmd prompt locally:
from optparse import OptionParser
from PyQt4 import QtGui, QtCore
class TopDialog(QtGui.QWidget):
def __init__(self, title='Message', width=960, height=640, ):
super(TopDialog, self).__init__()
self.setFixedSize(width, height)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)
screen = QtGui.QDesktopWidget().screenGeometry()
self.move((screen.width() - self.width())/2, (screen.height() - self.height())/2)
if not isinstance(title, unicode):
title = title.decode('utf-8')
self.title_lb = QtGui.QLabel(title)
self.title_lb.setAlignment(QtCore.Qt.AlignCenter)
self.title_lb.setFrameStyle(QtGui.QFrame.StyledPanel | QtGui.QFrame.Sunken)
self.message_lb = QtGui.QLabel()
self.message_lb.setAlignment(QtCore.Qt.AlignCenter)
self.message_lb.setMinimumSize(self.width()/2, self.height()/2)
self.ok_bt = QtGui.QPushButton('OK')
self.ok_bt.clicked.connect(self._ok_bt_clicked)
self.main_lo = QtGui.QVBoxLayout()
self.main_lo.addWidget(self.title_lb)
self.main_lo.addStretch()
self.main_lo.addWidget(self.message_lb)
self.main_lo.addStretch()
self.main_lo.addWidget(self.ok_bt)
self.setLayout(self.main_lo)
def set_message(self, message):
if not isinstance(message, unicode):
message = message.decode('utf-8')
self.message_lb.setText(message)
def set_button_text(self, text):
if not isinstance(text, unicode):
text = text.decode('utf-8')
self.ok_bt.setText(text)
def _ok_bt_clicked(self):
# do something you want.
self.close() # close the window
client = None
def main():
global client
parser = OptionParser()
parser.add_option('-m', '--message', type=str, action="store", dest="message", help="The alert message")
parser.add_option('-s', '--sent_by', type=str, action="store", dest="sent_by", help='login of sender')
(options, args) = parser.parse_args()
app = QtGui.QApplication(sys.argv)
sent_by = options.sent_by
if sent_by is None:
sent_by = "Someone"
message = options.message
if message is None:
message = "we are not sure why"
print sent_by, message
client = TopDialog(' %s wants your attention' % (sent_by))
client.set_message('%s' % (message))
client.set_button_text('OK')
client.show()
app.exec_()
main()

Adding multiple nginx to collectd's monitoring plugin

Collectd queries nginx's HttpStubStatusModule
in order to find the active connections.
The config end looks like-
<Plugin "nginx">
URL "https://localhost:8433/nginx_status"
</Plugin>
The plugin is here.
i have a setup wherein i have 4 Nginx instances running on the same physical host, each listening at a different port. How do i make collectd monitor multiple Nginxes? The following does not work-
<Plugin "nginx">
URL "https://localhost:8433/nginx_status"
</Plugin>
<Plugin "nginx">
URL "https://localhost:8434/nginx_status"
</Plugin>
I have written a small script for the collectd Python plugin:
https://github.com/magazov/collectd-multinginx-python
It is very simple to use.
Here is the source code:
#! /usr/bin/env python
import re
import urllib2
import collectd
class Nginx(object):
def __init__(self):
self.pattern = re.compile("([A-Z][\w]*).+?(\d+)")
self.urls = {}
def do_nginx_status(self):
for instance, url in self.urls.items():
try:
response = urllib2.urlopen(url)
except urllib2.HTTPError, e:
collectd.error(str(e))
except urllib2.URLError, e:
collectd.error(str(e))
else:
data = response.read()
m = self.pattern.findall(data)
for key, value in m:
metric = collectd.Values()
metric.plugin = 'nginx-%s' % instance
metric.type_instance = key.lower()
metric.type = 'nginx_connections'
metric.values = [value]
metric.dispatch()
requests = data.split('\n')[2].split()[-1]
collectd.debug('Requests %s' % requests)
metric = collectd.Values()
metric.plugin = 'nginx-%s' % instance
metric.type = 'nginx_requests'
metric.values = [requests]
metric.dispatch()
def config(self, obj):
self.urls = dict((node.key, node.values[0]) for node in obj.children)
nginx = Nginx()
collectd.register_config(nginx.config)
collectd.register_read(nginx.do_nginx_status)
struct curl_slist *curl_list = NULL;
curl_list = curl_slist_append(curl_list, header);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_list);

Resources