Пример #1
0
    def __init__(self):
        self._monitor = Monitor()
        self._servers = {}

        # TODO(stub): add additional members

        self._start()
Пример #2
0
    def __init__(self):
        super(xbmcmediaimport.Observer, self).__init__()

        self._monitor = Monitor()
        self._player = Player()
        self._observers = {}

        self._run()
Пример #3
0
    def __init__(self):
        super(xbmcmediaimport.Observer, self).__init__()

        self._monitor = Monitor()
        self._observers = {}

        # TODO(stub): add additional members

        self._run()
Пример #4
0
def run_monitor():
    monitor = Monitor(config)

    # NOTE: Ugly workaround for running asyncio on Windows
    # Solution adapted from here: https://github.com/encode/httpx/issues/914#issuecomment-622586610
    if (sys.version_info[0] == 3 and
    sys.version_info[1] >= 8 and
    sys.platform.startswith('win')):
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    asyncio.run(monitor.monitor_and_produce(config['websites']))
Пример #5
0
    def process(self, command, debug):
        result = {}

        # basic = Monitor().system()
        basic = Basic().process(command, debug)
        result['basic'] = basic
        cpudata = {}
        if basic['os_platform'] == 'Linux':

            result['board'] = Board().process(command, debug)

            if debug:
                output = open(os.path.join(setting.BASEDIR, 'files/cpu.out'),
                              'r',
                              encoding='utf8').read()
            else:
                output = command('cat /proc/cpuinfo')
            cpudata = self.parseCpu(output)
        elif basic['os_platform'] == 'Windows':
            from lib import winmonitor
            cpudata = winmonitor.printCPU()
            cpudata['cpu_count'] = psutil.cpu_count(logical=True)
            result['board'] = winmonitor.getBoard()
        result['cpu'] = cpudata
        info = psutil.virtual_memory()
        result['mem'] = Monitor().bytes_to_gb(info.total)
        # 处理磁盘信息
        return result
Пример #6
0
def test_capture_insert_time():
	monitor = Monitor()
	monitor.capture_insert_document("test crawler")

	conn = pymongo.MongoClient("mongodb://%s:%s/%s" % (
		monitor.config["ip"],
		monitor.config["port"],
		monitor.config["database"]
	))
	db   = conn[monitor.config["database"]]
	docs = db.status.find({"crawler_name": re.compile("test crawler", re.IGNORECASE)})

	has_document = docs.count() != 0
	if has_document:
		doc = [doc for doc in docs][0]
		assert doc["crawler_name"] == "Test Crawler"

		db.status.remove({"crawler_name": re.compile("test crawler", re.IGNORECASE)})
	conn.close()
	assert has_document
Пример #7
0
def test_capture_insert_time():
    monitor = Monitor()
    monitor.capture_insert_document("test crawler")

    conn = pymongo.MongoClient("mongodb://%s:%s/%s" %
                               (monitor.config["ip"], monitor.config["port"],
                                monitor.config["database"]))
    db = conn[monitor.config["database"]]
    docs = db.status.find(
        {"crawler_name": re.compile("test crawler", re.IGNORECASE)})

    has_document = docs.count() != 0
    if has_document:
        doc = [doc for doc in docs][0]
        assert doc["crawler_name"] == "Test Crawler"

        db.status.remove(
            {"crawler_name": re.compile("test crawler", re.IGNORECASE)})
    conn.close()
    assert has_document
Пример #8
0
    def process(self, command, debug):
        # 处理磁盘信息
        if debug:
            output = {
                'os_platform': 'linux',
                'os_version': 'CentOS release 7.7',
                'hostname': 'python'
            }
        else:
            output = Monitor().system()

        return output
Пример #9
0
    def init_monitor(self, interval=10):
        try:
            self.log.debug("Manager initializes monitor.")

            if self.monitor_log == None:
                self.log.debug("Set monitor logger to backup logger.")
                self.monitor_log = self.log
            monitor = Monitor(self.monitor_log,
                              self.monitor_queue,
                              interval=int(interval))
            self.monitor = monitor
        except Exception as e:
            self.log.error("Manager failed to initialize monitor. %s" % e)
            return False
Пример #10
0
class Server(Process):
    def __init__(self, connect_info, process_list):
        super(Process, self).__init__()
        self.process_list = process_list
        self.server_monitor = Monitor(connect_info=connect_info)
        self.bot = telegram.Bot(token=Config.TELEGRAM_TOKEN)
        self.chat_id = Config.TELEGRAM_CHAT_ID

    def run(self):
        while True:
            time.sleep(5)
            for process in self.process_list:
                if not self.server_monitor.exist_process(process):
                    print(f'<<< {process} >>> is not working')
                    self.bot.sendMessage(
                        chat_id=Config.TELEGRAM_CHAT_ID,
                        text=f'<<< {process} >>> is not working')
            print(f'process check : {datetime.datetime.now()}')
