summaryrefslogtreecommitdiff
path: root/sublab_project/sublab_monitor/tasks.py
blob: 982b0a328918828fd57c42d631e0765949a5b75c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""Celery tasks.
"""
from datetime import timedelta
from celery.task import PeriodicTask
import subprocess
import urllib2
import urlparse
from PIL import Image, ImageOps
from StringIO import StringIO
from django.conf import settings
import os
import re

import sublab_monitor

class NetworkStatus(PeriodicTask):
    """Periodic task for getting sublab network status
    """
    hosts = {
            'taifun': '172.22.83.5',
            'trieste': '172.22.80.4',
            'nautilus': '172.22.80.7',
    }
    run_every = timedelta(minutes=2)
    ignore_result = True

    @staticmethod
    def host_alive(host):
        rc = subprocess.call(['ping', '-c', '2', '-W', '1', host])

        if rc == 0:
            return True
        else:
            return False

    def run(self, **kwargs):
        """Ping all the hosts.
        """
        self.logger = self.get_logger(**kwargs)

        results = {}
        for host, target in self.hosts.items():
            results[host] = self.host_alive(target)

        storage = sublab_monitor.Storage('network_status')
        for host, status in results.items():
            storage.set(host, status)

        return repr(results)


class ImageFetcher(object):
    """
    A task mixin which downloads, processes and stores an Image
    """

    @property
    def fetch_url(self):
        """
        The location from which the image should be fetched
        """
        raise NotImplementedError

    @property
    def store_name(self):
        """
        The name under which the image should be stored
        """
        raise NotImplementedError

    def process_image(self, image):
        """
        This method may be overwritten to perform some
        processing on the image
        """
        raise NotImplementedError

    def replace_file(self, filename, save):
        fn = os.path.join(settings.MEDIA_ROOT, filename)
        fn_new = os.path.join(settings.MEDIA_ROOT, 'new-%s' % filename)

        save(fn_new)
        os.rename(fn_new ,fn)

    def run(self, **kwargs):
        upstream = urllib2.urlopen(self.fetch_url).read()
        image = Image.open(StringIO(upstream))

        try:
            image = self.process_image(image)
        except NotImplementedError:
            pass

        self.replace_file(self.store_name, image.save)

        if image.mode.upper() == 'RGBA':
            image = Image.composite(image, Image.new("RGB", image.size, (255,255,255)), image)
            image.convert("RGB")

        image.thumbnail((180, 180), Image.ANTIALIAS)
        self.replace_file('thumb_' + self.store_name, image.save)

        return 'Done.'

class EnhancingImageFetcher(ImageFetcher):
    def process_image(self, image):
        rv = ImageOps.autocontrast(image)
        rv.im = ImageOps.unsharp_mask(rv, 10.0, 40, 7)

        return rv


class KarlHeineCamFetcher(EnhancingImageFetcher, PeriodicTask):
    run_every = timedelta(minutes=5)
    fetch_url = 'http://taifun.local.sublab.org/webcam.jpg'
    store_name = 'karlheine_cam.jpg'


class TempGraphFetcher(ImageFetcher, PeriodicTask):
    run_every = timedelta(minutes=5)
    fetch_url = 'http://taifun.local.sublab.org/temperature/temp-2hour.png'
    store_name = 'tempgraph.png'

class ReeknerSprookTempFetcher(ImageFetcher, PeriodicTask):
    run_every = timedelta(minutes=5)
    store_name = 'reeknersprook.png'

    @property
    def fetch_url(self):
        url = 'http://reeknersprook.de/sublog/graph-small'
        buf = urllib2.urlopen(url).read()
        rel = re.search(r'src="(.*?)"', buf).group(1)

        return urlparse.urljoin(url, rel)