LVS源碼分析(1)

來源:互聯網
上載者:User

由於要做一個類似LVS的包轉寄模組,研究了LVS的架構和代碼,下面這個系列會做一個總結。首先推薦下這個blog http://yfydz.cublog.cn 裡面對LVS, IPSec的講解非常不錯

幾個重要的資料結構如下:

ip_vs_conn:一個串連由N元組構成,包括 caddr (用戶端地址cip), vaddr (服務虛擬位址vip), daddr (目的realserver地址dip), cport (用戶端串連連接埠), vport (服務虛擬連接埠), dport (目的realserver連接埠), protocol (協議)

ip_vs_service:代表一個虛擬服務。LVS中虛擬服務代表一個虛擬IP和連接埠,作為服務的入口,後面跟著一些realserver,在這些realserver之間做Server Load Balancer。ip_vs_service中包括了protocol, addr, port。struct list_head destinations, __u32 num_dests則代表了後面realserver的鏈表和個數

ip_vs_dest:代表一個realserver。addr, port, weight分別代表了realserver的ip, port, 權重。struct dst_entry *dst_cache代表了從LVS到realserver的路由快取項目,在我看來這個應該只對NAT, tunnel模式有效。vport, vaddr, protocol代表了虛擬服務地址,連接埠和協議

ip_vs_scheduler:所有調度器的基類,對ip_vs_service進行調度,其最重要的方法是 struct ip_vs_dest* (*schedule)(struct ip_vs_service *svc, const struct sk_buff* skb),從ip_vs_service下的ip_vs_dest數組中選取一個出來返回

static int __init ip_vs_init(void)用來初始化ipvs.ko,也就是LVS的核心模組:

ip_vs_control_init調用nf_register_sockopt註冊struct nf_sockopt_ops結構,ip_vs_genl_register註冊struct genl_ops ip_vs_genl_ops[]數組,這是通過netlink進行控制的命令結構。

ip_vs_protocol_init依次註冊了ip_vs_protocol_tcp, ip_vs_protocol_udp, ip_vs_protocol_ah, ip_vs_protocol_esp四個協議

ip_vs_conn_init首先調用vmalloc分配一塊大的記憶體(64k)地區用於存放串連的雜湊表的key數組,也就是說有4096和list_head。

LVS最後調用nf_register_hooks,向netfilter註冊自己的鉤子結構。LVS一共有4個鉤子(不算IPV6),

static struct nf_hook_ops ip_vs_ops[] __read_mostly = {
    /* After packet filtering, forward packet through VS/DR, VS/TUN,
     * or VS/NAT(change destination), so that filtering rules can be
     * applied to IPVS. */
    {   
        .hook       = ip_vs_in,
        .owner      = THIS_MODULE,
        .pf     = PF_INET,
        .hooknum        = NF_INET_LOCAL_IN,
        .priority       = 100,
    },
    /* After packet filtering, change source only for VS/NAT */
    {
        .hook       = ip_vs_out,
        .owner      = THIS_MODULE,
        .pf     = PF_INET,
        .hooknum        = NF_INET_FORWARD,
        .priority       = 100,
    },
    /* After packet filtering (but before ip_vs_out_icmp), catch icmp
     * destined for 0.0.0.0/0, which is for incoming IPVS connections */
    {
        .hook       = ip_vs_forward_icmp,
        .owner      = THIS_MODULE,
        .pf     = PF_INET,
        .hooknum        = NF_INET_FORWARD,
        .priority       = 99,
    },

    /* Before the netfilter connection tracking, exit from POST_ROUTING */
    {
        .hook       = ip_vs_post_routing,
        .owner      = THIS_MODULE,
        .pf     = PF_INET,
        .hooknum        = NF_INET_POST_ROUTING,
        .priority       = NF_IP_PRI_NAT_SRC-1,
    },

};

LVS無論是VS/DR, VS/TUN, VS/NAT哪種模式,由於vip配置在LVS上,因此訪問vip的流量首先會走到NF_INET_LOCAL_IN,從而調用ip_vs_in

static unsigned int
ip_vs_in(unsigned int hooknum, struct sk_buff *skb,
     const struct net_device *in, const struct net_device *out,
     int (*okfn)(struct sk_buff *))
{

    ...

    // LVS ip_vs_in只處理髮給原生報文

    if (unlikely(skb->pkt_type != PACKET_HOST)) {
        IP_VS_DBG_BUF(12, "packet type=%d proto=%d daddr=%s ignored\n",
                  skb->pkt_type,
                  iph.protocol,
                  IP_VS_DBG_ADDR(af, &iph.daddr));
        return NF_ACCEPT;
    }

    ...

    /*
     * Check if the packet belongs to an existing connection entry
     */

    // conn_in_get由協議本身實現,對於TCP而言,調用tcp_conn_in_get得到一個ip_vs_conn
    cp = pp->conn_in_get(af, skb, pp, &iph, iph.len, 0);

    if (unlikely(!cp)) {
        int v;
    
        /* For local client packets, it could be a response */
        cp = pp->conn_out_get(af, skb, pp, &iph, iph.len, 0);  // 查看是否是一個出去的串連
        if (cp)
            return handle_response(af, skb, pp, cp, iph.len); // 主要是執行snat
    
        if (!pp->conn_schedule(af, skb, pp, &v, &cp))    // 執行tcp_conn_schedule,TCP協議的調度就是為client找一個realserver,然後把這個conn儲存下來,下次就直接基於這個ip_vs_conn轉寄了
            return v;   
    }

    ...

    /* Check the server status */
    if (cp->dest && !(cp->dest->flags & IP_VS_DEST_F_AVAILABLE)) {
        /* the destination server is not available */
        if (sysctl_ip_vs_expire_nodest_conn) {
            /* try to expire the connection immediately */
            ip_vs_conn_expire_now(cp);
        }
        /* don't restart its timer, and silently
           drop the packet. */
        __ip_vs_conn_put(cp);  // 如果後面的realserver失效,那麼drop這個ip_vs_conn
        return NF_DROP;
    }

    ip_vs_in_stats(cp, skb);
    restart = ip_vs_set_state(cp, IP_VS_DIR_INPUT, skb, pp);  // 調用tcp_state_transition,改變串連的自動機狀態
    if (cp->packet_xmit)
        ret = cp->packet_xmit(skb, cp, pp);  // 根據模式不同,調用不同的發送方法 e.g. NAT調用ip_vs_nat_xmit, DR調用ip_vs_dr_xmit
        /* do not touch skb anymore */
    else {
        IP_VS_DBG_RL("warning: packet_xmit is null");
        ret = NF_ACCEPT;
    }

    ...

}

LVS的VS/DR, VS/TUN都是單臂模式,只有VS/NAT是雙臂模式。在VS/NAT模式下,LVS會作為realserver回包的next hop,因此在NF_IP_FORWARD上註冊ip_vs_out,用來處理NAT模式下的回包

static unsigned int
ip_vs_out(unsigned int hooknum, struct sk_buff *skb,
      const struct net_device *in, const struct net_device *out,
      int (*okfn)(struct sk_buff *))
{
    struct ip_vs_iphdr iph;
    struct ip_vs_protocol *pp;
    struct ip_vs_conn *cp;
    int af;

    ....

    ip_vs_fill_iphdr(af, skb_network_header(skb), &iph);  // 填充ip_vs_iphdr的IP頭

    if (unlikely(iph.protocol == IPPROTO_ICMP)) {  // 這部分代碼用來處理icmp報文,主要邏輯在ip_vs_out_icmp上,該函數用來處理outgoing方向的icmp
        int related, verdict = ip_vs_out_icmp(skb, &related);

        if (related)
            return verdict;
        ip_vs_fill_iphdr(af, skb_network_header(skb), &iph);
    }

    ....

    if (unlikely(ip_hdr(skb)->frag_off & htons(IP_MF|IP_OFFSET) && !pp->dont_defrag)) {   // 如果是IP分區的包,那麼調用ip_vs_gather_frags先嘗試整合成一個完整包,具體請參考核心IP層的frag/defrag的相關代碼
        if (ip_vs_gather_frags(skb, IP_DEFRAG_VS_OUT))
            return NF_STOLEN;

        ip_vs_fill_iphdr(af, skb_network_header(skb), &iph);
    }

    /*
     * Check if the packet belongs to an existing entry
     */
    cp = pp->conn_out_get(af, skb, pp, &iph, iph.len, 0);  // 尋找是否有已有串連

    if (unlikely(!cp)) {
        if (sysctl_ip_vs_nat_icmp_send &&
            (pp->protocol == IPPROTO_TCP ||
             pp->protocol == IPPROTO_UDP)) {
            __be16 _ports[2], *pptr;

            pptr = skb_header_pointer(skb, iph.len,
                          sizeof(_ports), _ports);
            if (pptr == NULL)
                return NF_ACCEPT;   /* Not for me */
            if (ip_vs_lookup_real_service(af, iph.protocol,
                              &iph.saddr,
                              pptr[0])) {   // 查看這個realserver是否在LVS的hash表中,如果是真實的realserver,返回一個ICMP不可達

                /*
                 * Notify the real server: there is no
                 * existing entry if it is not RST
                 * packet or not TCP packet.
                 */
                if (iph.protocol != IPPROTO_TCP
                    || !is_tcp_reset(skb, iph.len)) {
                        icmp_send(skb,
                              ICMP_DEST_UNREACH,
                              ICMP_PORT_UNREACH, 0);
                    return NF_DROP;
                }
            }
        }
        IP_VS_DBG_PKT(12, pp, skb, 0,
                  "packet continues traversal as normal");
        return NF_ACCEPT;
    }

    return handle_response(af, skb, pp, cp, iph.len);  // handle_response真正去做SNAT
}

