AppServiceProvider.php 2.38 KB
Newer Older
Dominik Hebeler's avatar
Dominik Hebeler committed
1 2 3 4
<?php

namespace App\Providers;

5 6
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
7 8 9
use Illuminate\Support\ServiceProvider;
use Queue;
use Redis;
Dominik Hebeler's avatar
Dominik Hebeler committed
10 11 12 13 14 15 16 17 18 19

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
20 21 22
        # Wir loggen im Redis-System für jede Sekunde des Tages, wie viele Worker aktiv am Laufen waren.
        # Dies ist notwendig, damit wir mitbekommen können, ab welchem Zeitpunkt wir zu wenig Worker zur Verfügung haben.
        Queue::before(function (JobProcessing $event) {
23
            $this->begin = strtotime(date(DATE_RFC822, mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"))));
24 25
        });
        Queue::after(function (JobProcessed $event) {
26 27 28 29
            $today    = strtotime(date(DATE_RFC822, mktime(0, 0, 0, date("m"), date("d"), date("Y"))));
            $end      = strtotime(date(DATE_RFC822, mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y")))) - $today;
            $expireAt = strtotime(date(DATE_RFC822, mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"))));
            try {
30
                $redis = Redis::connection('redisLogs');
31
                if (!$redis) {
32
                    return;
33 34 35 36
                }

                $p     = getmypid();
                $host  = gethostname();
37
                $begin = $this->begin - $today;
38 39
                $redis->pipeline(function ($pipe) use ($p, $expireAt, $host, $begin, $end) {
                    for ($i = $begin; $i <= $end; $i++) {
40 41 42 43
                        $pipe->sadd("logs.worker.$host.$i", strval($p));
                        $pipe->expire("logs.worker.$host.$i", 10);
                        $pipe->eval("redis.call('hset', 'logs.worker.$host', '$i', redis.call('scard', 'logs.worker.$host.$i'))", 0);
                        $pipe->sadd("logs.worker", $host);
44
                        if (date("H") !== 0) {
45 46 47
                            $pipe->expire("logs.worker.$host", $expireAt);
                            $pipe->expire("logs.worker", $expireAt);
                        }
48
                    }
49
                });
50
            } catch (\Exception $e) {
51 52
                return;
            }
53
        });
Dominik Hebeler's avatar
Dominik Hebeler committed
54 55 56 57 58 59 60 61 62 63 64 65
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}