Пример #11
0
def main():
    config = {}
    config['sensor_gpio'] = os.getenv('SENSOR_GPIO')
    config['graphite_host'] = os.getenv('GRAPHITE_HOST')
    config['graphite_port'] = os.getenv('GRAPHITE_PORT')
    config['graphite_metric_prefix'] = os.getenv('GRAPHITE_METRIC_PREFIX')
    config['graphite_report_interval'] = os.getenv('GRAPHITE_REPORT_INTERVAL')
    config['prometheus_port'] = os.getenv('PROMETHEUS_PORT')
    config['influxdb_host'] = os.getenv('INFLUXDB_HOST')
    config['influxdb_port'] = os.getenv('INFLUXDB_PORT')

    try:
        monitor = Monitor(config)
        monitor.start()

        while True:
            time.sleep(60)

    except KeyboardInterrupt:
        print("cancelling...")
    finally:
        monitor.cleanup()
Пример #12
0
class PlexObserverService(xbmcmediaimport.Observer):
    def __init__(self):
        super(xbmcmediaimport.Observer, self).__init__()

        self._monitor = Monitor()
        self._player = Player()
        self._observers = {}

        self._run()

    def _run(self):
        log('Observing Plex servers...')

        while not self._monitor.abortRequested():
            # process the player
            self._player.Process()

            # process all observers
            for observer in self._observers.values():
                observer.Process()

            if self._monitor.waitForAbort(1):
                break

        # stop all observers
        for observer in self._observers.values():
            observer.Stop()

    def _addObserver(self, mediaProvider):
        if not mediaProvider:
            raise ValueError('cannot add invalid media provider')

        self._player.AddProvider(mediaProvider)

        # check if we already know about the media provider
        mediaProviderId = mediaProvider.getIdentifier()
        if mediaProviderId in self._observers:
            return

        # create the observer
        self._observers[mediaProviderId] = ProviderObserver()

    def _removeObserver(self, mediaProvider):
        if not mediaProvider:
            raise ValueError('cannot remove invalid media provider')

        self._player.RemoveProvider(mediaProvider)

        mediaProviderId = mediaProvider.getIdentifier()
        if mediaProviderId not in self._observers:
            return

        del self._observers[mediaProviderId]

    def _startObserver(self, mediaProvider):
        if not mediaProvider:
            raise ValueError('cannot start invalid media provider')

        # make sure the media provider has been added
        self._addObserver(mediaProvider)

        # start observing the media provider
        self._observers[mediaProvider.getIdentifier()].Start(mediaProvider)

    def _stopObserver(self, mediaProvider):
        if not mediaProvider:
            raise ValueError('cannot stop invalid media provider')

        mediaProviderId = mediaProvider.getIdentifier()
        if mediaProviderId not in self._observers:
            return

        self._observers[mediaProviderId].Stop()

    def _addImport(self, mediaImport):
        if not mediaImport:
            raise ValueError('cannot add invalid media import')

        mediaProvider = mediaImport.getProvider()
        if not mediaProvider:
            raise ValueError(
                'cannot add media import {} with invalid media provider'.
                format(mediaImport2str(mediaImport)))

        mediaProviderId = mediaProvider.getIdentifier()
        if not mediaProviderId in self._observers:
            return

        self._observers[mediaProviderId].AddImport(mediaImport)

    def _removeImport(self, mediaImport):
        if not mediaImport:
            raise ValueError('cannot remove invalid media import')

        mediaProvider = mediaImport.getProvider()
        if not mediaProvider:
            raise ValueError(
                'cannot remove media import {} with invalid media provider'.
                format(mediaImport2str(mediaImport)))

        mediaProviderId = mediaProvider.getIdentifier()
        if not mediaProviderId in self._observers:
            return

        self._observers[mediaProviderId].RemoveImport(mediaImport)

    def onProviderAdded(self, mediaProvider):
        self._addObserver(mediaProvider)

    def onProviderUpdated(self, mediaProvider):
        self._addObserver(mediaProvider)

        # make sure the media provider is being observed
        if mediaProvider.isActive():
            self._startObserver(mediaProvider)
        else:
            self._stopObserver(mediaProvider)

    def onProviderRemoved(self, mediaProvider):
        self._removeObserver(mediaProvider)

    def onProviderActivated(self, mediaProvider):
        self._startObserver(mediaProvider)

    def onProviderDeactivated(self, mediaProvider):
        self._stopObserver(mediaProvider)

    def onImportAdded(self, mediaImport):
        self._addImport(mediaImport)

    def onImportUpdated(self, mediaImport):
        self._addImport(mediaImport)

    def onImportRemoved(self, mediaImport):
        self._removeImport(mediaImport)
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GUI for Temperature Monitor
from Tkinter import *
import ttk
import tkMessageBox
import threading
#from threading import Thread
from lib.monitor import Monitor
import time
import datetime

degreeChar = u'\N{DEGREE SIGN}C'
lock = threading.RLock()
m = Monitor(lock)
root = Tk()
root.wm_title("Monitor Temperatury v.0.3")
tv = [StringVar() for _ in range(8)]
frame = Frame(root)
frame.pack()
sensborder = ttk.LabelFrame(frame, text="Sensors", labelanchor=N + S)
sensborder.grid(columns=3)
dateborder = ttk.LabelFrame(frame,
                            text="Current measurement",
                            labelanchor=N + S)
dateborder.grid(columns=3)
menubar = Menu(root)
state = True
timer = [0, 0, 0]
pattern = "{0:02d}:{1:02d}:{2:02d}"
Пример #14
0
class PlexObserverService(xbmcmediaimport.Observer):
    """Class that handles observation of Plex servers for live updates"""
    def __init__(self):
        super(xbmcmediaimport.Observer, self).__init__()

        self._monitor = Monitor()
        self._player = Player()
        self._observers = {}

        self._run()

    def _run(self):
        """Begin observing configured Plex servers"""
        log('Observing Plex servers...')

        while not self._monitor.abortRequested():
            # process the player
            self._player.Process()

            # process all observers
            for observer in self._observers.values():
                observer.Process()

            if self._monitor.waitForAbort(1):
                break

        # stop all observers
        for observer in self._observers.values():
            observer.Stop()

    def _addObserver(self, mediaProvider: xbmcmediaimport.MediaProvider):
        """Register a new observer (Plex server) in the observation process

        :param mediaProvider: Plex Server MediaProvider object to observe
        :type mediaProvider: :class:`xbmcmediaimport.MediaProvider`
        """
        if not mediaProvider:
            raise ValueError('cannot add invalid media provider')

        self._player.AddProvider(mediaProvider)

        # check if we already know about the media provider
        mediaProviderId = mediaProvider.getIdentifier()
        if mediaProviderId in self._observers:
            return

        # create the observer
        self._observers[mediaProviderId] = ProviderObserver()

    def _removeObserver(self, mediaProvider: xbmcmediaimport.MediaProvider):
        """Remove a registered observer (Plex sever) from the observation process

        :param mediaProvider: Plex Server MediaProvider object to remove from observation
        :type mediaProvider: :class:`xbmcmediaimport.MediaProvider`
        """
        if not mediaProvider:
            raise ValueError('cannot remove invalid media provider')

        self._player.RemoveProvider(mediaProvider)

        mediaProviderId = mediaProvider.getIdentifier()
        if mediaProviderId not in self._observers:
            return

        del self._observers[mediaProviderId]

    def _startObserver(self, mediaProvider: xbmcmediaimport.MediaProvider):
        """Start observation on the provided MediaProvider (Plex server)

        :param mediaProvider: Plex Server MediaProvider object to observe
        :type mediaProvider: :class:`xbmcmediaimport.MediaProvider`
        """
        if not mediaProvider:
            raise ValueError('cannot start invalid media provider')

        # make sure the media provider has been added
        self._addObserver(mediaProvider)

        # start observing the media provider
        self._observers[mediaProvider.getIdentifier()].Start(mediaProvider)

    def _stopObserver(self, mediaProvider: xbmcmediaimport.MediaProvider):
        """Stp[ observation on the provided MediaProvider (Plex server)

        :param mediaProvider: Plex Server MediaProvider object to stop observation of
        :type mediaProvider: :class:`xbmcmediaimport.MediaProvider`
        """
        if not mediaProvider:
            raise ValueError('cannot stop invalid media provider')

        mediaProviderId = mediaProvider.getIdentifier()
        if mediaProviderId not in self._observers:
            return

        self._observers[mediaProviderId].Stop()

    def _addImport(self, mediaImport: xbmcmediaimport.MediaImport):
        """Add provided mediaImport task to the associated MediaProvider observer

        :param mediaImport: MediaImport task to add to provider
        :type mediaImport: :class:`xbmcmediaimport.MediaImport`
        """
        if not mediaImport:
            raise ValueError('cannot add invalid media import')

        mediaProvider = mediaImport.getProvider()
        if not mediaProvider:
            raise ValueError(
                f"cannot add media import {mediaImport2str(mediaImport)} with invalid media provider"
            )

        mediaProviderId = mediaProvider.getIdentifier()
        if mediaProviderId not in self._observers:
            return

        self._observers[mediaProviderId].AddImport(mediaImport)

    def _removeImport(self, mediaImport: xbmcmediaimport.MediaImport):
        """Remove provided mediaImport task to the associated MediaProvider observer

        :param mediaImport: MediaImport task to remove from provider
        :type mediaImport: :class:`xbmcmediaimport.MediaImport`
        """
        if not mediaImport:
            raise ValueError('cannot remove invalid media import')

        mediaProvider = mediaImport.getProvider()
        if not mediaProvider:
            raise ValueError(
                f"cannot remove media import {mediaImport2str(mediaImport)} with invalid media provider"
            )

        mediaProviderId = mediaProvider.getIdentifier()
        if mediaProviderId not in self._observers:
            return

        self._observers[mediaProviderId].RemoveImport(mediaImport)

    def onProviderAdded(self, mediaProvider: xbmcmediaimport.MediaProvider):
        """Event handler: triggered when a new provider is added to the system, register it as an observer

        :param mediaProvider: MediaProvider that was added to the system
        :type mediaProvider: :class:`xbmcmediaimport.MediaProvider`
        """
        self._addObserver(mediaProvider)

    def onProviderUpdated(self, mediaProvider: xbmcmediaimport.MediaProvider):
        """Event handler: triggered when a provider is updated in the system, make sure it is being observed

        :param mediaProvider: MediaProvider that was added to the system
        :type mediaProvider: :class:`xbmcmediaimport.MediaProvider`
        """
        self._addObserver(mediaProvider)

        # make sure the media provider is being observed
        if mediaProvider.isActive():
            self._startObserver(mediaProvider)
        else:
            self._stopObserver(mediaProvider)

    def onProviderRemoved(self, mediaProvider: xbmcmediaimport.MediaProvider):
        """Event handler: triggered when a provider is removed from the system, remove from observation

        :param mediaProvider: MediaProvider that was removed from the system
        :type mediaProvider: :class:`xbmcmediaimport.MediaProvider`
        """
        self._removeObserver(mediaProvider)

    def onProviderActivated(self,
                            mediaProvider: xbmcmediaimport.MediaProvider):
        """Event handler: triggered when a provider is actived in the system, start observation

        :param mediaProvider: MediaProvider that was actived in the system
        :type mediaProvider: :class:`xbmcmediaimport.MediaProvider`
        """
        self._startObserver(mediaProvider)

    def onProviderDeactivated(self,
                              mediaProvider: xbmcmediaimport.MediaProvider):
        """Event handler: triggered when a provider is deactived in the system, remove from observation

        :param mediaProvider: MediaProvider that was deactived in the system
        :type mediaProvider: :class:`xbmcmediaimport.MediaProvider`
        """
        self._stopObserver(mediaProvider)

    def onImportAdded(self, mediaImport: xbmcmediaimport.MediaImport):
        """Event handler: triggered when a new import task is added to the system, add to media provider

        :param mediaImport: MediaImport task added to the system
        :type mediaImport: :class:`xbmcmediaimport.MediaImport`
        """
        self._addImport(mediaImport)

    def onImportUpdated(self, mediaImport: xbmcmediaimport.MediaImport):
        """Event handler: triggered when a new import task is updated in the system, update in media provider

        :param mediaImport: MediaImport task updated in the system
        :type mediaImport: :class:`xbmcmediaimport.MediaImport`
        """
        self._addImport(mediaImport)

    def onImportRemoved(self, mediaImport: xbmcmediaimport.MediaImport):
        """Event handler: triggered when a new import task is removed from the system, remove from media provider

        :param mediaImport: MediaImport task removed from the system
        :type mediaImport: :class:`xbmcmediaimport.MediaImport`
        """
        self._removeImport(mediaImport)
