Commit 6e2d6c37 authored by Alkim Gozen's avatar Alkim Gozen

initial commit with flask.socketio

parents
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
.static_storage/
.media/
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
pyenv/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.vscode/
.idea/
\ No newline at end of file
FROM centos:7
MAINTAINER Rain.lab
RUN yum install -y epel-release; \
yum install -y python-pip python-devel gcc; \
yum install -y yum-utils device-mapper-persistent-data lvm2;
RUN yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo;
RUN yum install -y docker-ce
ADD [ "src", "/src" ]
ADD [ "requirements.txt", "/src"]
WORKDIR /src
RUN pip install -r requirements.txt
VOLUME /var/lib/docker
CMD ["bash"]
\ No newline at end of file
version: '2'
services:
beiran:
image: rain.lab/beiran
build: .
privileged: true
volumes:
- /var/run/docker.sock:/var/run/docker.sock
networks:
- test
command: python -u beiran.py
networks:
test:
\ No newline at end of file
certifi==2017.11.5
chardet==3.0.4
click==6.7
docker==2.6.1
docker-pycreds==0.2.1
enum-compat==0.0.2
Flask==0.12.2
Flask-SocketIO==2.9.2
idna==2.6
itsdangerous==0.24
Jinja2==2.10
MarkupSafe==1.0
netifaces==0.10.6
python-engineio==2.0.1
python-socketio==1.8.3
requests==2.18.4
six==1.11.0
urllib3==1.22
websocket-client==0.44.0
Werkzeug==0.12.2
zeroconf==0.19.1
import logging
import socket
import signal
import sys
import time
from threading import Lock
from zeroconf import ServiceBrowser, ServiceInfo, ServiceStateChange, Zeroconf
from flask import Flask, request
from flask_socketio import SocketIO as SocketIOServer, emit
from flask_socketio import Namespace
from socketIO_client import SocketIO, LoggingNamespace
import logging
logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
logging.basicConfig()
info = None
hostname = socket.gethostname()
domain = "_beiran._tcp.local."
app = Flask(__name__)
# app.config['SECRET_KEY'] = 'secret!'
# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on installed packages.
async_mode = None
socketio_server = SocketIOServer(app, port=5000, async_mode=async_mode)
thread = None
thread_lock = Lock()
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
socketio_server.sleep(10)
count += 1
socketio_server.emit('my_response',
{'data': 'Server generated event', 'count': count},
namespace='/test')
def signal_term_handler(signal, frame):
print('got SIGTERM')
if info:
zeroconf.unregister_service(info)
sys.exit(0)
signal.signal(signal.SIGTERM, signal_term_handler)
def on_connect():
print('connect')
def on_disconnect():
print('disconnect')
def on_reconnect():
print('reconnect')
def connecNodeWs(info):
socketIO = SocketIO(socket.inet_ntoa(info.address), 5000)
socketIO.on('connect', on_connect)
socketIO.on('disconnect', on_disconnect)
socketIO.on('reconnect', on_reconnect)
def on_service_state_change(zeroconf, service_type, name, state_change):
print("Service %s of type %s state changed: %s" % (name, service_type, state_change))
if state_change is ServiceStateChange.Added:
info = zeroconf.get_service_info(service_type, name)
# if name != hostname + "." + domain:
connecNodeWs(info)
if info:
print(" Address: %s:%d" % (socket.inet_ntoa(info.address), info.port))
print(" Weight: %d, priority: %d" % (info.weight, info.priority))
print(" Server: %s" % (info.server))
if info.properties:
print(" Properties are:")
for key, value in info.properties.items():
print(" %s: %s" % (key, value))
else:
print(" No properties")
else:
print(" No info")
print('\n')
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
print('Number of arguments:', len(sys.argv), 'arguments.')
print('Argument List:', str(sys.argv))
if len(sys.argv) > 1:
assert sys.argv[1:] == ['--debug']
logging.getLogger('zeroconf').setLevel(logging.DEBUG)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('google.com', 0))
hostip = s.getsockname()[0]
print("hostname = " + hostname)
print("ip = " + hostip)
desc = {'name': hostname}
info = ServiceInfo(domain,
hostname + "." + domain,
socket.inet_aton(hostip), 3000, 0, 0,
desc, hostname + ".local.")
zeroconf = Zeroconf()
print("Registration of a service, press Ctrl-C to exit...")
try:
print("Registering " + hostname + "...")
zeroconf.register_service(info)
except KeyboardInterrupt:
pass
print("\nBrowsing services, press Ctrl-C to exit...\n")
browser = ServiceBrowser(zeroconf, domain, handlers=[on_service_state_change])
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
pass
finally:
zeroconf.close()
@socketio_server.on_error() # Handles the default namespace
def error_handler(e):
pass
@socketio_server.on_error_default # handles all namespaces without an explicit error handler
def default_error_handler(e):
pass
class BeiranNamespace(Namespace):
def on_my_ping(self):
emit('my_pong')
def on_connect(self):
global thread
with thread_lock:
if thread is None:
thread = socketio_server.start_background_task(
target=background_thread)
emit('my_response', {'data': 'Connected', 'count': 0})
def on_disconnect(self):
print('Client disconnected', request.sid)
socketio_server.on_namespace(BeiranNamespace('/beiran'))
import docker
# import os
# def getSize(filename):
# st = os.stat(filename)
# return st.st_size
#
# def exists(path):
# """Test whether a path exists. Returns False for broken symbolic links"""
# try:
# st = os.stat(path)
# except os.error:
# return False
# return True
client = docker.from_env()
image_list = client.images.list()
# driver = client.info().get('Driver')
# print("Docker INFO")
# print("Driver:" + driver)
# print("=================================")
print("IMAGE LIST")
print("=================================")
for i in image_list:
if len(i.tags) > 0:
print("Image Name: " + i.tags[0])
else:
print("Image has no name")
print("Image ID:", i.id[7:], "ENC:", i.id[:6])
print("Size:", i.attrs.get('Size'))
print("All Tags:")
print(i.tags)
print("Layers: ")
docker_layers = i.attrs.get("RootFS").get("Layers")
for layer in docker_layers:
enc = layer[:6]
layer_id = layer[7:]
# file = "/var/lib/docker/image/overlay2/layerdb/" + enc + "/" + layer_id
# if exists(file):
# print("ID:", layer_id, "Size:", getSize(file))
# else:
# print("ID:", layer_id, "NOSIZE")
print("ID:", layer_id, "ENC:", enc)
print("======================================================")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment