管理进程启动

@param  \Swoole\Server   $server
351951
public function onManagerStart(SwServer $server)
    {
        // {{
        $this->setRunUser();
        $this->setProcessName('manager');
        // }}

        // {{ log
        $this->get('logger')->info('启动 Manager 进程', [
            'pid' => $server->manager_pid
        ]);
        // }}
    }
673221
static function getServer(array $servers)
    {
        $weight = 0;
        //移除不在线的节点
        foreach ($servers as $k => $svr)
        {
            //节点已掉线
            if (!empty($svr['status']) and $svr['status'] == 'offline')
            {
                unset($servers[$k]);
            }
            else
            {
                $weight += $svr['weight'];
            }
        }
        //计算权重并随机选择一台机器
        $use = rand(0, $weight - 1);
        $weight = 0;
        foreach ($servers as $k => $svr)
        {
            //默认100权重
            if (empty($svr['weight']))
            {
                $svr['weight'] = 100;
            }
            $weight += $svr['weight'];
            //在权重范围内
            if ($use < $weight)
            {
                return $svr;
            }
        }
        //绝不会到这里
        $servers = array_values($servers);
        return $servers[0];
    }
389018
public function initialize(Server $server)
    {
        $this->server = $server;
        $server->on('method:GET', [$this, 'httpGet'], 90);
        $server->on('propFind', [$this, 'propFind']);

        $server->xml->namespaceMap[self::NS_CALENDARSERVER] = 'cs';
        $server->resourceTypeMapping['\\Sabre\\CalDAV\\Notifications\\ICollection'] = '{'.self::NS_CALENDARSERVER.'}notification';

        array_push($server->protectedProperties,
            '{'.self::NS_CALENDARSERVER.'}notification-URL',
            '{'.self::NS_CALENDARSERVER.'}notificationtype'
        );
    }
391720
public function initialize(DAV\Server $server)
    {
        $this->server = $server;

        $server->on('method:MKCALENDAR', [$this, 'httpMkCalendar']);
        $server->on('report', [$this, 'report']);
        $server->on('propFind', [$this, 'propFind']);
        $server->on('onHTMLActionsPanel', [$this, 'htmlActionsPanel']);
        $server->on('beforeCreateFile', [$this, 'beforeCreateFile']);
        $server->on('beforeWriteContent', [$this, 'beforeWriteContent']);
        $server->on('afterMethod:GET', [$this, 'httpAfterGET']);
        $server->on('getSupportedPrivilegeSet', [$this, 'getSupportedPrivilegeSet']);

        $server->xml->namespaceMap[self::NS_CALDAV] = 'cal';
        $server->xml->namespaceMap[self::NS_CALENDARSERVER] = 'cs';

        $server->xml->elementMap['{'.self::NS_CALDAV.'}supported-calendar-component-set'] = 'Sabre\\CalDAV\\Xml\\Property\\SupportedCalendarComponentSet';
        $server->xml->elementMap['{'.self::NS_CALDAV.'}calendar-query'] = 'Sabre\\CalDAV\\Xml\\Request\\CalendarQueryReport';
        $server->xml->elementMap['{'.self::NS_CALDAV.'}calendar-multiget'] = 'Sabre\\CalDAV\\Xml\\Request\\CalendarMultiGetReport';
        $server->xml->elementMap['{'.self::NS_CALDAV.'}free-busy-query'] = 'Sabre\\CalDAV\\Xml\\Request\\FreeBusyQueryReport';
        $server->xml->elementMap['{'.self::NS_CALDAV.'}mkcalendar'] = 'Sabre\\CalDAV\\Xml\\Request\\MkCalendar';
        $server->xml->elementMap['{'.self::NS_CALDAV.'}schedule-calendar-transp'] = 'Sabre\\CalDAV\\Xml\\Property\\ScheduleCalendarTransp';
        $server->xml->elementMap['{'.self::NS_CALDAV.'}supported-calendar-component-set'] = 'Sabre\\CalDAV\\Xml\\Property\\SupportedCalendarComponentSet';

        $server->resourceTypeMapping['\\Sabre\\CalDAV\\ICalendar'] = '{urn:ietf:params:xml:ns:caldav}calendar';

        $server->resourceTypeMapping['\\Sabre\\CalDAV\\Principal\\IProxyRead'] = '{http://calendarserver.org/ns/}calendar-proxy-read';
        $server->resourceTypeMapping['\\Sabre\\CalDAV\\Principal\\IProxyWrite'] = '{http://calendarserver.org/ns/}calendar-proxy-write';

        array_push($server->protectedProperties,
            '{'.self::NS_CALDAV.'}supported-calendar-component-set',
            '{'.self::NS_CALDAV.'}supported-calendar-data',
            '{'.self::NS_CALDAV.'}max-resource-size',
            '{'.self::NS_CALDAV.'}min-date-time',
            '{'.self::NS_CALDAV.'}max-date-time',
            '{'.self::NS_CALDAV.'}max-instances',
            '{'.self::NS_CALDAV.'}max-attendees-per-instance',
            '{'.self::NS_CALDAV.'}calendar-home-set',
            '{'.self::NS_CALDAV.'}supported-collation-set',
            '{'.self::NS_CALDAV.'}calendar-data',

            // CalendarServer extensions
            '{'.self::NS_CALENDARSERVER.'}getctag',
            '{'.self::NS_CALENDARSERVER.'}calendar-proxy-read-for',
            '{'.self::NS_CALENDARSERVER.'}calendar-proxy-write-for'
        );

        if ($aclPlugin = $server->getPlugin('acl')) {
            $aclPlugin->principalSearchPropertySet['{'.self::NS_CALDAV.'}calendar-user-address-set'] = 'Calendar address';
        }
    }
1058023
public function getServer($server)
    {
        if (! array_key_exists($server, $this->servers)) {
            throw new \Exception('Server ['.$server.'] is not defined.');
        }

        return Arr::get($this->servers, $server);
    }
192930
private function executeCommand(Server $server)
    {
        $cmd = ['listIndexes' => $this->collectionName];

        if (isset($this->options['maxTimeMS'])) {
            $cmd['maxTimeMS'] = $this->options['maxTimeMS'];
        }

        try {
            $cursor = $server->executeCommand($this->databaseName, new Command($cmd), $this->createOptions());
        } catch (DriverRuntimeException $e) {
            /* The server may return an error if the collection does not exist.
             * Check for possible error codes (see: SERVER-20463) and return an
             * empty iterator instead of throwing.
             */
            if ($e->getCode() === self::$errorCodeNamespaceNotFound || $e->getCode() === self::$errorCodeDatabaseNotFound) {
                return new IndexInfoIteratorIterator(new EmptyIterator);
            }

            throw $e;
        }

        $cursor->setTypeMap(['root' => 'array', 'document' => 'array']);

        return new IndexInfoIteratorIterator(new CachingIterator($cursor));
    }
877744
public function onFinish(SwServer $server, int $taskId, $data)
    {
        // {{
        $this->get('task')->onFinish($server, $taskId, $data);
        // }}

        // {{ log
        $this->get('logger')->info('结束任务', [
            'id' => $taskId,
            'data' => is_array($data) ? json_encode($data) : $data
        ]);
        // }}
    }
1134183
public function beforeSend(Server $server)
    {

        // Build the server code
        $this->server_code = implode('', array_map('chr', explode('.', $server->ip()))) .
                             pack("S", $server->portClient());

        // Loop over the packets and update them
        foreach ($this->packets as $packetType => $packet) {
            // Fill out the packet with the server info
            $this->packets[$packetType] = sprintf($packet, $this->server_code);
        }
    }
702092
public function execute(Server $server)
    {
        $cmd = ['listDatabases' => 1];

        if ( ! empty($this->options['filter'])) {
            $cmd['filter'] = (object) $this->options['filter'];
        }

        if (isset($this->options['maxTimeMS'])) {
            $cmd['maxTimeMS'] = $this->options['maxTimeMS'];
        }

        $cursor = $server->executeCommand('admin', new Command($cmd), $this->createOptions());
        $cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
        $result = current($cursor->toArray());

        if ( ! isset($result['databases']) || ! is_array($result['databases'])) {
            throw new UnexpectedValueException('listDatabases command did not return a "databases" array');
        }

        /* Return an Iterator instead of an array in case listDatabases is
         * eventually changed to return a command cursor, like the collection
         * and index enumeration commands. This makes the "totalSize" command
         * field inaccessible, but users can manually invoke the command if they
         * need that value.
         */
        return new DatabaseInfoLegacyIterator($result['databases']);
    }
929203
public function onShutdown(swoole_server $server)
    {
        if (file_exists($this->pidFile)) {
            unlink($this->pidFile);
        }

        $this->console(sprintf('Server <info>%s</info> Master[<info>%s</info>] is shutdown ', $this->name, $server->master_pid), OutputInterface::VERBOSITY_DEBUG);
    }
1334560
public static function workerStartApp($server, $target)
    {
        if(!static::$workerStartAppComplete)
        {
            // 触发项目的workerstart事件
            Event::trigger('IMI.MAIN_SERVER.WORKER.START.APP', [
                'server'    => $server,
                'workerID'  => static::$workerID,
            ], $target, WorkerStartEventParam::class);
            static::$workerStartAppComplete = true;
        }
    }
865372
public function execute(Server $server)
    {
        $inTransaction = isset($this->options['session']) && $this->options['session']->isInTransaction();
        if ($inTransaction && isset($this->options['writeConcern'])) {
            throw UnsupportedException::writeConcernNotSupportedInTransaction();
        }

        $options = ['ordered' => $this->options['ordered']];

        if (
            ! empty($this->options['bypassDocumentValidation']) &&
            \MongoDB\server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)
        ) {
            $options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
        }

        $bulk = new Bulk($options);
        $insertedIds = [];

        foreach ($this->documents as $i => $document) {
            $insertedIds[$i] = $bulk->insert($document);
        }

        $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $this->createOptions());

        return new InsertManyResult($writeResult, $insertedIds);
    }
788282
private function executeCommand(Server $server)
    {
        $cmd = [
            'createIndexes' => $this->collectionName,
            'indexes' => $this->indexes,
        ];

        if (isset($this->options['maxTimeMS'])) {
            $cmd['maxTimeMS'] = $this->options['maxTimeMS'];
        }

        $server->executeWriteCommand($this->databaseName, new Command($cmd), $this->createOptions());
    }
885321
public function bindSwooleServerEvents($server)
    {
        $bindersMap = $this->getBinders();

        foreach ($bindersMap as $event => $handler) {
            $server->on($event, $handler);
        }

        return $this;
    }
288336
function dispatch(\swoole_server $server ,string $data, ...$args):void
    {
        $clientIp = null;
        $type = $this->config->getType();
        switch ($type){
            case Config::TCP:{
                $client = new Tcp( ...$args);
                break;
            }
            case Config::WEB_SOCKET:{
                $client = new WebSocket( ...$args);
                break;
            }
            case Config::UDP:{
                $client = new Udp( ...$args);
                break;
            }
            default:{
                throw new \Exception('dispatcher type error : '.$type);
            }
        }
        $caller = null;
        $response = new Response();
        try{
            $caller = $this->config->getParser()->decode($data,$client);
        }catch (\Throwable $throwable){
            //注意，在解包出现异常的时候，则调用异常处理，默认是断开连接，服务端抛出异常
            $this->hookException($server,$throwable,$data,$client,$response);
            goto response;
        }
        //如果成功返回一个调用者，那么执行调用逻辑
        if($caller instanceof Caller){
            $caller->setClient($client);
            //解包正确
            $controllerClass = $caller->getControllerClass();
            try{
                $controller = $this->getController($controllerClass);
            }catch (\Throwable $throwable){
                $this->hookException($server,$throwable,$data,$client,$response);
                goto response;
            }
            if($controller instanceof Controller){
                try{
                    $controller->__hook( $server,$this->config, $caller, $response);
                }catch (\Throwable $throwable){
                    $this->hookException($server,$throwable,$data,$client,$response);
                }finally {
                    $this->recycleController($controllerClass,$controller);
                }
            }else{
                $throwable = new ControllerPoolEmpty('controller pool empty for '.$controllerClass);
                $this->hookException($server,$throwable,$data,$client,$response);
            }
        }
        response :{
            switch ($response->getStatus()){
                case Response::STATUS_OK:{
                    $this->response($server,$client,$response);
                    break;
                }
                case Response::STATUS_RESPONSE_AND_CLOSE:{
                    $this->response($server,$client,$response);
                    $this->close($server,$client);
                    break;
                }
                case Response::STATUS_CLOSE:{
                    $this->close($server,$client);
                    break;
                }
            }
        }
    }
271974
public function initialize(Server $server)
    {
        $server->resourceTypeMapping['Sabre\\CalDAV\\Subscriptions\\ISubscription'] =
            '{http://calendarserver.org/ns/}subscribed';

        $server->xml->elementMap['{http://calendarserver.org/ns/}source'] =
            'Sabre\\DAV\\Xml\\Property\\Href';

        $server->on('propFind', [$this, 'propFind'], 150);
    }
398511
public function userMapping($server)
    {
        foreach (['userName', 'firstName', 'lastName', 'email'] as $field) {
            if (!(isset($server[$field]) && '' !== $server[$field])) {
                return false;
            }
        }

        return true;
    }