Пример #15
0
 def process(self, command, debug):
     # 处理磁盘信息
     output = Monitor().net()
     return output
Пример #16
0
class DiscoveryService:
    DiscoveryAddress = '255.255.255.255'
    DiscoveryPort = 7359
    DiscoveryMessage = b'who is EmbyServer?'
    DiscoveryTimeoutS = 1.0

    def __init__(self):
        self._monitor = Monitor()
        self._sock = None
        self._servers = {}

        self._start()

    def _discover(self):
        # broadcast the discovery message
        self._sock.sendto(DiscoveryService.DiscoveryMessage,
                          (DiscoveryService.DiscoveryAddress,
                           DiscoveryService.DiscoveryPort))

        # try to receive an answer
        data = None
        try:
            self._sock.settimeout(DiscoveryService.DiscoveryTimeoutS)
            (data, _) = self._sock.recvfrom(1024)

        except socket.timeout:
            return
        except Exception as e:
            # TODO(Montellese): remove workaround for Kodi Python 3 issue
            if e.args and e.args[0] == 'timed out':
                return

            raise e

        if not data or data == DiscoveryService.DiscoveryMessage:
            return

        server = emby.api.server.Server.Discovery.fromString(data)
        if server is not None:
            self._addServer(server)

    def _addServer(self, server):
        registerServer = False

        # check if the server is already known
        if server.id not in self._servers:
            self._servers[server.id] = server
            registerServer = True
        else:
            # check if the server has already been registered or if some of its properties have changed
            if not self._servers[server.id].registered or self._servers[server.id].name != server.name or \
               self._servers[server.id].address != server.address:
                self._servers[server.id] = server
                registerServer = True
            else:
                # simply update the server's last seen property
                self._servers[server.id].lastseen = server.lastseen

        # if the server doesn't need to be registered there's nothing else to do
        if not registerServer:
            return

        providerId = Server.BuildProviderId(server.id)
        providerIconUrl = getIcon()
        mediaProvider = xbmcmediaimport.MediaProvider(
            providerId, server.name, providerIconUrl,
            emby.constants.SUPPORTED_MEDIA_TYPES)

        settings = mediaProvider.prepareSettings()
        if not settings:
            log('cannot prepare media provider settings', xbmc.LOGERROR)
            return

        ProviderSettings.SetUrl(settings, server.address)

        if xbmcmediaimport.addAndActivateProvider(mediaProvider):
            self._servers[server.id].registered = True
            log('Emby server "{}" ({}) successfully added and activated'.
                format(server.name, server.id))
        else:
            self._servers[server.id].registered = False
            log('failed to add and/or activate Emby server "{}" ({})'.format(
                server.name, server.id))

    def _expireServers(self):
        for serverId, server in iteritems(self._servers):
            if not server.isExpired(10):
                continue

            server.registered = False
            xbmcmediaimport.deactivateProvider(serverId)
            log('Emby server "{}" ({}) deactivated due to inactivity'.format(
                server.name, server.id))

    def _start(self):
        log('Looking for Emby servers...')

        # setup the UDP broadcast socket
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._sock.bind(('0.0.0.0', 0))

        while not self._monitor.abortRequested():
            # try to discover Emby servers
            self._discover()

            # expire Emby servers that haven't responded for a while
            self._expireServers()

            if self._monitor.waitForAbort(1):
                break

        self._sock.close()
Пример #17
0
    def __init__(self):
        self._monitor = Monitor()
        self._sock = None
        self._servers = {}

        self._start()
Пример #18
0
from lib.monitor import Monitor
from lib.config import Config
from lib.logger import start_printer, end_printer
import ast
import time
from datetime import datetime
import traceback

strtime = "%Y-%m-%d %H:%M:%S"
local = False

### MAIN
metadata = Config.get_variable("monitor", "metadata")
metadata = ast.literal_eval(metadata)
mc = Monitor(metadata)

start_printer("logs", datetime.now().strftime(strtime).replace(" ", "") + "_main.log")

while True:
    try:
        now = datetime.now()
        num_markets = mc.update_data()
        end = datetime.now()
        print("Updated " + str(num_markets) + " markets in " + str((end-now).total_seconds()) + " s." )
    except Exception as e: 
        print("Encountered Exception: " + str(e))
        print(traceback.format_exc())
        break

end_printer()
Пример #19
0
 def __init__(self, connect_info, process_list):
     super(Process, self).__init__()
     self.process_list = process_list
     self.server_monitor = Monitor(connect_info=connect_info)
     self.bot = telegram.Bot(token=Config.TELEGRAM_TOKEN)
     self.chat_id = Config.TELEGRAM_CHAT_ID
Пример #20
0
class DiscoveryService:
    DiscoveryAddress = '239.0.0.250'
    DiscoveryPort = 32414
    DiscoveryMessage = b'M-SEARCH * HTTP/1.1\r\n'
    DiscoveryTimeoutS = 1.0
    DiscoveryResponsePort = 32412
    DiscoveryResponse = b'200 OK'

    def __init__(self):
        self._monitor = Monitor()
        self._sock = None
        self._servers = {}

        self._start()

    def _discover(self):
        # broadcast the discovery message
        self._sock.sendto(self.DiscoveryMessage,
                          (self.DiscoveryAddress, self.DiscoveryPort))

        # try to receive an answer
        data = None
        address = None
        try:
            (data, address) = self._sock.recvfrom(1024)
        except socket.timeout:
            return  # nothing to do

        if not address or not data or not self.DiscoveryResponse in data:
            return  # nothing to do

        server = PlexServer.fromString(data, address[0])
        if not server is None:
            self._addServer(server)

    def _addServer(self, server):
        registerServer = False

        # check if the server is already known
        if not server.id in self._servers:
            self._servers[server.id] = server
            registerServer = True
        else:
            # check if the server has already been registered or if some of its properties have changed
            if not self._servers[server.id].registered or self._servers[
                    server.id].name != server.name or self._servers[
                        server.id].address != server.address:
                self._servers[server.id] = server
                registerServer = True
            else:
                # simply update the server's last seen property
                self._servers[server.id].lastseen = server.lastseen

        # if the server doesn't need to be registered there's nothing else to do
        if not registerServer:
            return

        providerId = Server.BuildProviderId(server.id)
        providerIconUrl = Server.BuildIconUrl(server.address)

        provider = xbmcmediaimport.MediaProvider(
            providerId, server.address, server.name, providerIconUrl,
            plex.constants.SUPPORTED_MEDIA_TYPES)

        # store local authentication in settings
        providerSettings = provider.prepareSettings()
        if not providerSettings:
            return None

        providerSettings.setInt(
            plex.constants.SETTINGS_PROVIDER_AUTHENTICATION,
            plex.constants.SETTINGS_PROVIDER_AUTHENTICATION_OPTION_LOCAL)
        providerSettings.save()

        if xbmcmediaimport.addAndActivateProvider(provider):
            self._servers[server.id].registered = True
            log('Plex Media Server {} successfully added and activated'.format(
                mediaProvider2str(provider)))
        else:
            self._servers[server.id].registered = False
            log('failed to add and/or activate Plex Media Server {}'.format(
                mediaProvider2str(provider)))

    def _expireServers(self):
        for serverId, server in iteritems(self._servers):
            if not server.isExpired(10):
                continue

            server.registered = False
            xbmcmediaimport.deactivateProvider(serverId)
            log('Plex Media Server "{}" ({}) deactivated due to inactivity'.
                format(server.name, server.id))

    def _start(self):
        log('Looking for Plex Media Servers...')

        # setup the UDP broadcast socket
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        ttl = struct.pack('b', 1)
        self._sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
        self._sock.settimeout(self.DiscoveryTimeoutS)

        while not self._monitor.abortRequested():
            # try to discover Plex media servers
            self._discover()

            # expire Plex media servers that haven't responded for a while
            self._expireServers()

            if self._monitor.waitForAbort(1):
                break

        self._sock.close()
