Blame view

trunk/src/app/srs_app_server.cpp 12.5 KB
winlin authored
1 2 3
/*
The MIT License (MIT)
4
Copyright (c) 2013-2014 winlin
winlin authored
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
24
#include <srs_app_server.hpp>
winlin authored
25 26 27 28 29

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
winlin authored
30 31 32
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
winlin authored
33 34 35

#include <algorithm>
36
#include <srs_kernel_log.hpp>
37
#include <srs_kernel_error.hpp>
38
#include <srs_app_rtmp_conn.hpp>
39
#include <srs_app_config.hpp>
40
#include <srs_kernel_utility.hpp>
winlin authored
41
42
#define SERVER_LISTEN_BACKLOG 512
winlin authored
43 44 45 46
#define SRS_TIME_RESOLUTION_MS 500

SrsListener::SrsListener(SrsServer* _server, SrsListenerType _type)
{
47 48 49 50 51 52
    fd = -1;
    stfd = NULL;
    
    port = 0;
    server = _server;
    type = _type;
53
54
    pthread = new SrsThread(this, 0);
winlin authored
55 56 57 58
}

SrsListener::~SrsListener()
{
59 60 61 62 63 64 65 66
    srs_close_stfd(stfd);
    
    pthread->stop();
    srs_freep(pthread);
    
    // st does not close it sometimes, 
    // close it manually.
    close(fd);
winlin authored
67 68 69 70
}

int SrsListener::listen(int _port)
{
71 72 73 74 75
    int ret = ERROR_SUCCESS;
    
    port = _port;
    
    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
winlin authored
76 77 78
        ret = ERROR_SOCKET_CREATE;
        srs_error("create linux socket error. ret=%d", ret);
        return ret;
79 80
    }
    srs_verbose("create linux socket success. fd=%d", fd);
winlin authored
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
    
    int reuse_socket = 1;
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_socket, sizeof(int)) == -1) {
        ret = ERROR_SOCKET_SETREUSE;
        srs_error("setsockopt reuse-addr error. ret=%d", ret);
        return ret;
    }
    srs_verbose("setsockopt reuse-addr success. fd=%d", fd);
    
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;
    if (bind(fd, (const sockaddr*)&addr, sizeof(sockaddr_in)) == -1) {
        ret = ERROR_SOCKET_BIND;
        srs_error("bind socket error. ret=%d", ret);
        return ret;
    }
    srs_verbose("bind socket success. fd=%d", fd);
    
    if (::listen(fd, SERVER_LISTEN_BACKLOG) == -1) {
        ret = ERROR_SOCKET_LISTEN;
        srs_error("listen socket error. ret=%d", ret);
        return ret;
    }
    srs_verbose("listen socket success. fd=%d", fd);
    
    if ((stfd = st_netfd_open_socket(fd)) == NULL){
        ret = ERROR_ST_OPEN_SOCKET;
        srs_error("st_netfd_open_socket open socket failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("st open socket success. fd=%d", fd);
    
115
    if ((ret = pthread->start()) != ERROR_SUCCESS) {
winlin authored
116 117 118 119 120
        srs_error("st_thread_create listen thread error. ret=%d", ret);
        return ret;
    }
    srs_verbose("create st listen thread success.");
    
121
    srs_trace("server started, listen at port=%d, type=%d, fd=%d", port, type, fd);
122 123
    
    return ret;
winlin authored
124 125
}
126
void SrsListener::on_enter_loop()
winlin authored
127
{
128
    srs_trace("listen cycle start, port=%d, type=%d, fd=%d", port, type, fd);
winlin authored
129 130
}
131
int SrsListener::cycle()
winlin authored
132
{
133 134
    int ret = ERROR_SUCCESS;
    
135 136 137 138 139 140 141 142
    st_netfd_t client_stfd = st_accept(stfd, NULL, NULL, ST_UTIME_NO_TIMEOUT);
    
    if(client_stfd == NULL){
        // ignore error.
        srs_warn("ignore accept thread stoppped for accept client error");
        return ret;
    }
    srs_verbose("get a client. fd=%d", st_netfd_fileno(client_stfd));
143 144 145 146 147 148 149 150 151
    
    if ((ret = server->accept_client(type, client_stfd)) != ERROR_SUCCESS) {
        srs_warn("accept client error. ret=%d", ret);
        return ret;
    }
    
    srs_verbose("accept client finished. conns=%d, ret=%d", (int)conns.size(), ret);
    
    return ret;
winlin authored
152 153 154 155
}

SrsServer::SrsServer()
{
156 157 158 159 160
    signal_reload = false;
    signal_gmc_stop = false;
    
    srs_assert(_srs_config);
    _srs_config->subscribe(this);
winlin authored
161 162 163 164
}

SrsServer::~SrsServer()
{
165 166 167 168 169 170 171 172 173 174 175 176
    _srs_config->unsubscribe(this);
    
    if (true) {
        std::vector<SrsConnection*>::iterator it;
        for (it = conns.begin(); it != conns.end(); ++it) {
            SrsConnection* conn = *it;
            srs_freep(conn);
        }
        conns.clear();
    }
    
    close_listeners();
winlin authored
177 178 179 180
}

int SrsServer::initialize()
{
181 182
    int ret = ERROR_SUCCESS;
    return ret;
winlin authored
183 184
}
winlin authored
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
int SrsServer::acquire_pid_file()
{
    int ret = ERROR_SUCCESS;
    
    std::string pid_file = _srs_config->get_pid_file();
    
    // -rw-r--r-- 
    // 644
    int mode = S_IRUSR | S_IWUSR |  S_IRGRP | S_IROTH;
    
    int fd;
    // open pid file
    if ((fd = ::open(pid_file.c_str(), O_WRONLY | O_CREAT, mode)) < 0) {
        ret = ERROR_SYSTEM_PID_ACQUIRE;
        srs_error("open pid file %s error, ret=%#x", pid_file.c_str(), ret);
        return ret;
    }
    
    // require write lock
    flock lock;

    lock.l_type = F_WRLCK; // F_RDLCK, F_WRLCK, F_UNLCK
    lock.l_start = 0; // type offset, relative to l_whence
    lock.l_whence = SEEK_SET;  // SEEK_SET, SEEK_CUR, SEEK_END
    lock.l_len = 0;
    
    if (fcntl(fd, F_SETLK, &lock) < 0) {
        if(errno == EACCES || errno == EAGAIN) {
            ret = ERROR_SYSTEM_PID_ALREADY_RUNNING;
            srs_error("srs is already running! ret=%#x", ret);
            return ret;
        }
        
        ret = ERROR_SYSTEM_PID_LOCK;
        srs_error("require lock for file %s error! ret=%#x", pid_file.c_str(), ret);
        return ret;
    }

    // truncate file
    if (ftruncate(fd, 0) < 0) {
        ret = ERROR_SYSTEM_PID_TRUNCATE_FILE;
        srs_error("truncate pid file %s error! ret=%#x", pid_file.c_str(), ret);
        return ret;
    }

    int pid = (int)getpid();
    
    // write the pid
    char buf[512];
    snprintf(buf, sizeof(buf), "%d", pid);
    if (write(fd, buf, strlen(buf)) != (int)strlen(buf)) {
        ret = ERROR_SYSTEM_PID_WRITE_FILE;
        srs_error("write our pid error! pid=%d file=%s ret=%#x", pid, pid_file.c_str(), ret);
        return ret;
    }

    // auto close when fork child process.
    int val;
    if ((val = fcntl(fd, F_GETFD, 0)) < 0) {
        ret = ERROR_SYSTEM_PID_GET_FILE_INFO;
        srs_error("fnctl F_GETFD error! file=%s ret=%#x", pid_file.c_str(), ret);
        return ret;
    }
    val |= FD_CLOEXEC;
    if (fcntl(fd, F_SETFD, val) < 0) {
        ret = ERROR_SYSTEM_PID_SET_FILE_INFO;
        srs_error("fcntl F_SETFD error! file=%s ret=%#x", pid_file.c_str(), ret);
        return ret;
    }
    
    srs_trace("write pid=%d to %s success!", pid, pid_file.c_str());
    
    return ret;
}
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
int SrsServer::initialize_st()
{
    int ret = ERROR_SUCCESS;
    
    // use linux epoll.
    if (st_set_eventsys(ST_EVENTSYS_ALT) == -1) {
        ret = ERROR_ST_SET_EPOLL;
        srs_error("st_set_eventsys use linux epoll failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("st_set_eventsys use linux epoll success");
    
    if(st_init() != 0){
        ret = ERROR_ST_INITIALIZE;
        srs_error("st_init failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("st_init success");
    
    // set current log id.
    _srs_context->generate_id();
    srs_info("log set id success");
    
    return ret;
}
winlin authored
286 287
int SrsServer::listen()
{
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    int ret = ERROR_SUCCESS;
    
    SrsConfDirective* conf = NULL;
    
    // stream service port.
    conf = _srs_config->get_listen();
    srs_assert(conf);
    
    close_listeners();
    
    for (int i = 0; i < (int)conf->args.size(); i++) {
        SrsListener* listener = new SrsListener(this, SrsListenerStream);
        listeners.push_back(listener);
        
        int port = ::atoi(conf->args.at(i).c_str());
        if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
            srs_error("RTMP stream listen at port %d failed. ret=%d", port, ret);
            return ret;
        }
    }
    
    if (_srs_config->get_http_api_enabled()) {
        SrsListener* listener = new SrsListener(this, SrsListenerHttpApi);
        listeners.push_back(listener);
        
        int port = _srs_config->get_http_api_listen();
        if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
            srs_error("HTTP api listen at port %d failed. ret=%d", port, ret);
            return ret;
        }
    }
    
    if (_srs_config->get_http_stream_enabled()) {
        SrsListener* listener = new SrsListener(this, SrsListenerHttpStream);
        listeners.push_back(listener);
        
        int port = _srs_config->get_http_stream_listen();
        if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
            srs_error("HTTP stream listen at port %d failed. ret=%d", port, ret);
327 328 329 330 331
            return ret;
        }
    }
    
    return ret;
winlin authored
332 333 334 335
}

int SrsServer::cycle()
{
336 337 338 339 340 341 342
    int ret = ERROR_SUCCESS;
    
    // the deamon thread, update the time cache
    while (true) {
        st_usleep(SRS_TIME_RESOLUTION_MS * 1000);
        srs_update_system_time_ms();
        
343 344 345
// for gperf heap checker,
// @see: research/gperftools/heap-checker/heap_checker.cc
// if user interrupt the program, exit to check mem leak.
346 347 348
// but, if gperf, use reload to ensure main return normally,
// because directly exit will cause core-dump.
#ifdef SRS_GPERF_MC
349 350 351
        if (signal_gmc_stop) {
            break;
        }
352
#endif
353 354 355 356 357 358 359 360 361 362 363 364 365 366
        
        if (signal_reload) {
            signal_reload = false;
            srs_info("get signal reload, to reload the config.");
            
            if ((ret = _srs_config->reload()) != ERROR_SUCCESS) {
                srs_error("reload config failed. ret=%d", ret);
                return ret;
            }
            srs_trace("reload config success.");
        }
    }
    
    return ret;
winlin authored
367 368 369 370
}

void SrsServer::remove(SrsConnection* conn)
{
371 372 373 374 375 376 377 378 379 380 381
    std::vector<SrsConnection*>::iterator it = std::find(conns.begin(), conns.end(), conn);
    
    if (it != conns.end()) {
        conns.erase(it);
    }
    
    srs_info("conn removed. conns=%d", (int)conns.size());
    
    // all connections are created by server,
    // so we free it here.
    srs_freep(conn);
winlin authored
382 383 384 385
}

void SrsServer::on_signal(int signo)
{
386 387 388 389 390 391
    if (signo == SIGNAL_RELOAD) {
        signal_reload = true;
        return;
    }
    
    if (signo == SIGINT) {
392
#ifdef SRS_GPERF_MC
393 394
        srs_trace("gmc is on, main cycle will terminate normally.");
        signal_gmc_stop = true;
395
#else
396 397
        srs_trace("user terminate program");
        exit(0);
398
#endif
399 400
        return;
    }
401 402 403 404 405 406
    
    if (signo == SIGTERM) {
        srs_trace("user terminate program");
        exit(0);
        return;
    }
winlin authored
407 408 409 410
}

void SrsServer::close_listeners()
{
411 412 413 414 415 416
    std::vector<SrsListener*>::iterator it;
    for (it = listeners.begin(); it != listeners.end(); ++it) {
        SrsListener* listener = *it;
        srs_freep(listener);
    }
    listeners.clear();
winlin authored
417 418 419 420
}

int SrsServer::accept_client(SrsListenerType type, st_netfd_t client_stfd)
{
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    int ret = ERROR_SUCCESS;
    
    int max_connections = _srs_config->get_max_connections();
    if ((int)conns.size() >= max_connections) {
        int fd = st_netfd_fileno(client_stfd);
        
        srs_error("exceed the max connections, drop client: "
            "clients=%d, max=%d, fd=%d", (int)conns.size(), max_connections, fd);
            
        srs_close_stfd(client_stfd);
        
        return ret;
    }
    
    SrsConnection* conn = NULL;
    if (type == SrsListenerStream) {
        conn = new SrsClient(this, client_stfd);
438 439
    } else if (type == SrsListenerHttpApi) {
    } else if (type == SrsListenerHttpStream) {
440
    } else {
441
        // TODO: FIXME: handler others
442 443 444 445 446 447 448 449 450 451 452 453 454 455
    }
    srs_assert(conn);
    
    // directly enqueue, the cycle thread will remove the client.
    conns.push_back(conn);
    srs_verbose("add conn from port %d to vector. conns=%d", port, (int)conns.size());
    
    // cycle will start process thread and when finished remove the client.
    if ((ret = conn->start()) != ERROR_SUCCESS) {
        return ret;
    }
    srs_verbose("conn start finished. ret=%d", ret);
    
    return ret;
winlin authored
456 457 458 459
}

int SrsServer::on_reload_listen()
{
460
    return listen();
winlin authored
461
}