thttp.c 2.4 KB
Newer Older
S
Shengliang Guan 已提交
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
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#define _DEFAULT_SOURCE
#include "thttp.h"
#include "taoserror.h"
#include "tlog.h"

int32_t taosSendHttpReport(const char* server, uint16_t port, const char* pCont, int32_t contLen) {
  int32_t code = -1;
  SOCKET  fd = 0;

  uint32_t ip = taosGetIpv4FromFqdn(server);
  if (ip == 0xffffffff) {
    terrno = TAOS_SYSTEM_ERROR(errno);
    uError("failed to get http server:%s ip since %s", server, terrstr());
    goto SEND_OVER;
  }

  fd = taosOpenTcpClientSocket(ip, port, 0);
  if (fd < 0) {
    terrno = TAOS_SYSTEM_ERROR(errno);
S
monitor  
Shengliang Guan 已提交
35
    uError("failed to create http socket to %s:%u since %s", server, port, terrstr());
S
Shengliang Guan 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48
    goto SEND_OVER;
  }

  char    header[4096] = {0};
  int32_t headLen = snprintf(header, sizeof(header),
                             "POST /report HTTP/1.1\n"
                             "Host: %s\n"
                             "Content-Type: application/json\n"
                             "Content-Length: %d\n\n",
                             server, contLen);

  if (taosWriteSocket(fd, (void*)header, headLen) < 0) {
    terrno = TAOS_SYSTEM_ERROR(errno);
49
    uError("failed to send http header to %s:%u since %s", server, port, terrstr());
S
Shengliang Guan 已提交
50 51 52 53 54
    goto SEND_OVER;
  }

  if (taosWriteSocket(fd, (void*)pCont, contLen) < 0) {
    terrno = TAOS_SYSTEM_ERROR(errno);
55
    uError("failed to send http content to %s:%u since %s", server, port, terrstr());
S
Shengliang Guan 已提交
56 57 58 59 60 61
    goto SEND_OVER;
  }

  // read something to avoid nginx error 499
  if (taosReadSocket(fd, header, 10) < 0) {
    terrno = TAOS_SYSTEM_ERROR(errno);
62
    uError("failed to receive response from %s:%u since %s", server, port, terrstr());
S
Shengliang Guan 已提交
63 64 65
    goto SEND_OVER;
  }

66
  uTrace("send http to %s:%u, len:%d content: %s", server, port, contLen, pCont);
S
Shengliang Guan 已提交
67 68 69 70 71 72 73 74 75
  code = 0;

SEND_OVER:
  if (fd != 0) {
    taosCloseSocket(fd);
  }

  return code;
}