Пример #21
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from lib.monitor import Monitor


if __name__ == "__main__":
    monitor = Monitor()
    monitor.run()
Пример #22
0
class DiscoveryService:
    """Class that handles discovery of Plex servers on the local network"""
    def __init__(self):
        self._monitor = Monitor()
        self._gdm = GDM()
        self._servers = {}

        self._start()

    def _discover(self):
        """Uses plexapi's GDM class to discover servers"""
        servers = self._gdm.find_by_content_type('plex/media-server')

        for server in servers:
            plexServer = PlexServer.fromData(server)
            if plexServer:
                self._addServer(plexServer)

    def _addServer(self, server: PlexServer):
        """Add a discovered PMS server as a MediaProvider to the Kodi mediaimport system

        :param server: The discovered PlexServer to add into the Kodi mediaimport system
        :type server: :class:`PlexServer`
        """
        registerServer = False

        # check if the server is already known
        if server.id not in self._servers:
            self._servers[server.id] = server
            registerServer = True
        else:
            # check if the server has already been registered or if some of its properties have changed
            if (not self._servers[server.id].registered
                    or self._servers[server.id].name != server.name
                    or self._servers[server.id].address != server.address):
                self._servers[server.id] = server
                registerServer = True
            else:
                # simply update the server's last seen property
                self._servers[server.id].lastseen = server.lastseen

        # if the server doesn't need to be registered there's nothing else to do
        if not registerServer:
            return

        providerId = Server.BuildProviderId(server.id)
        providerIconUrl = getIcon()

        provider = xbmcmediaimport.MediaProvider(
            providerId, server.name, providerIconUrl,
            plex.constants.SUPPORTED_MEDIA_TYPES)

        # store local authentication in settings
        providerSettings = provider.prepareSettings()
        if not providerSettings:
            return

        ProviderSettings.SetUrl(providerSettings, server.address)
        ProviderSettings.SetAuthenticationMethod(providerSettings, \
            plex.constants.SETTINGS_PROVIDER_AUTHENTICATION_OPTION_LOCAL)
        providerSettings.save()

        if xbmcmediaimport.addAndActivateProvider(provider):
            self._servers[server.id].registered = True
            log(
                f"Plex Media Server {mediaProvider2str(provider)} successfully added and activated",
                xbmc.LOGINFO)
        else:
            self._servers[server.id].registered = False
            log(
                f"failed to add and/or activate Plex Media Server {mediaProvider2str(provider)}",
                xbmc.LOGINFO)

    def _expireServers(self):
        """Check registered Plex servers against timeout and expire any inactive ones"""
        for serverId, server in iteritems(self._servers):
            if not server.isExpired(10):
                continue

            server.registered = False
            xbmcmediaimport.deactivateProvider(serverId)
            log(
                f"Plex Media Server '{server.name}' ({server.id}) deactivated due to inactivity",
                xbmc.LOGINFO)

    def _start(self):
        """Start the discovery and registration process"""
        log('Looking for Plex Media Servers...')

        while not self._monitor.abortRequested():
            # try to discover Plex media servers
            self._discover()

            # expire Plex media servers that haven't responded for a while
            self._expireServers()

            if self._monitor.waitForAbort(1):
                break
Пример #23
0
    def process(self, command, debug):
        # 处理磁盘信息
        monitor = Monitor()
        cpuinfo = monitor.cpu()

        return cpuinfo
Пример #24
0
    def __init__(self):
        self._monitor = Monitor()
        self._gdm = GDM()
        self._servers = {}

        self._start()