static unsigned int 
handle_response(int af, struct sk_buff *skb, struct ip_vs_protocol *pp,
        struct ip_vs_conn *cp, int ihl)
{

    if (!skb_make_writable(skb, ihl))  /* 如果要修改skb的話,當前核心版本需要先判斷skb_make_writable */
        goto drop;

    /* mangle the packet */
    if (pp->snat_handler && !pp->snat_handler(skb, pp, cp))  /* 對TCP而言,這裡是調用tcp_snat_handler, 主要功能是修改了tcp頭之後再做下checksum */
        goto drop;

    ip_hdr(skb)->saddr = cp->vaddr.ip;  /* SNAT, 把包的源IP替換為virtual IP */
    ip_send_check(ip_hdr(skb));  /* 對IP頭做checksum */

    /* For policy routing, packets originating from this

     * machine itself may be routed differently to packets
     * passing through.  We want this packet to be routed as
     * if it came from this machine itself.  So re-compute
     * the routing information.
     */

        if (ip_route_me_harder(skb, RTN_LOCAL) != 0)  /* 由於源IP變成了本地IP,而不是之前的轉寄包,需要重新計算路由 */
            goto drop;

    ip_vs_out_stats(cp, skb);
    ip_vs_set_state(cp, IP_VS_DIR_OUTPUT, skb, pp); /* 對TCP而言,調用tcp_state_transition */
    ip_vs_conn_put(cp);

    skb->ipvs_property = 1;  /* 標記這個skb已經被LVS處理過 */

    LeaveFunction(11);
    return NF_ACCEPT;

drop:
    ip_vs_conn_put(cp);
    kfree_skb(skb);
    return NF_STOLEN;
}

LVS在NF_INET_POST_ROUTING chain上還註冊了一個優先順序為NF_IP_PRI_NAT_SRC - 1的hook函數ip_vs_post_routing。該函數在iptables SNAT之前執行,檢查LVS是否處理過該skb,如果處理過則跳過下面的netfilter hook點

/*
 *      It is hooked before NF_IP_PRI_NAT_SRC at the NF_INET_POST_ROUTING
 *      chain, and is used for VS/NAT.
 *      It detects packets for VS/NAT connections and sends the packets
 *      immediately. This can avoid that iptable_nat mangles the packets
 *      for VS/NAT.
 */     
static unsigned int ip_vs_post_routing(unsigned int hooknum,
                       struct sk_buff *skb,
                       const struct net_device *in,
                       const struct net_device *out,
                       int (*okfn)(struct sk_buff *))
{
    if (!skb->ipvs_property)
        return NF_ACCEPT;
    /* The packet was sent from IPVS, exit this chain */
    return NF_STOP;  
}

netfilter架構下,NF_HOOK宏會調用到nf_hook_slow,進而調用nf_iterate,即對於特定PF下的特定HOOKNUM,按優先順序遍曆上面註冊的所有hook函數,只有當所有函數都返回NF_ACCEPT,或者有任意函數返回NF_STOP,整個nf_iterate才會返回NF_ACCEPT。與NF_ACCEPT不同的是,NF_STOP的語義會忽略該掛載點下其他優先順序的函數。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.