提交 12b22d2a authored 作者: Eliot Gable's avatar Eliot Gable

Initial check-in of mod_ha_cluster code; currently a work in progress.

上级 8d5a6ce7
include $(top_srcdir)/build/modmake.rulesam
MODNAME=mod_ha_cluster
mod_LTLIBRARIES = mod_ha_cluster.la
mod_ha_cluster_la_SOURCES = mod_ha_cluster.c ha_cluster_config.c ha_cluster_util.c \
ha_cluster_interfaces.c
mod_ha_cluster_la_CFLAGS = $(AM_CFLAGS) -I.
mod_ha_cluster_la_LIBADD = $(switch_builddir)/libfreeswitch.la
mod_ha_cluster_la_LDFLAGS = -avoid-version -module -no-undefined -shared
<configuration name="ha_cluster.conf" description="High Availability Cluster">
<network>
<!-- Define some anti-DoS rules for the IP addresses we manage.
To make use of this functionality, you must run:
iptables -N ha-cluster-rules
iptables -I INPUT -j ha-cluster-rules
/etc/init.d/iptables save
To disable this functionality, you can run:
iptables -D INPUT -j ha-cluster-rules
/etc/init.d/iptables save
-->
<dos-rules>
<!-- By default, udp ports 1024 - 65535 and tcp ports
5060 and 5061 are allowed. These rules limit the
number of requests per second which can be sent
to FreeSWITCH, as well as dropping scans from
SIP Vicious. -->
<rule-group name="public">
<!-- Rules applied in the order listed. When
you hit the end of the list, the default
rules are applied, then everything that
does not match a rule is dropped. -->
<rule name="sipvicios" type="drop" string="friendly-scanner"/>
<rule name="register" type="limit" string="REGISTER" rate="14/minute" burst="8" mode="srcip"/>
<rule name="options" type="limit" string="OPTIONS" rate="5/minute" burst="5" mode="srcip"/>
<rule name="notify" type="limit" string="NOTIFY" rate="5/minute" burst="5" mode="srcip"/>
<rule name="invite" type="limit" string="INVITE" rate="5/sec" burst="10" mode="srcip"/>
<rule name="bye" type="limit" string="BYE" rate="5/sec" burst="10" mode="srcip"/>
<rule name="ack" type="limit" string="ACK" rate="20/sec" burst="40" mode="srcip"/>
<rule name="cancel" type="limit" string="CANCEL" rate="5/sec" burst="10" mode="srcip"/>
<rule name="update" type="limit" string="UPDATE" rate="5/sec" burst="10" mode="srcip"/>
<rule name="info" type="limit" string="INFO" rate="20/sec" burst="40" mode="srcip"/>
<rule name="prack" type="limit" string="PRACK" rate="20/sec" burst="40" mode="srcip"/>
<rule name="refer" type="limit" string="REFER" rate="5/sec" burst="10" mode="srcip"/>
<rule name="subscribe" type="limit" string="SUBSCRIBE" rate="5/sec" burst="10" mode="srcip"/>
<rule name="publish" type="limit" string="PUBLISH" rate="5/sec" burst="10" mode="srcip"/>
<rule name="message" type="limit" string="MESSAGE" rate="5/sec" burst="10" mode="srcip"/>
</rule-group>
</dos-rules>
<!-- Define interfaces to be controlled by FreeSWITCH. These
interfaces should be entirely under the control of
FreeSWITCH or bad things might happen. -->
<interfaces>
<interface name="eth1" description="Public Interface">
<!-- Define a set of master/slave failover IP addresses
on this interface and assign a variable to them
for use in other configs. -->
<failover-ips name="eth1_ms_ips_group1">
<ip name="external5-ip" cidr="10.0.1.8/24" var="external5-ip" rule-group="public"/>
<ip name="external4-ip" cidr="10.0.1.7/24" var="external4-ip" rule-group="public"/>
<ip name="external3-ip" cidr="10.0.1.6/24" var="external3-ip" rule-group="public"/>
<ip name="external2-ip" cidr="10.0.1.5/24" var="external2-ip" rule-group="public"/>
<ip name="external1-ip" cidr="10.0.1.4/24" var="external1-ip" rule-group="public"/>
</failover-ips>
<!-- Set the default route to this interface when it comes up. -->
<route name="default" destination="0.0.0.0/0" gateway="10.0.1.1" metric="0"/>
<!-- Make sure we know where the gateway is when the
interface comes up since we use NOARP flag -->
<arp ip="10.0.1.1" mac="00:00:0D:03:DB:13"/>
</interface>
<interface name="eth2" description="Internal Interface">
<failover-ips name="eth2_ms_ips_group1">
<ip name="internal-ip" cidr="10.0.0.4/24" var="internal-ip"/>
</failover-ips>
<arp ip="10.0.0.1" mac="00:00:0D:03:DB:14"/>
</interface>
</interfaces>
<!-- Define failover groups. Each group requires one master
node. If you have two groups and two nodes, you end up
with two masters - one for each group. If you have two
groups and three nodes, you get two masters and one
slave. One group and two nodes gets you one master and
one slave. Two groups and four nodes gets you two masters
and two slaves. Two groups and five nodes gets you two
masters and three slaves.
type - can be failover-ips
-->
<failover-groups>
<group name="group1" type="failover-ips">
<include name="eth1_ms_ips_group1"/>
<include name="eth2_ms_ips_group1"/>
</group>
</failover-groups>
</network>
<general>
<!-- This node-id must be unique in the cluster -->
<nodeid value="0"/>
<!-- How many nodes are in the cluster -->
<total-nodes value="2"/>
<!-- How long to listen and learn of other nodes before
choosing a state and starting -->
<timer-a value="60"/>
<!-- Maximum time to spend listening in the starting state if
no other nodes can be heard. If set to -1, timer-a is also
the max it can be in starting. -->
<timer-b value="-1"/>
<!-- Maximum link latency in ms across all multicast groups.
This is used for de-duplicating events. If set too low,
you may process duplicate events if you have more than one
multicast group. -->
<max-latency value="50"/>
<!-- Define multicast groups and the source IP and port for
each group. To avoid split-brain, you need at least two.
Then, if one fails, the nodes can still talk to each
other, which prevents the nodes from trying to take over
another node's traffic while the other node is still
actually running. Split-brain is VERY BAD. -->
<heartbeat interval="100" bind-network="192.168.0.4" multicast-address="224.0.0.51" port="4096" ttl="1"/>
<heartbeat interval="100" bind-network="192.168.1.4" multicast-address="224.0.0.51" port="4096" ttl="1"/>
<!-- How long in ms to wait for a heartbeat before declaring
a node dead and commencing failover. -->
<failure-threshold value="3000"/>
<!-- Define a set of events on which to consider this node
dead and force a restart of FreeSWITCH. -->
<failover>
<condition event="SWITCH_EVENT_FAILURE">
<match name="module" value="mod_sofia"/>
<match name="class" value="PROFILE_START_FAILURE"/>
</condition>
<condition event="SWITCH_EVENT_FAILURE">
<match name="module" value="mod_sofia"/>
<match name="class" value="CONFIGURATION_LOAD_FAILURE"/>
</condition>
</failover>
</general>
</configuration>
/*
* High Availability Cluster Module for FreeSWITCH Modular Media Switching
* Software Library / Soft-Switch Application
*
* High Availability Cluster Module is
* Copyright (C) 2010, Eliot Gable <egable@gmail.com>
*
* FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application is
* Copyright (C) 2005-2010, Anthony Minessale II <anthm@freeswitch.org>
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is High Availability Module for FreeSWITCH Modular Media
* Switching Software Library / Soft-Switch Application
*
* The Initial Developer of the Original Code is
* Eliot Gable <egable@gmail.com>
* Portions created by the Initial Developer are Copyright (C)
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*
*/
#include <mod_ha_cluster.h>
switch_status_t config_routes(hac_route_t **routes, switch_xml_t root, const char *dev)
{
switch_xml_t x_list = NULL;
hac_route_t *cur;
cur = *routes;
for(x_list = switch_xml_child(root, "route"); x_list; x_list = x_list->next) {
const char* name = switch_xml_attr(x_list, "name");
const char* dest = switch_xml_attr(x_list, "destination");
const char* gwy = switch_xml_attr(x_list, "gateway");
const char* metric = switch_xml_attr(x_list, "metric");
if(switch_strlen_zero(name)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: route is missing name attribute.\n");
goto fail;
} else if(switch_strlen_zero(dest)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: route is missing dest attribute.\n");
goto fail;
} else if(switch_strlen_zero(gwy)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: route is missing gateway attribute.\n");
goto fail;
}
/* TODO: Check for route name conflicts */
/* TODO: Check route destination format */
/* TODO: Check route gateway format */
/* TODO: Check route metric for sane value */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: route discovered: %s (%s -> %s metric %s)\n", name, dest, gwy, metric);
if(!switch_strlen_zero(cur->name)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_route_t));
cur = cur->next;
}
cur->name = name;
cur->destination = dest;
cur->gateway = gwy;
cur->metric = metric;
cur->dev = dev;
cur->next = NULL;
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_arp(hac_arp_t **arps, switch_xml_t root, const char *dev)
{
switch_xml_t x_list = NULL;
hac_arp_t *cur;
cur = *arps;
for(x_list = switch_xml_child(root, "arp"); x_list; x_list = x_list->next) {
const char* ip = switch_xml_attr(x_list, "ip");
const char* mac = switch_xml_attr(x_list, "mac");
if(switch_strlen_zero(ip)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: arp entry missint IP attribute\n");
goto fail;
} else if(switch_strlen_zero(mac)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: arp entry missint MAC attribute\n");
goto fail;
}
/* TODO: Check for ARP IP address conflict */
/* TODO: Check IP address format */
/* TODO: Check MAC address format */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: arp entry discovered: %s -> %s\n", ip, mac);
if(!switch_strlen_zero(cur->ip)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_arp_t));
cur = cur->next;
}
cur->ip = ip;
cur->mac = mac;
cur->dev = dev;
cur->next = NULL;
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_ips(hac_ip_t** ips, switch_xml_t root, const char *dev)
{
switch_xml_t x_list = NULL;
hac_ip_t *cur;
cur = *ips;
for(x_list = switch_xml_child(root, "ip"); x_list; x_list = x_list->next) {
const char* name = switch_xml_attr(x_list, "name");
const char* cidr = switch_xml_attr(x_list, "cidr");
const char* var = switch_xml_attr(x_list, "var");
const char* rgroup = switch_xml_attr(x_list, "rule-group");
if(switch_strlen_zero(name)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: IP addresses must be named!\n");
goto fail;
} else if(switch_strlen_zero(cidr)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: IP address cidr attribute missing.\n");
goto fail;
} else if(strlen(name) > 14) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: IP address names cannot exceed 14 characters; sorry!\n");
goto fail;
} else if(!strchr(cidr, '/')) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: IP address cidr attribute not in CIDR format.\n");
goto fail;
}
/* TODO: Check for ip name conflicts */
/* TODO: Add more stringent check on IP address CIDR format */
/* TODO: Check to make sure the referenced rule group exists */
/* TODO: Check for variable name conflict */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: ip discovered: %s (%s) ${%s}\n", name, cidr, var);
if(!switch_strlen_zero(cur->name)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_ip_t));
cur = cur->next;
}
cur->name = name;
cur->cidr = cidr;
cur->rgroup = rgroup;
cur->var = var;
if(!switch_strlen_zero(var)) {
char buf[64], *p = NULL;
memset(buf, 0, 64);
switch_copy_string(buf, cidr, 64);
if((p = strchr(buf, '/')) != NULL) {
*p = '\0';
}
switch_core_set_variable(var, buf);
}
cur->dev = dev;
cur->next = NULL;
if(config_routes(&cur->routes, x_list, dev) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_cluster_ips(hac_cluster_ips_t **cips, switch_xml_t root, const char *dev)
{
switch_xml_t x_list = NULL;
hac_cluster_ips_t *cur;
cur = *cips;
for(x_list = switch_xml_child(root, "cluster-ips"); x_list; x_list = x_list->next) {
const char* name = switch_xml_attr(x_list, "name");
const char* vmac = switch_xml_attr(x_list, "vmac");
if(switch_strlen_zero(name)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: clustered ip group has no name\n");
goto fail;
} else if(switch_strlen_zero(vmac)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: clustered ip group has no virtual MAC\n");
goto fail;
}
/* TODO: verify virtual MAC address format and that it is
* multicast */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: clustered ip discovered: %s (%s)\n", name, vmac);
if(!switch_strlen_zero(cur->name)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_cluster_ips_t));
cur = cur->next;
}
cur->name = name;
cur->vmac = vmac;
cur->dev = dev;
cur->next = NULL;
cur->ips = switch_core_alloc(config.pool, sizeof(hac_ip_t));
cur->routes = switch_core_alloc(config.pool, sizeof(hac_route_t));
if(config_ips(&cur->ips, x_list, dev) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
if(config_routes(&cur->routes, x_list, dev) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_failover_ips(hac_failover_ips_t **fips, switch_xml_t root, const char *dev)
{
switch_xml_t x_list = NULL;
hac_failover_ips_t *cur;
cur = *fips;
for(x_list = switch_xml_child(root, "failover-ips"); x_list; x_list = x_list->next) {
const char* name = switch_xml_attr(x_list, "name");
const char* nodes = switch_xml_attr(x_list, "nodes");
if(switch_strlen_zero(name)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: failover ip missing name attribute\n");
goto fail;
}
/* TODO: evaluate removing nodes attribute from failover-ips */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: failover ip discovered: %s (%s)\n", name, nodes);
if(!switch_strlen_zero(cur->name)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_failover_ips_t));
cur = cur->next;
}
cur->name = name;
cur->nodes = nodes;
cur->dev = dev;
cur->next = NULL;
cur->ips = switch_core_alloc(config.pool, sizeof(hac_ip_t));
cur->routes = switch_core_alloc(config.pool, sizeof(hac_route_t));
if(config_ips(&cur->ips, x_list, dev) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
if(config_routes(&cur->routes, x_list, dev) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_interfaces(hac_interface_t **ints, switch_xml_t root)
{
switch_xml_t x_list = NULL;
hac_interface_t *cur;
cur = *ints;
for(x_list = switch_xml_child(root, "interface"); x_list; x_list = x_list->next) {
const char *name = switch_xml_attr(x_list, "name");
const char *desc = switch_xml_attr(x_list, "description");
const char *duplex = switch_xml_attr(x_list, "duplex");
const char *speed = switch_xml_attr(x_list, "speed");
if(switch_strlen_zero(name)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface missing name\n");
goto fail;
}
/* TODO: Validate duplex */
/* TODO: Validate speed */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: interface discovered: %s (%s)\n", name, desc);
if(!switch_strlen_zero(cur->name)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_interface_t));
cur = cur->next;
}
cur->name = name;
cur->description = desc;
cur->duplex = duplex;
cur->speed = speed;
cur->next = NULL;
cur->cips = switch_core_alloc(config.pool, sizeof(hac_cluster_ips_t));
cur->fips = switch_core_alloc(config.pool, sizeof(hac_failover_ips_t));
cur->ips = switch_core_alloc(config.pool, sizeof(hac_ip_t));
cur->routes = switch_core_alloc(config.pool, sizeof(hac_route_t));
cur->arps = switch_core_alloc(config.pool, sizeof(hac_arp_t));
if(config_cluster_ips(&cur->cips, root, name) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
if(config_failover_ips(&cur->fips, root, name) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
if(config_ips(&cur->ips, root, name) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
if(config_routes(&cur->routes, root, name) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
if(config_arp(&cur->arps, root, name) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_rules(hac_rule_t** rules, switch_xml_t root)
{
switch_xml_t x_list = NULL;
hac_rule_t *cur;
cur = *rules;
for(x_list = switch_xml_child(root, "rule"); x_list; x_list = x_list->next) {
const char* name = switch_xml_attr(x_list, "name");
const char* type = switch_xml_attr(x_list, "type");
const char* string = switch_xml_attr(x_list, "string");
const char* rate = switch_xml_attr(x_list, "rate");
const char* burst = switch_xml_attr(x_list, "burst");
const char* mode = switch_xml_attr(x_list, "mode");
const char* proto = switch_xml_attr(x_list, "proto");
const char* sport = switch_xml_attr(x_list, "sport");
const char* dport = switch_xml_attr(x_list, "dport");
const char* src = switch_xml_attr(x_list, "src");
const char* srcrange = switch_xml_attr(x_list, "srcrange");
const char* length = switch_xml_attr(x_list, "length");
const char* mports = switch_xml_attr(x_list, "mports");
const char* srcmports = switch_xml_attr(x_list, "srcmports");
const char* dstmports = switch_xml_attr(x_list, "dstmports");
const char* state = switch_xml_attr(x_list, "state");
const char* rejectwith = switch_xml_attr(x_list, "rejectwith");
const char* mark = switch_xml_attr(x_list, "mark");
if(switch_strlen_zero(name)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: rule missing name attribute.\n");
goto fail;
}
if(switch_strlen_zero(type)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: rule missing type attribute.\n");
goto fail;
}
if(strlen(name) > 14) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: rule name must not exceed 14 characters; sorry!\n");
goto fail;
}
if(strlen(string) > 96) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: rule string match must not exceed 96 characters; sorry!\n");
goto fail;
}
/* TODO: Validate rule type */
/* TODO: Validate rule rate format */
/* TODO: Validate sanity of burst */
/* TODO: Validate rule mode */
/* TODO: Validate rule proto */
/* TODO: Validate rule sport */
/* TODO: Validate rule dport */
/* TODO: Validate src format (DNS or IP) */
/* TODO: Validate srcrange format */
/* TODO: Validate sanity of packet length */
/* TODO: Validate mports format and range */
/* TODO: Validate srcmports format and ranges */
/* TODO: Validate dstmports format and ranges */
/* TODO: Validate state */
/* TODO: Validate rejectwith */
/* TODO: Validate sanity of mark */
/* TODO: Validate we have enough info to generate a full rule */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: rule discovered: %s\n", type);
if(!switch_strlen_zero(cur->name)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_rule_t));
cur = cur->next;
}
cur->name = name;
cur->type = type;
cur->string = string;
cur->rate = rate;
cur->burst = burst;
cur->mode = mode;
cur->proto = proto;
cur->sport = sport;
cur->dport = dport;
cur->src = src;
cur->srcrange = srcrange;
cur->length = length;
cur->mports = mports;
cur->srcmports = srcmports;
cur->dstmports = dstmports;
cur->state = state;
cur->rejectwith = rejectwith;
cur->mark = mark;
cur->next = NULL;
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_rule_groups(hac_rule_group_t** rgroups, switch_xml_t root)
{
switch_xml_t x_list = NULL;
hac_rule_group_t *cur;
cur = *rgroups;
for(x_list = switch_xml_child(root, "rule-group"); x_list; x_list = x_list->next) {
const char* name = switch_xml_attr(x_list, "name");
if(switch_strlen_zero(name)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: rule group missing name attribute.\n");
goto fail;
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: rule group discovered: %s\n", name);
if(!switch_strlen_zero(cur->name)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_rule_group_t));
cur = cur->next;
}
cur->name = name;
cur->next = NULL;
cur->rules = switch_core_alloc(config.pool, sizeof(hac_rule_t));
if(config_rules(&cur->rules, x_list) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_failover_groups(hac_failover_group_t** fover, switch_xml_t root)
{
switch_xml_t x_list = NULL, x_list2 = NULL;
int cur_inc = 0;
hac_failover_group_t *cur;
cur = *fover;
for(x_list = switch_xml_child(root, "group"); x_list; x_list = x_list->next) {
const char* name = switch_xml_attr(x_list, "name");
const char* type = switch_xml_attr(x_list, "type");
if(switch_strlen_zero(name)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: failover group missing name attribute.\n");
goto fail;
}
if(switch_strlen_zero(type)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: failover group missing type attribute.\n");
goto fail;
}
/* TODO: Validate failover type */
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: failover group discovered: %s (%s)\n", name, type);
if(!switch_strlen_zero(cur->name)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_failover_group_t));
cur = cur->next;
}
cur->name = name;
cur->include_type = type;
cur->next = NULL;
cur->num_includes = 0;
for(x_list2 = switch_xml_child(x_list, "include"); x_list2; x_list2 = x_list2->next) {
cur->num_includes++;
}
cur->include_names = switch_core_alloc(config.pool, sizeof(const char*) * cur->num_includes);
for(x_list2 = switch_xml_child(x_list, "include"); x_list2; x_list2 = x_list2->next) {
cur->include_names[cur_inc] = switch_xml_attr(x_list2, "name");
if(switch_strlen_zero(cur->include_names[cur_inc])) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: failover group include missing name attribute.\n");
goto fail;
}
cur_inc++;
}
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_network(switch_xml_t root)
{
switch_xml_t x_list = NULL;
if((x_list = switch_xml_child(root, "dos-rules"))) {
config.network.rgroups = switch_core_alloc(config.pool, sizeof(hac_rule_group_t));
if(config_rule_groups(&config.network.rgroups, x_list) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
}
config.network.interfaces = NULL;
if((x_list = switch_xml_child(root, "interfaces"))) {
config.network.interfaces = switch_core_alloc(config.pool, sizeof(hac_interface_t));
if(config_interfaces(&config.network.interfaces, x_list) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
}
if(config.network.interfaces == NULL) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: missing interfaces section in config file\n");
goto fail;
}
if((x_list = switch_xml_child(root, "failover-groups"))) {
config.network.fgroups = switch_core_alloc(config.pool, sizeof(hac_failover_group_t));
if(config_failover_groups(&config.network.fgroups, x_list) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_hb(hac_hb_t** hb, switch_xml_t root)
{
hac_hb_t *cur = NULL;
const char *interval = NULL, *network = NULL, *address = NULL, *ttl = NULL, *port = NULL;
cur = *hb;
interval = switch_xml_attr(root, "interval");
network = switch_xml_attr(root, "bind-network");
port = switch_xml_attr(root, "port");
address = switch_xml_attr(root, "multicast-address");
ttl = switch_xml_attr(root, "ttl");
if(switch_strlen_zero(interval)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing interval attributes for heartbeat element\n");
goto fail;
}
if(switch_strlen_zero(network)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing bind-network attributes for heartbeat element\n");
goto fail;
}
if(switch_strlen_zero(address)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing multicast-address attributes for heartbeat element\n");
goto fail;
}
if(switch_strlen_zero(port)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing port attributes for heartbeat element\n");
goto fail;
}
/* TODO: Validate heartbeat interval sanity */
/* TODO: Validate bind-network address format and existence */
/* TODO: Sanity check on port */
/* TODO: Validate multicast-address */
/* TODO: TTL Sanity check */
if(!switch_strlen_zero(cur->address)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_hb_t));
cur = cur->next;
}
cur->interval = interval;
cur->network = network;
cur->address = address;
cur->port = port;
cur->lport = atoi(port);
cur->ttl = ttl;
cur->next = NULL;
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_events(hac_event_match_t** events, switch_xml_t root)
{
switch_xml_t x_list = NULL;
hac_event_match_t *cur;
cur = *events;
for(x_list = switch_xml_child(root, "match"); x_list; x_list = x_list->next) {
const char* name = switch_xml_attr(x_list, "name");
const char* value = switch_xml_attr(x_list, "value");
if(switch_strlen_zero(name)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: event name is missing.\n");
goto fail;
} else if(switch_strlen_zero(value)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: event value is missing.\n");
goto fail;
}
if(!switch_strlen_zero(cur->name)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_event_match_t));
cur = cur->next;
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: failover event match on: %s = %s\n", name, value);
cur->name = name;
cur->value = value;
cur->next = NULL;
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_failover(hac_failover_t** fover, switch_xml_t root)
{
switch_xml_t x_list = NULL;
hac_failover_t *cur;
cur = *fover;
for(x_list = switch_xml_child(root, "condition"); x_list; x_list = x_list->next) {
const char* event = switch_xml_attr(x_list, "event");
if(switch_strlen_zero(event)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: failover event missing in condition.\n");
goto fail;
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: failover event discovered: %s\n", event);
if(!switch_strlen_zero(cur->event)) {
cur->next = switch_core_alloc(config.pool, sizeof(hac_failover_t));
cur = cur->next;
}
cur->event = event;
cur->next = NULL;
cur->match_rules = switch_core_alloc(config.pool, sizeof(hac_event_match_t));
if(config_events(&cur->match_rules, x_list) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t config_general(switch_xml_t root)
{
switch_xml_t x_list = NULL;
hac_hb_t *cur = NULL;
if((x_list = switch_xml_child(root, "nodeid"))) {
const char* value = NULL;
value = switch_xml_attr(x_list, "value");
if(!switch_strlen_zero(value)) {
config.general.nodeid = value;
switch_thread_rwlock_wrlock(hac_globals.lock);
hac_globals.nodeid = (switch_strlen_zero(value) ? -1 : atoi(value));
switch_thread_rwlock_unlock(hac_globals.lock);
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing nodeid value in general section.\n");
goto fail;
}
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing nodeid element in general section.\n");
goto fail;
}
if((x_list = switch_xml_child(root, "master-slave-ratio"))) {
const char* value = NULL;
value = switch_xml_attr(x_list, "value");
if(!switch_strlen_zero(value)) {
config.general.msr = value;
switch_thread_rwlock_wrlock(hac_globals.lock);
hac_globals.msr = (switch_strlen_zero(value) ? "4:1" : value);
switch_thread_rwlock_unlock(hac_globals.lock);
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing master-slave-ratio value in general section.\n");
goto fail;
}
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing master-slave-ratio element in general section.\n");
goto fail;
}
if((x_list = switch_xml_child(root, "timer-a"))) {
const char* value = NULL;
value = switch_xml_attr(x_list, "value");
if(!switch_strlen_zero(value)) {
config.general.timer_a = value;
switch_thread_rwlock_wrlock(hac_globals.lock);
hac_globals.timer_a_dur = (switch_strlen_zero(value) ? 60 : atoi(value));
switch_thread_rwlock_unlock(hac_globals.lock);
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing timer-a value in general section.\n");
goto fail;
}
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing timer-a element in general section.\n");
goto fail;
}
if((x_list = switch_xml_child(root, "timer-b"))) {
const char* value = NULL;
value = switch_xml_attr(x_list, "value");
if(!switch_strlen_zero(value)) {
config.general.timer_b = value;
switch_thread_rwlock_wrlock(hac_globals.lock);
hac_globals.timer_b_dur = (switch_strlen_zero(value) ? 60 : atoi(value));
switch_thread_rwlock_unlock(hac_globals.lock);
}
}
if((x_list = switch_xml_child(root, "failure-threshold"))) {
const char* value = NULL;
value = switch_xml_attr(x_list, "value");
if(!switch_strlen_zero(value)) {
config.general.failure_threshold = value;
switch_thread_rwlock_wrlock(hac_globals.lock);
hac_globals.failure_threshold = (switch_strlen_zero(value) ? 5000 : atoi(value));
switch_thread_rwlock_unlock(hac_globals.lock);
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "HAC: Missing failure-threshold value in general section; defaulted to 5000ms.\n");
}
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "HAC: Missing failure-threshold element in general section; defaulting to 5000ms.\n");
switch_thread_rwlock_wrlock(hac_globals.lock);
hac_globals.failure_threshold = 5000;
switch_thread_rwlock_unlock(hac_globals.lock);
}
config.general.heartbeat = switch_core_alloc(config.pool, sizeof(hac_hb_t));
cur = config.general.heartbeat;
for(x_list = switch_xml_child(root, "heartbeat"); x_list; x_list = x_list->next) {
if(config_hb(&cur, x_list) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
switch_thread_rwlock_wrlock(hac_globals.lock);
hac_globals.hb = config.general.heartbeat;
switch_thread_rwlock_unlock(hac_globals.lock);
}
if(switch_strlen_zero(config.general.heartbeat->address)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing heartbeat element in general section.\n");
goto fail;
}
if((x_list = switch_xml_child(root, "failover"))) {
config.general.failover = switch_core_alloc(config.pool, sizeof(hac_failover_t));
if(config_failover(&config.general.failover, x_list) != SWITCH_STATUS_SUCCESS) {
goto fail;
}
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Missing failover section in general section.\n");
goto fail;
}
return SWITCH_STATUS_SUCCESS;
fail:
return SWITCH_STATUS_FALSE;
}
switch_status_t do_config(switch_bool_t reload)
{
switch_xml_t xml = NULL;
volatile switch_xml_t x_lists = NULL;
switch_xml_t cfg = NULL;
if(reload == SWITCH_TRUE) {
switch_core_destroy_memory_pool(&config.pool);
}
switch_core_new_memory_pool(&config.pool);
if((xml = switch_xml_open_cfg("ha_cluster.conf", &cfg, NULL))) {
if((x_lists = switch_xml_child(cfg, "network"))) {
if(config_network(x_lists) != SWITCH_STATUS_SUCCESS) {
goto failconfig;
}
}
if((x_lists = switch_xml_child(cfg, "general"))) {
if(config_general(x_lists) != SWITCH_STATUS_SUCCESS) {
goto failconfig;
}
}
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: Could not open ha_cluster.conf\n");
goto failconfig;
}
switch_xml_free(xml);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: Configuration loaded.\n");
switch_thread_rwlock_wrlock(hac_globals.lock);
hac_globals.state = HAC_PEER_STARTING;
switch_thread_rwlock_unlock(hac_globals.lock);
return SWITCH_STATUS_SUCCESS;
failconfig:
switch_xml_free(xml);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: Configuration failed to load.\n");
return SWITCH_STATUS_FALSE;
}
/*
* High Availability Cluster Module for FreeSWITCH Modular Media Switching
* Software Library / Soft-Switch Application
*
* High Availability Cluster Module is
* Copyright (C) 2010, Eliot Gable <egable@gmail.com>
*
* FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application is
* Copyright (C) 2005-2010, Anthony Minessale II <anthm@freeswitch.org>
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is High Availability Module for FreeSWITCH Modular Media
* Switching Software Library / Soft-Switch Application
*
* The Initial Developer of the Original Code is
* Eliot Gable <egable@gmail.com>
* Portions created by the Initial Developer are Copyright (C)
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*
*/
#include <mod_ha_cluster.h>
switch_status_t initialize_interfaces()
{
char *cmd_result = NULL, cmd[256];
hac_interface_t* cur_int = NULL;
int count = 0;
switch_status_t status;
char expected_speed[16];
char expected_duplex[16];
memset(expected_speed, 0, 16);
memset(expected_duplex, 0, 16);
/* First, make sure all interfaces exist. */
cur_int = config.network.interfaces;
while(cur_int != NULL) {
memset(cmd, 0, 256);
sprintf(cmd, "ip link list %s", cur_int->name);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result) {
return SWITCH_STATUS_FALSE;
}
if(strstr(cmd_result, "does not exist")) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface '%s' does not exist\n", cur_int->name);
fprintf(stderr, "HAC: interface '%s' does not exist\n", cur_int->name);
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
cur_int = cur_int->next;
}
/* After we know they exist, then take controll over them. */
cur_int = config.network.interfaces;
while(cur_int != NULL) {
/* This clears routes and puts the interface in a DOWN state
which then requires us to bring it back up. This helps to
check for issues to make sure we can actually bring it back
up. Sometimes we can take the interface down when something
is wrong, but not bring it back up. This helps us check
that condition. */
memset(cmd, 0, 256);
sprintf(cmd, "ifdown %s 2>&1", cur_int->name);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && strstr(cmd_result, "does not exist"))) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to control interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: unable to control interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
/* We do not want to have an IP address conflict while starting
this node, so we flush the addresses. */
memset(cmd, 0, 256);
sprintf(cmd, "ip addr flush %s 2>&1", cur_int->name);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && strstr(cmd_result, "does not exist"))) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to control interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: unable to control interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
/* If speed and duplex are specified, set them and disable autoneg */
if(!switch_strlen_zero(cur_int->speed) && !switch_strlen_zero(cur_int->duplex)) {
memset(cmd, 0, 256);
sprintf(cmd, "ethtool -s %s speed %s duplex %s autoneg off 2>&1", cur_int->name, cur_int->speed, cur_int->duplex);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && strstr(cmd_result, "Cannot set new settings"))) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to set speed and duplex on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: unable to set speed and duplex on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
} else {
if(!switch_strlen_zero(cur_int->duplex)) {
/* Set the duplex on the interface if specified */
memset(cmd, 0, 256);
sprintf(cmd, "ethtool -s %s duplex %s 2>&1", cur_int->name, cur_int->duplex);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && strstr(cmd_result, "Cannot set new settings"))) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to set duplex on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: unable to set duplex on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
}
if(!switch_strlen_zero(cur_int->speed)) {
/* Set the speed on the interface if specified */
memset(cmd, 0, 256);
sprintf(cmd, "ethtool -s %s speed %s 2>&1", cur_int->name, cur_int->speed);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && strstr(cmd_result, "Cannot set new settings"))) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to set speed on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: unable to set speed on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
}
}
/* Now we bring the interface back up to ensure we *can* bring
it up. We turn off ARP so that when we assign IPs to it, we
do not immediately start talking over it. */
memset(cmd, 0, 256);
sprintf(cmd, "ip link set %s up arp off 2>&1", cur_int->name);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && strstr(cmd_result, "does not exist"))) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to control interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: unable to control interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
/* Run an internal test on the interface to help check to see
if it is good. */
memset(cmd, 0, 256);
sprintf(cmd, "sleep 1 && ethtool -t %s online 2>&1", cur_int->name);
count = 0;
while(((status = execute_command(cmd, &cmd_result)) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && !strstr(cmd_result, "PASS"))) && count < 30) {
switch_yield(1000);
count++;
}
if(status != SWITCH_STATUS_SUCCESS || count > 30) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface '%s' failed test: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: interface '%s' failed test: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
/* Check for carrier signal on interface */
memset(cmd, 0, 256);
sprintf(cmd, "ip link list dev %s 2>&1", cur_int->name);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && (strstr(cmd_result, "NO-CARRIER") || strstr(cmd_result, "DOWN")))) {
if(cmd_result && strstr(cmd_result, "NO-CARRIER")) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface '%s' loss of carrier detected\n", cur_int->name);
fprintf(stderr, "HAC: interface '%s' loss of carrier detected\n", cur_int->name);
} else if(cmd_result && strstr(cmd_result, "DOWN")) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface '%s' is down\n", cur_int->name);
fprintf(stderr, "HAC: interface '%s' is down\n", cur_int->name);
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to check carrier status on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
fprintf(stderr, "HAC: unable to check carrier status on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
}
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
/* Set the duplex on the interface if specified */
memset(cmd, 0, 256);
sprintf(cmd, "ethtool %s 2>&1", cur_int->name);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to query interface '%s' for duplex and speed: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: unable to query interface '%s' for duplex and speed: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
if(!switch_strlen_zero(cur_int->duplex)) {
sprintf(expected_duplex, "Duplex: %s", cur_int->duplex);
if(!strcasestr(cmd_result, expected_duplex)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface '%s' duplex not set correctly: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: interface '%s' duplex not set correctly: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
}
if(!switch_strlen_zero(cur_int->speed)) {
sprintf(expected_speed, "Speed: %sMb/s", cur_int->speed);
if(!strcasestr(cmd_result, expected_speed)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface '%s' speed not set correctly: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: interface '%s' speed not set correctly: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
}
switch_safe_free(cmd_result);
cur_int = cur_int->next;
}
/* If we get here, we are fairly confident all the interfaces are
working. */
return SWITCH_STATUS_SUCCESS;
}
switch_status_t initialize_firewall()
{
char *cmd_result = NULL, *cmd = NULL, *chain_start = NULL, *chain_end = NULL;
int cmd_result_len = 0, bufsize = 0;
hac_chain_list_t *chains = NULL;
hac_chain_list_t *cur = NULL;
switch_status_t status;
switch_bool_t skip_create = SWITCH_FALSE;
switch_bool_t added_delete_rule = SWITCH_FALSE;
chains = malloc(sizeof(hac_chain_list_t));
switch_assert(chains);
memset(chains, 0, sizeof(hac_chain_list_t));
cur = chains;
/* List the chains that exist */
if(execute_command("iptables -nL | grep Chain", &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result) {
switch_goto_status(SWITCH_STATUS_FALSE, done);
}
cmd_result_len = strlen(cmd_result);
chain_start = cmd_result;
chain_end = cmd_result;
/* Loop through the chains and look for ha- chains. */
while(chain_start && chain_end && chain_start < (cmd_result + cmd_result_len) && chain_end < (cmd_result + cmd_result_len)) {
chain_start = strstr(chain_end, "ha-");
if(chain_start == NULL && chain_end == cmd_result) {
switch_goto_status(SWITCH_STATUS_SUCCESS, clean);
}
chain_end = strchr(chain_start, ' ');
if(chain_start && chain_end && chain_end < (cmd_result + cmd_result_len) && chain_start < (cmd_result + cmd_result_len)) {
*chain_end = '\0';
if(cur->chain_len > 0) {
cur->next = malloc(sizeof(hac_chain_list_t));
switch_assert(cur->next);
memset(cur->next, 0, sizeof(hac_chain_list_t));
cur = cur->next;
}
cur->chain_len = strlen(chain_start);
cur->chain_name = malloc(cur->chain_len+1);
switch_assert(cur->chain_name);
memset(cur->chain_name, 0, cur->chain_len+1);
memcpy(cur->chain_name, chain_start, cur->chain_len);
snprintf(cur->chain_flush, 64, "iptables -F %s", cur->chain_name);
snprintf(cur->chain_delete, 64, "iptables -X %s", cur->chain_name);
bufsize += 35 + (2 * cur->chain_len);
chain_start = chain_end + 15;
}
}
cmd = malloc(bufsize+1);
switch_assert(bufsize);
memset(cmd, ' ', bufsize);
cmd[bufsize] = '\0';
cur = chains; chain_start = cmd;
/* Use "flush" rules first since we cannot remove referenced chains */
while(cur != NULL) {
memcpy(chain_start, cur->chain_flush, 12 + cur->chain_len);
chain_start += 12 + cur->chain_len;
if(cur->next != NULL) {
memcpy(chain_start, " && ", 4);
chain_start += 4;
}
cur = cur->next;
}
memcpy(chain_start, " && ", 4);
chain_start += 4;
cur = chains;
/* Then try to delete all the ha- chains */
while(cur != NULL) {
if(!strcasestr(cur->chain_name, "ha-cluster-rules")) {
memcpy(chain_start, cur->chain_delete, 12 + cur->chain_len);
chain_start += 12 + cur->chain_len;
if(cur->next != NULL) {
memcpy(chain_start, " && ", 4);
chain_start += 4;
}
added_delete_rule = SWITCH_TRUE;
} else {
skip_create = SWITCH_TRUE;
}
cur = cur->next;
}
if(added_delete_rule != SWITCH_TRUE) {
chain_start -= 4;
*chain_start = '\0';
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: executing '%s'\n", cmd);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result) {
switch_goto_status(SWITCH_STATUS_FALSE, done);
}
clean:
/* If the ha-cluster-rules chain does not exist, make it */
if(skip_create != SWITCH_TRUE) {
if(execute_command("iptables -N ha-cluster-rules", &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result) {
switch_goto_status(SWITCH_STATUS_FALSE, done);
}
}
done:
cur = chains;
while(cur != NULL) {
hac_chain_list_t *tmp = cur;
switch_safe_free(cur->chain_name);
cur = cur->next;
switch_safe_free(tmp);
}
switch_safe_free(cmd);
switch_safe_free(cmd_result);
return SWITCH_STATUS_SUCCESS;
}
switch_status_t verify_interfaces()
{
char *cmd_result = NULL, cmd[256];
hac_interface_t* cur_int = NULL;
struct timeval cur_time;
gettimeofday(&cur_time, NULL);
cur_int = config.network.interfaces;
while(cur_int != NULL) {
/* Check for carrier signal on interface */
memset(cmd, 0, 256);
sprintf(cmd, "ip link list dev %s 2>&1", cur_int->name);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && (strstr(cmd_result, "NO-CARRIER") || strstr(cmd_result, "DOWN")))) {
if(cmd_result && strstr(cmd_result, "NO-CARRIER")) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface '%s' loss of carrier detected\n", cur_int->name);
fprintf(stderr, "HAC: interface '%s' loss of carrier detected\n", cur_int->name);
} else if(cmd_result && strstr(cmd_result, "DOWN")) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface '%s' is down\n", cur_int->name);
fprintf(stderr, "HAC: interface '%s' is down\n", cur_int->name);
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to check carrier status on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
fprintf(stderr, "HAC: unable to check carrier status on interface '%s': %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
}
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
/* Run an internal test on the interface to help check to see
if it is good. */
memset(cmd, 0, 256);
sprintf(cmd, "ethtool -t %s 2>&1", cur_int->name);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS || !cmd_result || (cmd_result && !strstr(cmd_result, "PASS"))) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: interface '%s' failed test: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
fprintf(stderr, "HAC: interface '%s' failed test: %s\n", cur_int->name, (switch_strlen_zero(cmd_result) ? "unkown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
cur_int = cur_int->next;
}
return SWITCH_STATUS_SUCCESS;
}
switch_status_t routes_up(const hac_route_t *routes)
{
char *cmd_result = NULL, cmd[256];
const hac_route_t* cur = NULL;
cur = routes;
while(cur != NULL) {
/* Check for carrier signal on interface */
memset(cmd, 0, 256);
sprintf(cmd, "ip route add %s via %s dev %s metric %s 2>&1", cur->destination, cur->gateway, cur->dev, (switch_strlen_zero(cur->metric) ? "0" : cur->metric));
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: error bringing up route '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
fprintf(stderr, "HAC: error bringing up route '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
cur = cur->next;
}
return SWITCH_STATUS_SUCCESS;
}
switch_status_t routes_down(const hac_route_t *routes)
{
char *cmd_result = NULL, cmd[256];
const hac_route_t* cur = NULL;
cur = routes;
while(cur != NULL) {
/* Check for carrier signal on interface */
memset(cmd, 0, 256);
sprintf(cmd, "ip route del %s via %s dev %s metric %s 2>&1", cur->destination, cur->gateway, cur->dev, (switch_strlen_zero(cur->metric) ? "0" : cur->metric));
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: error bringing down route '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
fprintf(stderr, "HAC: error bringing down route '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
cur = cur->next;
}
return SWITCH_STATUS_SUCCESS;
}
switch_status_t ips_up(const hac_ip_t *ips)
{
char *cmd_result = NULL, cmd[256];
const hac_ip_t* cur = NULL;
cur = ips;
while(cur != NULL) {
/* Check for carrier signal on interface */
memset(cmd, 0, 256);
sprintf(cmd, "ip addr add %s dev %s 2>&1", cur->cidr, cur->dev);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: error adding IP address '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
fprintf(stderr, "HAC: error adding IP address '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
cur = cur->next;
}
return SWITCH_STATUS_SUCCESS;
}
switch_status_t ips_down(const hac_ip_t *ips)
{
char *cmd_result = NULL, cmd[256];
const hac_ip_t* cur = NULL;
cur = ips;
while(cur != NULL) {
/* Check for carrier signal on interface */
memset(cmd, 0, 256);
sprintf(cmd, "ip addr del %s dev %s 2>&1", cur->cidr, cur->dev);
if(execute_command(cmd, &cmd_result) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: error removing IP address '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
fprintf(stderr, "HAC: error removing IP address '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
switch_safe_free(cmd_result);
return SWITCH_STATUS_FALSE;
}
switch_safe_free(cmd_result);
cur = cur->next;
}
return SWITCH_STATUS_SUCCESS;
}
char *generate_rule_cmd(const hac_rule_t *rule, const hac_ip_t *ip, const int rule_num)
{
char *cmd = NULL, *slash = NULL;
char begin[128], action[128], match[4044], string[128], hashlimit[384],
proto[64], sport[32], dport[32], dest[256], src[256], destrange[512],
srcrange[512], length[64], mports[1024], state[256], rejectwith[128],
mark[64], ip_addr[64];
/* Validate that we will actually build a fully formed command */
if(switch_strlen_zero(rule->type)) {
goto fail;
}
if(switch_strlen_zero(rule->string) && switch_strlen_zero(rule->rate) &&
switch_strlen_zero(rule->burst) && switch_strlen_zero(rule->mode) &&
switch_strlen_zero(rule->proto) && switch_strlen_zero(rule->sport) &&
switch_strlen_zero(rule->dport) && switch_strlen_zero(rule->src) &&
switch_strlen_zero(rule->srcrange) && switch_strlen_zero(rule->length) &&
switch_strlen_zero(rule->mports) && switch_strlen_zero(rule->srcmports) &&
switch_strlen_zero(rule->dstmports) && switch_strlen_zero(rule->state) &&
switch_strlen_zero(rule->rejectwith) &&
switch_strlen_zero(rule->mark)) {
goto fail;
}
if(!strcasestr(rule->type, "limit") || !strcasestr(rule->type, "drop") ||
!strcasestr(rule->type, "accept") || !strcasestr(rule->type, "reject")) {
goto fail;
}
memset(begin, 0, sizeof(begin));
memset(action, 0, sizeof(action));
memset(match, 0, sizeof(match));
memset(string, 0, sizeof(string));
memset(hashlimit, 0, sizeof(hashlimit));
memset(proto, 0, sizeof(proto));
memset(sport, 0, sizeof(sport));
memset(dport, 0, sizeof(dport));
memset(dest, 0, sizeof(dest));
memset(src, 0, sizeof(src));
memset(destrange, 0, sizeof(destrange));
memset(srcrange, 0, sizeof(srcrange));
memset(length, 0, sizeof(length));
memset(mports, 0, sizeof(mports));
memset(state, 0, sizeof(state));
memset(rejectwith, 0, sizeof(rejectwith));
memset(mark, 0, sizeof(mark));
memset(ip_addr, 0, sizeof(ip_addr));
cmd = malloc(4300);
switch_assert(cmd);
memset(cmd, 0, 4300);
snprintf(begin, sizeof(begin),"iptables -A ha-%s", ip->name);
if(strcasestr(rule->type, "reject")) {
if(switch_strlen_zero(rule->rejectwith)) {
goto fail;
}
snprintf(action, sizeof(action), "-j REJECT --reject-with %s", rule->rejectwith);
} else if(strcasestr(rule->type, "limit")) {
if(switch_strlen_zero(rule->rate)) {
goto fail;
}
snprintf(hashlimit, sizeof(hashlimit), "iptables -N ha-%s-%s && iptables -I ha-%s-%s -m hashlimit --hashlimit-name %s-%s-%d --hashlimit %s --hashlimit-burst %s --hashlimit-mode %s --hashlimit-htable-size 24593 --hashlimit-htable-expire 90000 -j RETURN && iptables -A ha-%s-%s -j DROP", ip->name, rule->name, ip->name, rule->name, ip->name, rule->name, rule_num, rule->rate, (switch_strlen_zero(rule->burst) ? "5" : rule->burst), (switch_strlen_zero(rule->mode) ? "srcip" : rule->mode), ip->name, rule->name);
snprintf(action, sizeof(action), "-j ha-%s-%s", ip->name, rule->name);
} else if(strcasestr(rule->type, "drop")) {
snprintf(action, sizeof(action), "-j DROP");
} else if(strcasestr(rule->type, "accept")) {
snprintf(action, sizeof(action), "-j ACCEPT");
}
if(!switch_strlen_zero(rule->string)) {
snprintf(string, sizeof(string), "-m string --algo kmp --string %s", rule->string);
}
if(!switch_strlen_zero(rule->proto)) {
snprintf(proto, sizeof(proto), "-p %s", rule->proto);
}
if(!switch_strlen_zero(rule->sport)) {
snprintf(sport, sizeof(sport), "--sport %s", rule->sport);
}
if(!switch_strlen_zero(rule->dport)) {
snprintf(dport, sizeof(dport), "--dport %s", rule->dport);
}
if(!switch_strlen_zero(rule->src)) {
snprintf(src, sizeof(src), "-s %s", rule->src);
}
if(!switch_strlen_zero(rule->srcrange)) {
snprintf(srcrange, sizeof(srcrange), "-m iprange --dst-range %s", rule->srcrange);
}
if(!switch_strlen_zero(rule->length)) {
snprintf(length, sizeof(length), "-m length --length %s", rule->length);
}
if(!switch_strlen_zero(rule->mports)) {
snprintf(mports, sizeof(mports), "-m mport --ports %s", rule->mports);
}
if(!switch_strlen_zero(rule->srcmports) && switch_strlen_zero(rule->mports) && switch_strlen_zero(rule->dstmports)) {
snprintf(mports, sizeof(mports), "-m mport --source-ports %s", rule->srcmports);
} else if(!switch_strlen_zero(rule->dstmports) && switch_strlen_zero(rule->mports) && switch_strlen_zero(rule->srcmports)) {
snprintf(mports, sizeof(mports), "-m mport --destination-ports %s", rule->dstmports);
} else if(!switch_strlen_zero(rule->srcmports) && !switch_strlen_zero(rule->dstmports) && switch_strlen_zero(rule->mports)) {
snprintf(mports, sizeof(mports), "-m mport --source-ports %s --destination-ports %s", rule->srcmports, rule->dstmports);
}
if(!switch_strlen_zero(rule->state)) {
snprintf(state, sizeof(state), "-m state --state %s", rule->state);
}
if(!switch_strlen_zero(rule->mark)) {
snprintf(mark, sizeof(mark), "-m mark --mark %s", rule->mark);
}
memcpy(ip_addr, ip->cidr, strlen(ip->cidr));
if((slash = strchr(ip_addr, '/')) == NULL) {
goto fail;
}
*slash = '\0';
snprintf(dest, sizeof(dest), "-d %s", ip_addr);
snprintf(cmd, sizeof(cmd), "%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s",
begin, proto, sport, dport, src, dest,
mports, srcrange, destrange, state, mark, length, string, action,
(switch_strlen_zero(hashlimit) ? "" : " && "), hashlimit);
return cmd;
fail:
return NULL;
}
switch_status_t rules_up(const hac_rule_t *rules, const hac_ip_t *ip)
{
char *cmd_result = NULL, **cmds = NULL, *cmd = NULL, *cmd_loc = NULL;
const hac_rule_t* cur = NULL;
int num_rules = 0, cur_rule = 0, cmd_size = 0;
switch_status_t status;
/* Compute number of commands needed */
cur = rules;
while(cur != NULL) {
num_rules++;
cur = cur->next;
}
cmds = malloc(num_rules * sizeof(char*));
switch_assert(cmds);
memset(cmds, 0, num_rules * sizeof(char*));
/* Generate a command for each rule in the list */
cur = rules;
while(cur != NULL) {
cmds[cur_rule] = generate_rule_cmd(cur, ip, cur_rule);
cur_rule++;
cur = cur->next;
}
/* Make enough space for the commands and ' && ' between them */
cmd_size = 4300 * num_rules + 5 * num_rules;
cmd = malloc(cmd_size);
switch_assert(cmd);
memset(cmd, 0, cmd_size);
/* Loop through commands and dump them into a single command */
cmd_loc = cmd;
for(int r = 0; r < num_rules; r++) {
if(cmd_loc > cmd && !switch_strlen_zero(cmds[r])) {
sprintf(cmd_loc, " && %s", cmds[r]);
cmd_loc += 4 + strlen(cmds[r]);
} else if(!switch_strlen_zero(cmds[r])) {
sprintf(cmd_loc, "%s", cmds[r]);
cmd_loc += strlen(cmds[r]);
}
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: firewall rules command: %s\n", cmd);
if((status = execute_command(cmd, &cmd_result)) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: error adding firewall rules for IP address '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
fprintf(stderr, "HAC: error adding firewall rules for IP address '%s': %s\n", cmd, (switch_strlen_zero(cmd_result) ? "unknown error" : cmd_result));
switch_goto_status(SWITCH_STATUS_FALSE, done);
}
done:
if(cmds && num_rules) {
for(int r = 0; r < num_rules; r++) {
switch_safe_free(cmds[r]);
}
}
switch_safe_free(cmds);
switch_safe_free(cmd);
switch_safe_free(cmd_result);
return status;
}
/*
* High Availability Cluster Module for FreeSWITCH Modular Media Switching
* Software Library / Soft-Switch Application
*
* High Availability Cluster Module is
* Copyright (C) 2010, Eliot Gable <egable@gmail.com>
*
* FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application is
* Copyright (C) 2005-2010, Anthony Minessale II <anthm@freeswitch.org>
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is High Availability Module for FreeSWITCH Modular Media
* Switching Software Library / Soft-Switch Application
*
* The Initial Developer of the Original Code is
* Eliot Gable <egable@gmail.com>
* Portions created by the Initial Developer are Copyright (C)
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*
*/
#include <mod_ha_cluster.h>
/* Don't forget to free "out" when done with it */
switch_status_t execute_command(const char *cmd, char **out)
{
FILE* fh = NULL;
char buf[HAC_BUFFSIZE];
int ret_code = 0;
ssize_t len;
memset(buf, 0, HAC_BUFFSIZE);
#ifdef MACOSX
#elif defined(DARWIN)
#elif defined(WIN32)
#else
setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/usr/local/freeswitch/bin:/opt/bin:/opt/sbin", 1);
errno = 0;
fh = popen(cmd, "r");
if(!fh || errno) {
char errbuf[256];
memset(errbuf, 0, 256);
strerror_r(errno, errbuf, sizeof(errbuf));
if(strlen(errbuf)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to execute command '%s': %s\n", cmd, errbuf);
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to execute command '%s': process failed to open (errno %d)\n", cmd, errno);
}
return SWITCH_STATUS_FALSE;
}
len = fread(buf, 1, sizeof(buf), fh);
if(errno) {
char errbuf[256];
memset(errbuf, 0, 256);
strerror_r(errno, errbuf, sizeof(errbuf));
if(strlen(errbuf)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to read file handle: %s\n", errbuf);
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to read file handle: an unknown error occurred\n");
}
return SWITCH_STATUS_FALSE;
}
errno = 0;
ret_code = pclose(fh);
*out = malloc(len+1);
switch_assert(*out);
memset(*out, 0, len+1);
memcpy(*out, buf, len);
#endif
if(errno == ECHILD) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: unable to determine exit status of child command '%s'\n", cmd);
return SWITCH_STATUS_FALSE;
}
if(ret_code != 0) {
return SWITCH_STATUS_FALSE;
}
return SWITCH_STATUS_SUCCESS;
}
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="mod_skel"
ProjectGUID="{11C9BC3D-45E9-46E3-BE84-B8CEE4685E39}"
RootNamespace="mod_skel"
Keyword="Win32Proj"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
ConfigurationType="2"
InheritedPropertySheets="..\..\..\..\w32\module_debug.vsprops"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="..\..\..\..\w32\module_debug.vsprops"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(SolutionDir)$(PlatformName)\$(ConfigurationName)/mod/$(ProjectName).dll"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
ConfigurationType="2"
InheritedPropertySheets="..\..\..\..\w32\module_release.vsprops"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
ConfigurationType="2"
InheritedPropertySheets="..\..\..\..\w32\module_release.vsprops"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(SolutionDir)$(PlatformName)\$(ConfigurationName)/mod/$(ProjectName).dll"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="17"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath=".\mod_skel.c"
>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
/*
* High Availability Cluster Module for FreeSWITCH Modular Media Switching
* Software Library / Soft-Switch Application
*
* High Availability Cluster Module is
* Copyright (C) 2010, Eliot Gable <egable@gmail.com>
*
* FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application is
* Copyright (C) 2005-2010, Anthony Minessale II <anthm@freeswitch.org>
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is High Availability Module for FreeSWITCH Modular Media
* Switching Software Library / Soft-Switch Application
*
* The Initial Developer of the Original Code is
* Eliot Gable <egable@gmail.com>
* Portions created by the Initial Developer are Copyright (C)
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*
* mod_ha_cluster.c
*
* The HA Cluster module implements a dynamic, self-regulating cluster. It
* will auto-detect the nodes that are part of the cluster, automatically
* assign master and slave statuses based on a configured master to slave
* ratio, automatically assign node IDs, propogate registrations and call
* limiting information between cluster nodes, and automatically transfer
* calls from failed nodes to slave nodes. If the cluster reaches a state
* where no slaves are present and a slave can be safely designated from
* an existing master node, that master will relinquish its master status
* and become a slave.
*
* Most of the cluster operations are contention-free due to pre-defined
* rules on which node takes what actions based on randomly chosen node
* weights and IDs. The only contention period is during start-up when
* choosing random node weights. Because each node tracks the state of all
* other nodes and maintains a list of their weights, each node can
* independently determine which node will be taking what actions based on
* received events. Because they all share the same information, they will
* all come to the same decisions.
*
* The cluster algorithms require that all nodes are always able to see all
* other nodes in the cluster. If a network split occurs, it could cause
* something similar to a "split-brain" condition. This would be a very
* bad thing.
*
*/
#include <mod_ha_cluster.h>
/* Prototypes */
SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_ha_cluster_shutdown);
SWITCH_MODULE_RUNTIME_FUNCTION(mod_ha_cluster_runtime);
SWITCH_MODULE_LOAD_FUNCTION(mod_ha_cluster_load);
/* SWITCH_MODULE_DEFINITION(name, load, shutdown, runtime)
* Defines a switch_loadable_module_function_table_t and a static const char[] modname
*/
SWITCH_MODULE_DEFINITION(mod_ha_cluster, mod_ha_cluster_load, mod_ha_cluster_shutdown, mod_ha_cluster_runtime);
/*SWITCH_MODULE_DEFINITION(mod_ha_cluster, mod_ha_cluster_load, mod_ha_cluster_shutdown, NULL); */
unsigned char MAGIC[] = { 226, 132, 177, 197, 152, 198, 142, 211, 172, 197, 158, 208, 169, 208, 135, 197, 166, 207, 154, 196, 166 };
hac_config_t config;
struct s_global hac_globals;
/* TODO: Make this notify the admin of the system */
static void hac_notify_admin(const char* mesg)
{
}
static switch_status_t send_event(switch_event_t* event, switch_bool_t hb)
{
size_t len;
char *packet = NULL, *buf = NULL;
hac_hb_t *cur_hb = NULL;
struct timeval cur_time;
size_t tstamp = 0, tstamp_hb = 0;
switch_uuid_t uuid;
char uuid_str[SWITCH_UUID_FORMATTED_LENGTH + 1];
if(hb == SWITCH_TRUE) {
gettimeofday(&cur_time, NULL);
tstamp = cur_time.tv_sec * 1000;
tstamp += cur_time.tv_usec / 1000;
}
switch_uuid_get(&uuid);
switch_uuid_format(uuid_str, &uuid);
switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "HAC-Event-UUID", uuid_str);
if(switch_event_serialize(event, &packet, SWITCH_TRUE) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "HAC: Failed to serialize event for sending!\n");
goto failsend;
}
len = strlen(packet) + strlen((char*) MAGIC);
buf = malloc(len + 1);
memset(buf, 0, len + 1);
switch_assert(buf);
switch_copy_string(buf, packet, len);
switch_copy_string(buf + strlen(packet), (char*)MAGIC, strlen((char*)MAGIC) + 1);
/* Only one thread can write to the socket at one time, and we don't want
them changing in the middle of writes */
switch_thread_rwlock_wrlock(hac_globals.lock);
cur_hb = hac_globals.hb;
while(cur_hb != NULL) {
if(hb == SWITCH_TRUE) {
tstamp_hb = cur_hb->last_hb.tv_sec * 1000;
tstamp_hb += cur_hb->last_hb.tv_usec / 1000;
if(tstamp > tstamp_hb + atoi(cur_hb->interval)) {
switch_socket_sendto(cur_hb->udp_sock, cur_hb->addr, 0, buf, &len);
cur_hb->last_hb.tv_sec = cur_time.tv_sec;
cur_hb->last_hb.tv_usec = cur_time.tv_usec;
}
} else {
switch_socket_sendto(cur_hb->udp_sock, cur_hb->addr, 0, buf, &len);
}
cur_hb = cur_hb->next;
}
switch_thread_rwlock_unlock(hac_globals.lock);
switch_safe_free(packet);
switch_safe_free(buf);
return SWITCH_STATUS_SUCCESS;
failsend:
return SWITCH_STATUS_FALSE;
}
/*
static void clear_event_hash()
{
switch_hash_index_t *hi = NULL;
void *val;
hac_event_t *hevent;
for(hi = switch_hash_first(NULL, hac_globals.event_hash); hi; hi = switch_hash_next(hi)) {
switch_hash_this(hi, NULL, NULL, &val);
if(val) {
hevent = (hac_event_t*)val;
}
switch_safe_free(val);
}
}
static void receive_events()
{
//switch_event_t *event = NULL;
char *buf = NULL;//, *myaddr = NULL, *packet = NULL;
switch_sockaddr_t *addr;
size_t len = HAC_BUFFSIZE;
switch_status_t status;
hac_hb_t *cur_hb = NULL;
buf = (char*) malloc(HAC_BUFFSIZE);
switch_assert(buf);
memset(buf, 0, len);
switch_sockaddr_info_get(&addr, NULL, SWITCH_UNSPEC, 0, 0, hac_globals.pool);
cur_hb = hac_globals.hb;
while(cur_hb != NULL && hac_globals.mod_state == HAC_LOOPING) {
/ * Read up to 1000 events from each multicast group at a time */
/* size_t count = 0;
while((status = switch_socket_recvfrom(addr, cur_hb->udp_sock, 0, buf, &len)) == SWITCH_STATUS_SUCCESS && len && count < 1000) {
count++;
}
cur_hb = cur_hb->next;
}
}
*/
static void send_hb()
{
switch_event_t *local_event;
if (switch_event_create_subclass(&local_event, SWITCH_EVENT_CUSTOM, HAC_HEARTBEAT) == SWITCH_STATUS_SUCCESS) {
char buf[256];
memset(buf, 0, 256);
switch_thread_rwlock_rdlock(hac_globals.lock);
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "HAC-Peer", hac_globals.hostname);
sprintf(buf, "%d", hac_globals.nodeid);
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "HAC-Node-ID", buf);
memset(buf, 0, 256);
sprintf(buf, "%ld", hac_globals.rand_val);
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "HAC-Priority", buf);
switch(hac_globals.state) {
case HAC_PEER_STARTING:
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "State", "STARTING");
break;
case HAC_PEER_MASTER:
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "State", "MASTER");
break;
case HAC_PEER_SLAVE:
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "State", "SLAVE");
break;
case HAC_PEER_FAILED_MASTER:
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "State", "FAILED_MASTER");
break;
case HAC_PEER_FAILED_SLAVE:
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "State", "FAILED_SLAVE");
break;
case HAC_PEER_STOPPING_MASTER:
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "State", "STOPPING_MASTER");
break;
case HAC_PEER_STOPPING_SLAVE:
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "State", "STOPPING_SLAVE");
break;
case HAC_PEER_UNKNOWN:
default:
switch_event_add_header_string(local_event, SWITCH_STACK_BOTTOM, "State", "UNKNOWN");
break;
}
switch_thread_rwlock_unlock(hac_globals.lock);
if(send_event(local_event, SWITCH_TRUE) != SWITCH_STATUS_SUCCESS) {
hac_notify_admin("Failed to send heartbeat.");
}
}
}
static void starting_event_handler(switch_event_t *event)
{
}
static void master_event_handler(switch_event_t *event)
{
}
static void slave_event_handler(switch_event_t *event)
{
/* on a takover, load sofia */
/* if (switch_loadable_module_load_module((char *) SWITCH_GLOBAL_dirs.mod_dir, "mod_sofia", SWITCH_TRUE, &err) != SWITCH_STATUS_SUCCESS) {
}*/
}
static void failed_master_event_handler(switch_event_t *event)
{
}
static void failed_slave_event_handler(switch_event_t *event)
{
}
static void stopping_master_event_handler(switch_event_t *event)
{
}
static void stopping_slave_event_handler(switch_event_t *event)
{
}
static void event_handler(switch_event_t *event)
{
hac_peer_state_t state;
switch_thread_rwlock_rdlock(hac_globals.lock);
state = hac_globals.state;
switch_thread_rwlock_unlock(hac_globals.lock);
switch(state) {
case HAC_PEER_STARTING:
starting_event_handler(event);
break;
case HAC_PEER_MASTER:
master_event_handler(event);
break;
case HAC_PEER_SLAVE:
slave_event_handler(event);
break;
case HAC_PEER_FAILED_MASTER:
failed_master_event_handler(event);
break;
case HAC_PEER_FAILED_SLAVE:
failed_slave_event_handler(event);
break;
case HAC_PEER_STOPPING_MASTER:
stopping_master_event_handler(event);
break;
case HAC_PEER_STOPPING_SLAVE:
stopping_slave_event_handler(event);
break;
default:
break;
}
}
SWITCH_STANDARD_API(ha_cluster_function)
{
do_config(SWITCH_TRUE);
return SWITCH_STATUS_SUCCESS;
}
/* Macro expands to: switch_status_t mod_ha_cluster_load(switch_loadable_module_interface_t **module_interface, switch_memory_pool_t *pool) */
SWITCH_MODULE_LOAD_FUNCTION(mod_ha_cluster_load)
{
switch_api_interface_t *api_interface;
switch_status_t status;
sigset_t set, oset;
hac_hb_t *cur_hb;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGPIPE);
sigprocmask(SIG_BLOCK, &set, &oset);
memset(&hac_globals, 0, sizeof(hac_globals));
hac_globals.state = HAC_PEER_STARTING;
hac_globals.mod_state = HAC_LOOPING;
hac_globals.pool = pool;
gethostname(hac_globals.hostname, sizeof(hac_globals.hostname));
switch_thread_rwlock_create(&hac_globals.lock, pool);
switch_core_new_memory_pool(&hac_globals.event_pool);
switch_core_hash_init(&hac_globals.event_hash, pool);
switch_core_hash_init(&hac_globals.peer_hash, pool);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "HAC: Loading configuration...\n");
if(do_config(SWITCH_FALSE) == SWITCH_STATUS_FALSE) {
switch_goto_status(SWITCH_STATUS_TERM, fail);
}
cur_hb = hac_globals.hb;
while(cur_hb != NULL) {
char *ip;
if (switch_sockaddr_info_get(&cur_hb->addr, cur_hb->address, SWITCH_UNSPEC, cur_hb->lport, 0, hac_globals.pool) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Cannot find address.\n");
switch_goto_status(SWITCH_STATUS_TERM, fail);
}
if (switch_sockaddr_info_get(&cur_hb->iface, cur_hb->network, SWITCH_UNSPEC, cur_hb->lport, 0, hac_globals.pool) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Cannot find address.\n");
switch_goto_status(SWITCH_STATUS_TERM, fail);
}
switch_sockaddr_ip_get(&ip, cur_hb->iface);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CONSOLE, "HAC: IP of Multicast Interface: %s\n", ip);
if(switch_socket_create(&cur_hb->udp_sock, AF_INET, SOCK_DGRAM, 0, hac_globals.pool) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Socket Error\n");
switch_goto_status(SWITCH_STATUS_TERM, fail);
}
if(switch_socket_opt_set(cur_hb->udp_sock, SWITCH_SO_REUSEADDR, 1) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Socket Option Error\n");
switch_goto_status(SWITCH_STATUS_TERM, fail);
}
if(switch_mcast_join(cur_hb->udp_sock, cur_hb->addr, cur_hb->iface, NULL) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Multicast Error\n");
switch_goto_status(SWITCH_STATUS_TERM, fail);
}
if(switch_mcast_hops(cur_hb->udp_sock, (switch_strlen_zero(cur_hb->ttl) ? 1 : atoi(cur_hb->ttl))) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Failed to set ttl to '%s'\n", cur_hb->ttl);
switch_goto_status(SWITCH_STATUS_TERM, fail);
}
if(switch_socket_bind(cur_hb->udp_sock, cur_hb->iface) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Bind Error\n");
switch_goto_status(SWITCH_STATUS_TERM, fail);
}
cur_hb = cur_hb->next;
}
if(switch_event_reserve_subclass(HAC_HEARTBEAT) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_HEARTBEAT);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_LIMIT_UP) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_LIMIT_UP);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_LIMIT_DOWN) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_LIMIT_DOWN);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_REGISTER) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_REGISTER);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_UNREGISTER) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_UNREGISTER);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_STARTUP) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_STARTUP);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_SHUTDOWN) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_SHUTDOWN);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_FAILURE) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_FAILURE);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_CHOSE_RANDOM) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_CHOSE_RANDOM);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_TAKEOVER) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_TAKEOVER);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if(switch_event_reserve_subclass(HAC_RELINQUISH) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't register subclass %s!\n", HAC_RELINQUISH);
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
if (switch_event_bind(modname, SWITCH_EVENT_ALL, SWITCH_EVENT_SUBCLASS_ANY, event_handler, NULL) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "HAC: Couldn't bind to events.\n");
switch_goto_status(SWITCH_STATUS_GENERR, fail);
}
/* connect my internal structure to the blank pointer passed to me */
*module_interface = switch_loadable_module_create_module_interface(pool, modname);
SWITCH_ADD_API(api_interface, "ha_cluster", "HA Cluster API", ha_cluster_function, "syntax");
sigprocmask(SIG_SETMASK, &oset, &set);
return SWITCH_STATUS_SUCCESS;
fail:
sigprocmask(SIG_SETMASK, &oset, &set);
cur_hb = hac_globals.hb;
while(cur_hb != NULL) {
if (cur_hb->udp_sock) {
switch_socket_close(cur_hb->udp_sock);
}
cur_hb = cur_hb->next;
}
switch_event_free_subclass(HAC_LIMIT_UP);
switch_event_free_subclass(HAC_LIMIT_DOWN);
switch_event_free_subclass(HAC_REGISTER);
switch_event_free_subclass(HAC_UNREGISTER);
switch_event_free_subclass(HAC_STARTUP);
switch_event_free_subclass(HAC_SHUTDOWN);
switch_event_free_subclass(HAC_FAILURE);
switch_event_free_subclass(HAC_CHOSE_RANDOM);
switch_event_free_subclass(HAC_TAKEOVER);
switch_event_free_subclass(HAC_RELINQUISH);
return status;
}
/*
Called when the system shuts down
Macro expands to: switch_status_t mod_ha_cluster_shutdown() */
SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_ha_cluster_shutdown)
{
/* Cleanup dynamically allocated config settings */
/*switch_xml_config_cleanup(instructions);*/
hac_hb_t *cur_hb = NULL;
hac_globals.mod_state = HAC_SHUTDOWN_RUNTIME;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Waiting for runtime thread...\n");
while(hac_globals.mod_state == HAC_SHUTDOWN_RUNTIME) switch_yield(1000);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Commencing module cleanup...\n");
switch_core_hash_destroy(&hac_globals.event_hash);
switch_core_hash_destroy(&hac_globals.peer_hash);
cur_hb = hac_globals.hb;
while(cur_hb != NULL) {
if (cur_hb->udp_sock) {
switch_socket_close(cur_hb->udp_sock);
}
cur_hb = cur_hb->next;
}
switch_event_free_subclass(HAC_LIMIT_UP);
switch_event_free_subclass(HAC_LIMIT_DOWN);
switch_event_free_subclass(HAC_REGISTER);
switch_event_free_subclass(HAC_UNREGISTER);
switch_event_free_subclass(HAC_STARTUP);
switch_event_free_subclass(HAC_SHUTDOWN);
switch_event_free_subclass(HAC_FAILURE);
switch_event_free_subclass(HAC_CHOSE_RANDOM);
switch_event_free_subclass(HAC_TAKEOVER);
switch_event_free_subclass(HAC_RELINQUISH);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Unloading module...\n");
return SWITCH_STATUS_SUCCESS;
}
/*
If it exists, this is called in it's own thread when the module-load completes
If it returns anything but SWITCH_STATUS_TERM it will be called again automatically
Macro expands to: switch_status_t mod_ha_cluster_runtime()
*/
SWITCH_MODULE_RUNTIME_FUNCTION(mod_ha_cluster_runtime)
{
int arg = 0;
switch_yield(500000);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Starting processing...\n");
hac_globals.mod_state = HAC_LOOPING;
if(initialize_interfaces() != SWITCH_STATUS_SUCCESS) {
switch_core_session_ctl(SCSC_SHUTDOWN_NOW, &arg);
}
if(initialize_firewall() != SWITCH_STATUS_SUCCESS) {
switch_core_session_ctl(SCSC_SHUTDOWN_NOW, &arg);
}
while(hac_globals.mod_state == HAC_LOOPING)
{
/*switch_cond_next();*/
switch_yield(1000);
send_hb();
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE, "Shutting down...\n");
hac_globals.mod_state = HAC_UNLOAD;
return SWITCH_STATUS_TERM;
}
/* For Emacs:
* Local Variables:
* mode:c
* indent-tabs-mode:t
* tab-width:4
* c-basic-offset:4
* End:
* For VIM:
* vim:set softtabstop=4 shiftwidth=4 tabstop=4
*/
#ifndef _HA_CLUSTER_H_
#define _HA_CLUSTER_H_
#include <switch.h>
#include <sys/time.h>
#include <errno.h>
#define HAC_BUFFSIZE 65536
#define HAC_HEARTBEAT "ha_cluster::heartbeat" /* Call limit was just set up */
#define HAC_LIMIT_UP "ha_cluster::limit_up" /* Call limit was just set up */
#define HAC_LIMIT_DOWN "ha_cluster::limit_down" /* Call limit was just removed */
#define HAC_REGISTER "ha_cluster::register" /* Register event occured here */
#define HAC_UNREGISTER "ha_cluster::unregister" /* De-register event occured here */
#define HAC_STARTUP "ha_cluster::startup" /* This node just started */
#define HAC_SHUTDOWN "ha_cluster::shutdown" /* This node is shutting down */
#define HAC_FAILURE "ha_cluster::failure" /* This node just failed in some way */
#define HAC_CHOSE_RANDOM "ha_cluster::random" /* This node just picked a random number */
#define HAC_TAKEOVER "ha_cluster::takeover" /* This node is taking over another node */
#define HAC_RELINQUISH "ha_cluster::relinquish" /* This node is relinquishing master state to ensure we have a slave */
extern unsigned char MAGIC[];
/*static char *MARKER = "1"; */
typedef enum {
HAC_PEER_UNKNOWN = 0,
HAC_PEER_STARTING = 1,
HAC_PEER_MASTER = 2,
HAC_PEER_SLAVE = 3,
HAC_PEER_FAILED_MASTER = 4,
HAC_PEER_FAILED_SLAVE = 5,
HAC_PEER_STOPPING_MASTER = 6,
HAC_PEER_STOPPING_SLAVE = 7
} hac_peer_state_t;
struct s_hac_rule {
const char* name;
const char* type;
const char* string;
const char* rate;
const char* burst;
const char* mode;
const char* proto;
const char* sport;
const char* dport;
const char* src;
const char* srcrange;
const char* length;
const char* mports;
const char* srcmports;
const char* dstmports;
const char* state;
const char* rejectwith;
const char* mark;
struct s_hac_rule* next;
};
typedef struct s_hac_rule hac_rule_t;
struct s_hac_rule_group {
const char* name;
hac_rule_t* rules;
struct s_hac_rule_group* next;
};
typedef struct s_hac_rule_group hac_rule_group_t;
struct s_hac_route {
const char* name;
const char* destination;
const char* gateway;
const char* metric;
const char* dev;
struct s_hac_route* next;
};
typedef struct s_hac_route hac_route_t;
struct s_hac_arp {
const char* ip;
const char* mac;
const char* dev;
struct s_hac_arp* next;
};
typedef struct s_hac_arp hac_arp_t;
struct s_hac_ip {
const char* name;
const char* cidr;
const char* var;
const char* dev;
const char* rgroup;
hac_route_t* routes;
struct s_hac_ip* next;
};
typedef struct s_hac_ip hac_ip_t;
struct s_hac_cluster_ips {
const char* name;
const char* vmac;
const char* dev;
hac_ip_t* ips;
hac_route_t* routes;
struct s_hac_cluster_ips* next;
};
typedef struct s_hac_cluster_ips hac_cluster_ips_t;
struct s_hac_failover_ips {
const char* name;
const char* nodes;
const char* dev;
hac_ip_t* ips;
hac_route_t* routes;
struct s_hac_failover_ips* next;
};
typedef struct s_hac_failover_ips hac_failover_ips_t;
struct s_hac_interface {
const char* name;
const char* description;
const char* duplex;
const char* speed;
hac_cluster_ips_t* cips;
hac_failover_ips_t* fips;
hac_ip_t* ips;
hac_route_t* routes;
hac_arp_t* arps;
struct s_hac_interface* next;
};
typedef struct s_hac_interface hac_interface_t;
struct s_hac_failover_group {
const char* name;
const char* include_type;
const char** include_names;
int num_includes;
struct s_hac_failover_group *next;
};
typedef struct s_hac_failover_group hac_failover_group_t;
struct s_hac_network {
hac_rule_group_t* rgroups;
hac_interface_t* interfaces;
hac_failover_group_t* fgroups;
int num_interfaces;
int num_groups;
};
typedef struct s_hac_network hac_network_t;
struct s_hac_hb {
const char* interval;
const char* network;
const char* address;
const char* port;
const char* ttl;
switch_port_t lport;
switch_sockaddr_t *addr;
switch_sockaddr_t *iface;
switch_socket_t *udp_sock;
struct timeval last_hb;
struct s_hac_hb* next;
};
typedef struct s_hac_hb hac_hb_t;
struct s_hac_event_match {
const char* name;
const char* value;
struct s_hac_event_match* next;
};
typedef struct s_hac_event_match hac_event_match_t;
struct s_hac_failover {
const char* event;
hac_event_match_t* match_rules;
struct s_hac_failover* next;
};
typedef struct s_hac_failover hac_failover_t;
struct s_hac_general {
const char* nodeid;
const char* msr;
const char* timer_a;
const char* timer_b;
const char* failure_threshold;
hac_hb_t* heartbeat;
hac_failover_t* failover;
size_t num_failover_conditions;
};
typedef struct s_hac_general hac_general_t;
struct s_hac_config {
hac_network_t network;
hac_general_t general;
switch_memory_pool_t* pool;
};
typedef struct s_hac_config hac_config_t;
typedef enum {
HAC_LOOPING = 0,
HAC_SHUTDOWN_RUNTIME = 1,
HAC_UNLOAD = 2
} hac_state_t;
extern hac_config_t config;
struct s_hac_event {
switch_event_t *event;
switch_bool_t processed;
struct timeval arrived;
};
typedef struct s_hac_event hac_event_t;
struct s_hac_chain_list {
char *chain_name;
int chain_len;
char chain_flush[64];
char chain_delete[64];
struct s_hac_chain_list *next;
};
typedef struct s_hac_chain_list hac_chain_list_t;
struct s_hac_peer {
char hostname[256];
char* ip;
int nodeid;
uint64_t rand_val;
struct timeval first_seen;
struct timeval last_seen;
hac_peer_state_t state;
uint64_t missed_beats;
};
typedef struct s_hac_peer hac_peer_t;
struct s_global {
switch_memory_pool_t* pool;
char hostname[256];
uint64_t host_hash;
switch_memory_pool_t* event_pool;
switch_hash_t *event_hash;
switch_hash_t *peer_hash;
hac_peer_state_t state;
hac_state_t mod_state;
hac_hb_t* hb;
int nodeid;
uint64_t rand_val;
const char* msr;
int req_masters;
int masters;
int slaves;
int timer_a_dur;
int timer_b_dur;
struct timeval timer_a;
struct timeval timer_b;
int failure_threshold;
switch_thread_rwlock_t *lock;
};
extern struct s_global hac_globals;
/* ha_cluster_util.c */
switch_status_t execute_command(const char *cmd, char **out);
/* ha_cluster_config.c */
switch_status_t config_routes(hac_route_t **routes, switch_xml_t root, const char *dev);
switch_status_t config_arp(hac_arp_t **arps, switch_xml_t root, const char *dev);
switch_status_t config_ips(hac_ip_t** ips, switch_xml_t root, const char *dev);
switch_status_t config_cluster_ips(hac_cluster_ips_t **cips, switch_xml_t root, const char *dev);
switch_status_t config_failover_ips(hac_failover_ips_t **fips, switch_xml_t root, const char *dev);
switch_status_t config_interfaces(hac_interface_t **ints, switch_xml_t root);
switch_status_t config_rules(hac_rule_t** rules, switch_xml_t root);
switch_status_t config_rule_groups(hac_rule_group_t** rgroups, switch_xml_t root);
switch_status_t config_failover_groups(hac_failover_group_t** fover, switch_xml_t root);
switch_status_t config_network(switch_xml_t root);
switch_status_t config_hb(hac_hb_t** hb, switch_xml_t root);
switch_status_t config_events(hac_event_match_t** events, switch_xml_t root);
switch_status_t config_failover(hac_failover_t** fover, switch_xml_t root);
switch_status_t config_general(switch_xml_t root);
switch_status_t do_config(switch_bool_t reload);
/* ha_cluster_interfaces.c */
switch_status_t initialize_interfaces();
switch_status_t initialize_firewall();
switch_status_t verify_interfaces();
switch_status_t routes_up(const hac_route_t *routes);
switch_status_t routes_down(const hac_route_t *routes);
switch_status_t ips_up(const hac_ip_t *ips);
switch_status_t ips_down(const hac_ip_t *ips);
char *generate_rule_cmd(const hac_rule_t *rule, const hac_ip_t *ip, const int rule_num);
switch_status_t rules_up(const hac_rule_t *rules, const hac_ip_t *ip);
#endif
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论