Пример #25
0
class DiscoveryService:
    class Server:
        def __init__(self):
            self.id = ""
            self.name = ""
            self.address = ""
            self.registered = False
            self.last_seen = None

        def is_expired(self, timeout_s: int):
            return self.registered and self.last_seen + timeout_s < time.time()

    def __init__(self):
        self._monitor = Monitor()
        self._servers = {}

        # TODO(stub): add additional members

        self._start()

    def _discover(self):
        server = None

        # TODO(stub): execute discovery

        if server:
            self._add_server(server)

    def _add_server(self, server: DiscoveryService.Server):  # noqa F821
        register_server = False

        # check if the server is already known
        if server.id not in self._servers:
            self._servers[server.id] = server
            register_server = True
        else:
            # check if the server has already been registered or if some of its properties have changed
            if (not self._servers[server.id].registered
                    or self._servers[server.id].name != server.name
                    or self._servers[server.id].address != server.address):
                self._servers[server.id] = server
                register_server = True
            else:
                # simply update the server"s last seen property
                self._servers[server.id].last_seen = server.last_seen

        # if the server doesn"t need to be registered there"s nothing else to do
        if not register_server:
            return

        # TODO(stub): create / determine a unique media provider identifier
        provider_id = "stub"
        # TODO(stub): determine the path to an icon for the media provider
        provider_icon_url = "stub-icon.png"
        # TODO(stub): specify which media types can be imported from the media provider
        supported_media_types = set([
            xbmcmediaimport.MediaTypeMovie,
            xbmcmediaimport.MediaTypeVideoCollection,
            xbmcmediaimport.MediaTypeMusicVideo,
            xbmcmediaimport.MediaTypeTvShow,
            xbmcmediaimport.MediaTypeSeason,
            xbmcmediaimport.MediaTypeEpisode,
        ])

        # create the media provider
        media_provider = xbmcmediaimport.MediaProvider(provider_id,
                                                       server.name,
                                                       provider_icon_url,
                                                       supported_media_types)

        # prepare / get the settings of the media provider
        settings = media_provider.prepareSettings()
        if not settings:
            log("cannot prepare media provider settings", xbmc.LOGERROR)
            return

        # TODO(stub): store the URL to the media provider in the settings
        settings.setString("stub.url", server.address)

        # add the media provider and activate it
        if xbmcmediaimport.addAndActivateProvider(media_provider):
            self._servers[server.id].registered = True
            log(f'stub server "{server.name}" ({server.id}) successfully added and activated'
                )
        else:
            self._servers[server.id].registered = False
            log(f'failed to add and/or activate stub server "{server.name}" ({server.id})'
                )

    def _expire_servers(self):
        for server_id, server in iteritems(self._servers):
            # expire the server after 10 seconds
            if not server.is_expired(10):
                continue

            server.registered = False
            xbmcmediaimport.deactivateProvider(server_id)
            log(f'stub server "{server.name}" ({server.id}) deactivated due to inactivity'
                )

    def _start(self):
        log("Looking for stub servers...")

        # TODO(stub): setup discovery

        while not self._monitor.abortRequested():
            # try to discover servers
            self._discover()

            # expire servers that haven"t responded for a while
            self._expire_servers()

            if self._monitor.waitForAbort(1):
                break
Пример #26
0
            parameter = {
                "name":
                name,
                "target":
                target_value,
                "monitor_type":
                monitor_type,
                "TLS_CERT_EXPIRATION_DATES":
                TLS_CERT_EXPIRATION_DATES if "TLS_CERT_EXPIRATION_DATES"
                in globals() else 7  # default 7 days
            }

            parameters.append(parameter)

    # generate monitors
    monitors = [Monitor(parameter) for parameter in parameters]

    # status chache table
    privious_status = {}
    for monitor in monitors:
        privious_status[str(monitor.id)] = monitor.status

    while True:
        print(
            f'[{datetime.now().strftime("%Y/%m/%d %H:%M:%S")}] Cycle start monitortargets: {len(parameters)} host'
        )

        with Pool(PROCESS_POOL) as pool:
            all_result = []
            # monitorsは各プロセス用にハードコピーされる。そのためchangedは更新されるはずがない。
            for result in pool.imap_unordered(nextCycle, monitors):
Пример #27
0
    def __init__(self, args):

        # the Bottle application
        self.app = bottle.Bottle()

        # the base root from which to serve files
        #  (mako needs a string, not a Path() object).
        self.base_root = str(args.base_root.resolve())
        self.base_url = re.sub(r"/+", "/", "/{0}/".format(args.base_url))

        self.assets_dir = args.assets_dir

        if "private" in args:
            self.PRIVATE_FILES = self.PRIVATE_FILES + tuple(
                re.compile(_) for _ in args.private.split(","))

        # the TemplateLookup of Mako
        self.templates = TemplateLookup(
            directories=[self.base_root],
            imports=[
                "from markdown import markdown",
                "from lib.typogrify import amp, caps, initial_quotes,"
                "    smartypants, titlecase, typogrify, widont",
                "from lib.decorators import css, js",
            ],
            input_encoding="UTF8",
            collection_size=100,
            default_filters=["trim"],
        )

        self.context = {
            "base_url": self.base_url.rstrip("/"),
            "base_root": Path(self.base_root),
            "assets_dir": self.assets_dir,
            "output_root": self.base_root,
            "compress": False,
        }

        # establish routing config for bottle
        self.app.route("{0}<path:path>".format(self.base_url),
                       method="GET",
                       callback=self.render)
        self.app.route(self.base_url,
                       method="GET",
                       callback=lambda: self.render("index.html"))

        # if there's a 404.html file in the root folder, render this for
        #  404 responses (this returns the wrong response code, of course,
        #  but there's no point in modifying this on a dev-only server).
        if os.path.isfile(os.path.join(self.base_root, "404.html")):
            self.app.error(404)(lambda err: self.render("404.html"))

        # prep the simple WSGI server (could use waitress here, but the extra
        #  dependency is not really necessary for dev-only purposes).
        self.server = make_server(args.host, args.port, self,
                                  ThreadingWSGIServer)

        def restart(modified_path, base_dir=os.getcwd()):
            """automatically restart the server if changes are made to python
            files on this path."""
            self.server.server_close()
            self.server.shutdown()
            logging.info("change detected to '%s' -- restarting server",
                         modified_path)
            args = sys.argv[:]
            args.insert(0, sys.executable)
            os.chdir(base_dir)
            os.execv(sys.executable, args)

        monitor = Monitor(interval=1.0)
        if args.ini_file is not None:
            monitor.track(
                str(Path(os.path.expanduser(args.ini_file)).resolve()))
        monitor.on_modified = restart
Пример #28
0
class ObserverService(xbmcmediaimport.Observer):
    def __init__(self):
        super(xbmcmediaimport.Observer, self).__init__()

        self._monitor = Monitor()
        self._observers = {}

        # TODO(stub): add additional members

        self._run()

    def _run(self):
        log("Observing stub media providers...")

        while not self._monitor.abortRequested():
            # process all observers
            for observer in self._observers.values():
                observer.Process()

            # TODO(stub): perform additional processing (e.g. player interaction / callbacks)

            if self._monitor.waitForAbort(1):
                break

        # stop all observers
        for observer in self._observers.values():
            observer.Stop()

    def _add_observer(self, media_provider: xbmcmediaimport.MediaProvider):
        if not media_provider:
            raise ValueError("cannot add invalid media provider")

        self._player.AddProvider(media_provider)

        # check if we already know about the media provider
        media_provider_id = media_provider.getIdentifier()
        if media_provider_id in self._observers:
            return

        # create the observer
        self._observers[media_provider_id] = ProviderObserver()

    def _remove_observer(self, media_provider: xbmcmediaimport.MediaProvider):
        if not media_provider:
            raise ValueError("cannot remove invalid media provider")

        self._player.RemoveProvider(media_provider)

        media_provider_id = media_provider.getIdentifier()
        if media_provider_id not in self._observers:
            return

        del self._observers[media_provider_id]

    def _start_observer(self, media_provider: xbmcmediaimport.MediaProvider):
        if not media_provider:
            raise ValueError("cannot start invalid media provider")

        # make sure the media provider has been added
        self._add_observer(media_provider)

        # start observing the media provider
        self._observers[media_provider.getIdentifier()].start(media_provider)

    def _stop_observer(self, media_provider: xbmcmediaimport.MediaProvider):
        if not media_provider:
            raise ValueError("cannot stop invalid media provider")

        media_provider_id = media_provider.getIdentifier()
        if media_provider_id not in self._observers:
            return

        self._observers[media_provider_id].stop()

    def _add_import(self, media_import: xbmcmediaimport.MediaImport):
        if not media_import:
            raise ValueError("cannot add invalid media import")

        media_provider = media_import.getProvider()
        if not media_provider:
            raise ValueError(
                f"cannot add media import {import2str(media_import)} with invalid media provider"
            )

        media_provider_id = media_provider.getIdentifier()
        if media_provider_id not in self._observers:
            return

        self._observers[media_provider_id].add_import(media_import)

    def _remove_import(self, media_import: xbmcmediaimport.MediaImport):
        if not media_import:
            raise ValueError("cannot remove invalid media import")

        media_provider = media_import.getProvider()
        if not media_provider:
            raise ValueError(
                f"cannot remove media import {import2str(media_import)} with invalid media provider"
            )

        media_provider_id = media_provider.getIdentifier()
        if media_provider_id not in self._observers:
            return

        self._observers[media_provider_id].remove_import(media_import)

    def onProviderAdded(self, media_provider: xbmcmediaimport.MediaProvider):
        self._add_observer(media_provider)

    def onProviderUpdated(self, media_provider: xbmcmediaimport.MediaProvider):
        self._add_observer(media_provider)

        # make sure the media provider is being observed
        if media_provider.isActive():
            self._start_observer(media_provider)
        else:
            self._stop_observer(media_provider)

    def onProviderRemoved(self, media_provider: xbmcmediaimport.MediaProvider):
        self._remove_observer(media_provider)

    def onProviderActivated(self,
                            media_provider: xbmcmediaimport.MediaProvider):
        self._start_observer(media_provider)

    def onProviderDeactivated(self,
                              media_provider: xbmcmediaimport.MediaProvider):
        self._stop_observer(media_provider)

    def onImportAdded(self, media_import: xbmcmediaimport.MediaImport):
        self._add_import(media_import)

    def onImportUpdated(self, media_import: xbmcmediaimport.MediaImport):
        self._add_import(media_import)

    def onImportRemoved(self, media_import: xbmcmediaimport.MediaImport):
        self._remove_import(media_import)