diff --git a/ci/build.sh b/ci/build.sh index c331e9ab4..b900ddc05 100755 --- a/ci/build.sh +++ b/ci/build.sh @@ -1,82 +1,93 @@ #!/usr/bin/env bash set -o pipefail [[ "${DEBUG:-}" ]] && set -x declare -i failed failed=0 # SC2046: Quote this to prevent word splitting. # SC1090: Can't follow non-constant source. Use a directive to specify location. # SC2039: In POSIX sh, 'local' is undefined. # SC2086: Double quote to prevent globbing and word splitting. # SC2154: var is referenced but not assigned. ignored_errors="SC1090,SC2039,SC2154" success() { printf "\r\033[2K [ \033[00;32mOK\033[0m ] Checking %s...\n" "$1" } warn() { printf "\r\033[2K [\033[0;33mWARNING\033[0m] Checking %s...\n" "$1" } fail() { printf "\r\033[2K [\033[0;31mFAIL\033[0m] Checking %s...\n" "$1" failed=$((failed + 1)) } check() { local script="$1" out="$(shellcheck -s sh -f gcc -x -e "$ignored_errors" "$script" 2>&1)" rc=$? if [ $rc -eq 0 ]; then success "$script" elif echo "$out" | grep -i 'error' >/dev/null; then fail "$script" else warn "$script" fi echo "$out" } find_prunes() { local prunes="! -path './.git/*'" if [ -f .gitmodules ]; then while read -r module; do prunes="$prunes ! -path './$module/*'" done < <(grep path .gitmodules | awk '{print $3}') fi echo "$prunes" } find_cmd() { - echo "find heartbeat -type f -and \( -perm /111 -or -name '*.sh' \) $(find_prunes)" + echo "find heartbeat -type f -and \( -perm /111 -or -name '*.sh' -or -name '*.c' -or -name '*.in' \) $(find_prunes)" } check_all_executables() { echo "Checking executables and .sh files..." while read -r script; do file --mime "$script" | grep 'charset=binary' >/dev/null 2>&1 && continue file --mime "$script" | grep 'text/x-python' >/dev/null 2>&1 && continue + # upstream CI doesnt detect MIME-format correctly for Makefiles + [[ "$script" =~ .*/Makefile.in ]] && continue + + if grep -qE "\ * Copyright (c) 2004 International Business Machines * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* * It can add an IPv6 address, or remove one. * * Usage: IPv6addr {start|stop|status|monitor|meta-data} * * The "start" arg adds an IPv6 address. * The "stop" arg removes one. * The "status" arg shows whether the IPv6 address exists * The "monitor" arg shows whether the IPv6 address can be pinged (ICMPv6 ECHO) * The "meta_data" arg shows the meta data(XML) */ /* * ipv6-address: * * currently the following forms are legal: * address * address/prefix * * E.g. * 3ffe:ffff:0:f101::3 * 3ffe:ffff:0:f101::3/64 * * It should be passed by environment variant: * OCF_RESKEY_ipv6addr=3ffe:ffff:0:f101::3 * OCF_RESKEY_cidr_netmask=64 * OCF_RESKEY_nic=eth0 * */ /* * start: * 1.IPv6addr will choice a proper interface for the new address. * 2.Then assign the new address to the interface. * 3.Wait until the new address is available (reply ICMPv6 ECHO packet) * 4.Send out the unsolicited advertisements. * * return 0(OCF_SUCCESS) for success * return 1(OCF_ERR_GENERIC) for failure * return 2(OCF_ERR_ARGS) for invalid or excess argument(s) * * * stop: * remove the address from the inferface. * * return 0(OCF_SUCCESS) for success * return 1(OCF_ERR_GENERIC) for failure * return 2(OCF_ERR_ARGS) for invalid or excess argument(s) * * status: * return the status of the address. only check whether it exists. * * return 0(OCF_SUCCESS) for existing * return 1(OCF_NOT_RUNNING) for not existing * return 2(OCF_ERR_ARGS) for invalid or excess argument(s) * * * monitor: * ping the address by ICMPv6 ECHO request. * * return 0(OCF_SUCCESS) for response correctly. * return 1(OCF_NOT_RUNNING) for no response. * return 2(OCF_ERR_ARGS) for invalid or excess argument(s) */ #include #include #include #include #include #include #include #include #include #include /* for inet_pton */ #include /* for if_nametoindex */ #include #include #include #include #include #include #include #include #define PIDFILE_BASE HA_RSCTMPDIR "/IPv6addr-" /* 0 No error, action succeeded completely 1 generic or unspecified error (current practice) The "monitor" operation shall return this for a crashed, hung or otherwise non-functional resource. 2 invalid or excess argument(s) Likely error code for validate-all, if the instance parameters do not validate. Any other action is free to also return this exit status code for this case. 3 unimplemented feature (for example, "reload") 4 user had insufficient privilege 5 program is not installed 6 program is not configured 7 program is not running 8 resource is running in "master" mode and fully operational 9 resource is in "master" mode but in a failed state */ #define OCF_SUCCESS 0 #define OCF_ERR_GENERIC 1 #define OCF_ERR_ARGS 2 #define OCF_ERR_UNIMPLEMENTED 3 #define OCF_ERR_PERM 4 #define OCF_ERR_INSTALLED 5 #define OCF_ERR_CONFIGURED 6 #define OCF_NOT_RUNNING 7 const char* APP_NAME = "IPv6addr"; const char* START_CMD = "start"; const char* STOP_CMD = "stop"; const char* STATUS_CMD = "status"; const char* MONITOR_CMD = "monitor"; const char* ADVT_CMD = "advt"; const char* RECOVER_CMD = "recover"; const char* RELOAD_CMD = "reload"; const char* META_DATA_CMD = "meta-data"; const char* VALIDATE_CMD = "validate-all"; const int QUERY_COUNT = 5; struct in6_ifreq { struct in6_addr ifr6_addr; uint32_t ifr6_prefixlen; unsigned int ifr6_ifindex; }; static int start_addr6(struct in6_addr* addr6, int prefix_len, char* prov_ifname); static int stop_addr6(struct in6_addr* addr6, int prefix_len, char* prov_ifname); static int status_addr6(struct in6_addr* addr6, int prefix_len, char* prov_ifname); static int monitor_addr6(struct in6_addr* addr6, int prefix_len); static int advt_addr6(struct in6_addr* addr6, int prefix_len, char* prov_ifname); static int meta_data_addr6(void); static void usage(const char* self); int write_pid_file(const char *pid_file); int create_pid_directory(const char *pid_file); static void byebye(int nsig); static char* scan_if(struct in6_addr* addr_target, int* plen_target, int use_mask, char* prov_ifname); static char* find_if(struct in6_addr* addr_target, int* plen_target, char* prov_ifname); static char* get_if(struct in6_addr* addr_target, int* plen_target, char* prov_ifname); static int assign_addr6(struct in6_addr* addr6, int prefix_len, char* if_name); static int unassign_addr6(struct in6_addr* addr6, int prefix_len, char* if_name); int is_addr6_available(struct in6_addr* addr6); int main(int argc, char* argv[]) { char pid_file[256]; char* ipv6addr; char* cidr_netmask; int ret; char* cp; char* prov_ifname = NULL; int prefix_len = -1; struct in6_addr addr6; /* Check the count of parameters first */ if (argc < 2) { usage(argv[0]); return OCF_ERR_ARGS; } /* set termination signal */ siginterrupt(SIGTERM, 1); signal(SIGTERM, byebye); /* open system log */ cl_log_set_entity(APP_NAME); cl_log_set_facility(LOG_DAEMON); /* the meta-data dont need any parameter */ if (0 == strncmp(META_DATA_CMD, argv[1], strlen(META_DATA_CMD))) { ret = meta_data_addr6(); return OCF_SUCCESS; } /* check the OCF_RESKEY_ipv6addr parameter, should be an IPv6 address */ ipv6addr = getenv("OCF_RESKEY_ipv6addr"); if (ipv6addr == NULL) { cl_log(LOG_ERR, "Please set OCF_RESKEY_ipv6addr to the IPv6 address you want to manage."); usage(argv[0]); return OCF_ERR_ARGS; } /* legacy option */ if ((cp = strchr(ipv6addr, '/'))) { prefix_len = atol(cp + 1); if ((prefix_len < 0) || (prefix_len > 128)) { cl_log(LOG_ERR, "Invalid prefix_len [%s], should be an integer in [0, 128]", cp+1); usage(argv[0]); return OCF_ERR_ARGS; } *cp=0; } /* get provided netmask (optional) */ cidr_netmask = getenv("OCF_RESKEY_cidr_netmask"); if (cidr_netmask != NULL) { if ((atol(cidr_netmask) < 0) || (atol(cidr_netmask) > 128)) { cl_log(LOG_ERR, "Invalid prefix_len [%s], " "should be an integer in [0, 128]", cidr_netmask); usage(argv[0]); return OCF_ERR_ARGS; } if (prefix_len != -1 && prefix_len != atol(cidr_netmask)) { cl_log(LOG_DEBUG, "prefix_len(%d) is overwritted by cidr_netmask(%s)", prefix_len, cidr_netmask); } prefix_len = atol(cidr_netmask); } else if (prefix_len == -1) { prefix_len = 0; } /* get provided interface name (optional) */ prov_ifname = getenv("OCF_RESKEY_nic"); if (inet_pton(AF_INET6, ipv6addr, &addr6) <= 0) { cl_log(LOG_ERR, "Invalid IPv6 address [%s]", ipv6addr); usage(argv[0]); return OCF_ERR_ARGS; } /* Check whether this system supports IPv6 */ if (access(IF_INET6, R_OK)) { cl_log(LOG_ERR, "No support for INET6 on this system."); return OCF_ERR_GENERIC; } /* create the pid file so we can make sure that only one IPv6addr * for this address is running */ if (snprintf(pid_file, sizeof(pid_file), "%s%s", PIDFILE_BASE, ipv6addr) >= (int)sizeof(pid_file)) { cl_log(LOG_ERR, "Pid file truncated"); return OCF_ERR_GENERIC; } if (write_pid_file(pid_file) < 0) { return OCF_ERR_GENERIC; } /* switch the command */ if (0 == strncmp(START_CMD,argv[1], strlen(START_CMD))) { ret = start_addr6(&addr6, prefix_len, prov_ifname); }else if (0 == strncmp(STOP_CMD,argv[1], strlen(STOP_CMD))) { ret = stop_addr6(&addr6, prefix_len, prov_ifname); }else if (0 == strncmp(STATUS_CMD,argv[1], strlen(STATUS_CMD))) { ret = status_addr6(&addr6, prefix_len, prov_ifname); }else if (0 ==strncmp(MONITOR_CMD,argv[1], strlen(MONITOR_CMD))) { ret = monitor_addr6(&addr6, prefix_len); }else if (0 ==strncmp(RELOAD_CMD,argv[1], strlen(RELOAD_CMD))) { ret = OCF_ERR_UNIMPLEMENTED; }else if (0 ==strncmp(RECOVER_CMD,argv[1], strlen(RECOVER_CMD))) { ret = OCF_ERR_UNIMPLEMENTED; }else if (0 ==strncmp(VALIDATE_CMD,argv[1], strlen(VALIDATE_CMD))) { /* ipv6addr has been validated by inet_pton, hence a valid IPv6 address */ ret = OCF_SUCCESS; }else if (0 ==strncmp(ADVT_CMD,argv[1], strlen(MONITOR_CMD))) { ret = advt_addr6(&addr6, prefix_len, prov_ifname); }else{ usage(argv[0]); ret = OCF_ERR_ARGS; } /* release the pid file */ unlink(pid_file); return ret; } int start_addr6(struct in6_addr* addr6, int prefix_len, char* prov_ifname) { int i; char* if_name; if(OCF_SUCCESS == status_addr6(addr6,prefix_len,prov_ifname)) { return OCF_SUCCESS; } /* we need to find a proper device to assign the address */ if_name = find_if(addr6, &prefix_len, prov_ifname); if (NULL == if_name) { cl_log(LOG_ERR, "no valid mechanisms"); return OCF_ERR_GENERIC; } /* Assign the address */ if (0 != assign_addr6(addr6, prefix_len, if_name)) { cl_log(LOG_ERR, "failed to assign the address to %s", if_name); return OCF_ERR_GENERIC; } /* Check whether the address available */ for (i = 0; i < QUERY_COUNT; i++) { if (0 == is_addr6_available(addr6)) { break; } sleep(1); } if (i == QUERY_COUNT) { cl_log(LOG_ERR, "failed to ping the address"); return OCF_ERR_GENERIC; } /* Send unsolicited advertisement packet to neighbor */ for (i = 0; i < UA_REPEAT_COUNT; i++) { send_ua(addr6, if_name); sleep(1); } return OCF_SUCCESS; } int advt_addr6(struct in6_addr* addr6, int prefix_len, char* prov_ifname) { /* First, we need to find a proper device to assign the address */ char* if_name = get_if(addr6, &prefix_len, prov_ifname); int i; if (NULL == if_name) { cl_log(LOG_ERR, "no valid mechanisms"); return OCF_ERR_GENERIC; } /* Send unsolicited advertisement packet to neighbor */ for (i = 0; i < UA_REPEAT_COUNT; i++) { send_ua(addr6, if_name); sleep(1); } return OCF_SUCCESS; } int stop_addr6(struct in6_addr* addr6, int prefix_len, char* prov_ifname) { char* if_name; if(OCF_NOT_RUNNING == status_addr6(addr6,prefix_len,prov_ifname)) { return OCF_SUCCESS; } if_name = get_if(addr6, &prefix_len, prov_ifname); if (NULL == if_name) { cl_log(LOG_ERR, "no valid mechanisms."); /* I think this should be a success exit according to LSB. */ return OCF_ERR_GENERIC; } /* Unassign the address */ if (0 != unassign_addr6(addr6, prefix_len, if_name)) { cl_log(LOG_ERR, "failed to assign the address to %s", if_name); return OCF_ERR_GENERIC; } return OCF_SUCCESS; } int status_addr6(struct in6_addr* addr6, int prefix_len, char* prov_ifname) { char* if_name = get_if(addr6, &prefix_len, prov_ifname); if (NULL == if_name) { return OCF_NOT_RUNNING; } return OCF_SUCCESS; } int monitor_addr6(struct in6_addr* addr6, int prefix_len) { if(0 == is_addr6_available(addr6)) { return OCF_SUCCESS; } return OCF_NOT_RUNNING; } /* find the network interface associated with an address */ char* scan_if(struct in6_addr* addr_target, int* plen_target, int use_mask, char* prov_ifname) { FILE *f; static char devname[21]=""; struct in6_addr addr; struct in6_addr mask; unsigned int plen, scope, dad_status, if_idx; unsigned int addr6p[4]; /* open /proc/net/if_inet6 file */ if ((f = fopen(IF_INET6, "r")) == NULL) { return NULL; } /* Loop for each entry */ while (1) { int i; int n; int s; gboolean same = TRUE; i = fscanf(f, "%08x%08x%08x%08x %x %02x %02x %02x %20s\n", &addr6p[0], &addr6p[1], &addr6p[2], &addr6p[3], &if_idx, &plen, &scope, &dad_status, devname); if (i == EOF) { break; } else if (i != 9) { cl_log(LOG_INFO, "Error parsing %s, " "perhaps the format has changed\n", IF_INET6); break; } /* Consider link-local addresses (scope == 0x20) only when * the inerface name is provided, and global addresses * (scope == 0). Skip everything else. */ if (scope != 0) { if (scope != 0x20 || prov_ifname == 0 || *prov_ifname == 0) continue; } /* If specified prefix, only same prefix entry * would be considered. */ if (*plen_target!=0 && plen != *plen_target) { continue; } /* If interface name provided, only same devname entry * would be considered */ if (prov_ifname!=0 && *prov_ifname!=0) { if (strcmp(devname, prov_ifname)) continue; } for (i = 0; i< 4; i++) { addr.s6_addr32[i] = htonl(addr6p[i]); } /* Make the mask based on prefix length */ memset(mask.s6_addr, 0xff, 16); if (use_mask && plen < 128) { n = plen / 32; memset(mask.s6_addr32 + n + 1, 0, (3 - n) * 4); s = 32 - plen % 32; if (s == 32) mask.s6_addr32[n] = 0x0; else mask.s6_addr32[n] = 0xffffffff << s; mask.s6_addr32[n] = htonl(mask.s6_addr32[n]); } /* compare addr and addr_target */ same = TRUE; for (i = 0; i < 4; i++) { if ((addr.s6_addr32[i]&mask.s6_addr32[i]) != (addr_target->s6_addr32[i]&mask.s6_addr32[i])) { same = FALSE; break; } } /* We found it! */ if (same) { fclose(f); *plen_target = plen; return devname; } } fclose(f); return NULL; } /* find a proper network interface to assign the address */ char* find_if(struct in6_addr* addr_target, int* plen_target, char* prov_ifname) { char *best_ifname = scan_if(addr_target, plen_target, 1, prov_ifname); /* use the provided ifname and prefix if the address did not match */ if (best_ifname == NULL && prov_ifname != 0 && *prov_ifname != 0 && *plen_target != 0) { cl_log(LOG_INFO, "Could not find a proper interface by the ipv6addr. Using the specified nic:'%s' and cidr_netmask:'%d'", prov_ifname, *plen_target); return prov_ifname; } return best_ifname; } /* get the device name and the plen_target of a special address */ char* get_if(struct in6_addr* addr_target, int* plen_target, char* prov_ifname) { return scan_if(addr_target, plen_target, 0, prov_ifname); } int assign_addr6(struct in6_addr* addr6, int prefix_len, char* if_name) { struct in6_ifreq ifr6; /* Get socket first */ int fd; struct ifreq ifr; fd = socket(AF_INET6, SOCK_DGRAM, 0); if (fd < 0) { return 1; } /* Query the index of the if */ strcpy(ifr.ifr_name, if_name); if (ioctl(fd, SIOGIFINDEX, &ifr) < 0) { return -1; } /* Assign the address to the if */ ifr6.ifr6_addr = *addr6; ifr6.ifr6_ifindex = ifr.ifr_ifindex; ifr6.ifr6_prefixlen = prefix_len; if (ioctl(fd, SIOCSIFADDR, &ifr6) < 0) { return -1; } close (fd); return 0; } int unassign_addr6(struct in6_addr* addr6, int prefix_len, char* if_name) { int fd; struct ifreq ifr; struct in6_ifreq ifr6; /* Get socket first */ fd = socket(AF_INET6, SOCK_DGRAM, 0); if (fd < 0) { return 1; } /* Query the index of the if */ strcpy(ifr.ifr_name, if_name); if (ioctl(fd, SIOGIFINDEX, &ifr) < 0) { return -1; } /* Unassign the address to the if */ ifr6.ifr6_addr = *addr6; ifr6.ifr6_ifindex = ifr.ifr_ifindex; ifr6.ifr6_prefixlen = prefix_len; if (ioctl(fd, SIOCDIFADDR, &ifr6) < 0) { return -1; } close (fd); return 0; } #define MINPACKSIZE 64 int is_addr6_available(struct in6_addr* addr6) { struct sockaddr_in6 addr; struct icmp6_hdr icmph; u_char outpack[MINPACKSIZE]; int icmp_sock; int ret; struct iovec iov; u_char packet[MINPACKSIZE]; struct msghdr msg; if ((icmp_sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) == -1) { return -1; } memset(&icmph, 0, sizeof(icmph)); icmph.icmp6_type = ICMP6_ECHO_REQUEST; icmph.icmp6_code = 0; icmph.icmp6_cksum = 0; icmph.icmp6_seq = htons(0); icmph.icmp6_id = 0; memset(&outpack, 0, sizeof(outpack)); memcpy(&outpack, &icmph, sizeof(icmph)); memset(&addr, 0, sizeof(struct sockaddr_in6)); addr.sin6_family = AF_INET6; addr.sin6_port = htons(IPPROTO_ICMPV6); memcpy(&addr.sin6_addr,addr6,sizeof(struct in6_addr)); /* Only the first 8 bytes of outpack are meaningful... */ ret = sendto(icmp_sock, (char *)outpack, sizeof(outpack), 0, (struct sockaddr *) &addr, sizeof(struct sockaddr_in6)); if (0 >= ret) { return -1; } iov.iov_base = (char *)packet; iov.iov_len = sizeof(packet); msg.msg_name = &addr; msg.msg_namelen = sizeof(addr); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = NULL; msg.msg_controllen = 0; ret = recvmsg(icmp_sock, &msg, MSG_DONTWAIT); if (0 >= ret) { return -1; } return 0; } static void usage(const char* self) { printf("usage: %s {start|stop|status|monitor|validate-all|meta-data}\n",self); return; } /* Following code is copied from send_arp.c, linux-HA project. */ void byebye(int nsig) { (void)nsig; /* Avoid an "error exit" log message if we're killed */ exit(0); } int create_pid_directory(const char *pid_file) { int status; int return_status = -1; struct stat stat_buf; char* dir; dir = strdup(pid_file); if (!dir) { cl_log(LOG_INFO, "Memory allocation failure: %s", strerror(errno)); return -1; } dirname(dir); status = stat(dir, &stat_buf); if (status < 0 && errno != ENOENT && errno != ENOTDIR) { cl_log(LOG_INFO, "Could not stat pid-file directory " "[%s]: %s", dir, strerror(errno)); goto err; } if (!status) { if (S_ISDIR(stat_buf.st_mode)) { goto out; } cl_log(LOG_INFO, "Pid-File directory exists but is " "not a directory [%s]", dir); goto err; } if (mkdir(dir, S_IRUSR|S_IWUSR|S_IXUSR | S_IRGRP|S_IXGRP) < 0) { cl_log(LOG_INFO, "Could not create pid-file directory " "[%s]: %s", dir, strerror(errno)); goto err; } out: return_status = 0; err: free(dir); return return_status; } int write_pid_file(const char *pid_file) { int pidfilefd; char pidbuf[11]; unsigned long pid; ssize_t bytes; if (*pid_file != '/') { cl_log(LOG_INFO, "Invalid pid-file name, must begin with a " "'/' [%s]\n", pid_file); return -1; } if (create_pid_directory(pid_file) < 0) { return -1; } while (1) { pidfilefd = open(pid_file, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR); if (pidfilefd < 0) { if (errno != EEXIST) { /* Old PID file */ cl_log(LOG_INFO, "Could not open pid-file " "[%s]: %s", pid_file, strerror(errno)); return -1; } } else { break; } pidfilefd = open(pid_file, O_RDONLY, S_IRUSR|S_IWUSR); if (pidfilefd < 0) { cl_log(LOG_INFO, "Could not open pid-file " "[%s]: %s", pid_file, strerror(errno)); return -1; } while (1) { bytes = read(pidfilefd, pidbuf, sizeof(pidbuf)-1); if (bytes < 0) { if (errno == EINTR) { continue; } cl_log(LOG_INFO, "Could not read pid-file " "[%s]: %s", pid_file, strerror(errno)); return -1; } pidbuf[bytes] = '\0'; break; } if(unlink(pid_file) < 0) { cl_log(LOG_INFO, "Could not delete pid-file " "[%s]: %s", pid_file, strerror(errno)); return -1; } if (!bytes) { cl_log(LOG_INFO, "Invalid pid in pid-file " "[%s]: %s", pid_file, strerror(errno)); return -1; } close(pidfilefd); pid = strtoul(pidbuf, NULL, 10); if (pid == ULONG_MAX && errno == ERANGE) { cl_log(LOG_INFO, "Invalid pid in pid-file " "[%s]: %s", pid_file, strerror(errno)); return -1; } if (kill(pid, SIGKILL) < 0 && errno != ESRCH) { cl_log(LOG_INFO, "Error killing old process [%lu] " "from pid-file [%s]: %s", pid, pid_file, strerror(errno)); return -1; } cl_log(LOG_INFO, "Killed old send_ua process [%lu]", pid); } if (snprintf(pidbuf, sizeof(pidbuf), "%u" , getpid()) >= (int)sizeof(pidbuf)) { cl_log(LOG_INFO, "Pid too long for buffer [%u]", getpid()); return -1; } while (1) { bytes = write(pidfilefd, pidbuf, strlen(pidbuf)); if (bytes != strlen(pidbuf)) { if (bytes < 0 && errno == EINTR) { continue; } cl_log(LOG_INFO, "Could not write pid-file " "[%s]: %s", pid_file, strerror(errno)); return -1; } break; } close(pidfilefd); return 0; } static int meta_data_addr6(void) { const char* meta_data= "\n" "\n" "\n" " 1.0\n" " \n" " This script manages IPv6 alias IPv6 addresses,It can add an IP6\n" " alias, or remove one.\n" " \n" " Manages IPv6 aliases\n" " \n" " \n" " \n" " The IPv6 address this RA will manage \n" " \n" " IPv6 address\n" " \n" " \n" " \n" " \n" " The netmask for the interface in CIDR format. (ie, 24).\n" " The value of this parameter overwrites the value of _prefix_\n" " of ipv6addr parameter.\n" " \n" " Netmask\n" " \n" " \n" " \n" " \n" " The base network interface on which the IPv6 address will\n" " be brought online.\n" " \n" " Network interface\n" " \n" " \n" " \n" " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" " \n" "\n"; printf("%s\n",meta_data); return OCF_SUCCESS; } diff --git a/heartbeat/nagios b/heartbeat/nagios index 4cb462f6a..3d07b141c 100755 --- a/heartbeat/nagios +++ b/heartbeat/nagios @@ -1,246 +1,246 @@ #!/bin/sh # # License: GNU General Public License (GPL) # (c) 2015 T.J. Yang, O. Albrigtsen # and Linux-HA contributors # # ----------------------------------------------------------------------------- # O C F R E S O U R C E S C R I P T S P E C I F I C A T I O N # ----------------------------------------------------------------------------- # # NAME # nagios : OCF resource agent script for Nagios Server # # Initialization: : ${OCF_FUNCTIONS_DIR=${OCF_ROOT}/lib/heartbeat} . ${OCF_FUNCTIONS_DIR}/ocf-shellfuncs # Defaults OCF_RESKEY_user_default="nagios" OCF_RESKEY_group_default="nagios" OCF_RESKEY_binary_default="/usr/sbin/nagios" OCF_RESKEY_config_default="/etc/nagios/nagios.cfg" OCF_RESKEY_log_default="/var/log/nagios/nagios.log" OCF_RESKEY_retention_default="/var/log/nagios/retention.dat" OCF_RESKEY_command_default="/var/log/nagios/rw/nagios.cmd" OCF_RESKEY_pid_default="/var/run/nagios.pid" : ${OCF_RESKEY_user=${OCF_RESKEY_user_default}} : ${OCF_RESKEY_group=${OCF_RESKEY_group_default}} : ${OCF_RESKEY_binary=${OCF_RESKEY_binary_default}} : ${OCF_RESKEY_config=${OCF_RESKEY_config_default}} : ${OCF_RESKEY_log=${OCF_RESKEY_log_default}} : ${OCF_RESKEY_retention=${OCF_RESKEY_retention_default}} : ${OCF_RESKEY_command=${OCF_RESKEY_command_default}} : ${OCF_RESKEY_pid=${OCF_RESKEY_pid_default}} nagios_usage() { cat < 0.75 OCF Resource script for Nagios 3.x or 4.x. It manages a Nagios instance as a HA resource. Nagios resource agent User running Nagios daemon (for file permissions) Nagios user Group running Nagios daemon (for file permissions) Nagios group Location of the Nagios binary Nagios binary Configuration file Nagios config Location of the Nagios log Nagios log Location of the Nagios retention file Nagios retention file Location of the Nagios external command file Nagios command file Location of the Nagios pid/lock Nagios pid file - + END } nagios_start() { nagios_validate_all rc=$? if [ $rc -ne 0 ]; then return $rc fi # if resource is already running,no need to continue code after this. if nagios_monitor; then ocf_log info "Nagios is already running" return $OCF_SUCCESS fi # Remove ${OCF_RESKEY_pid} if it exists rm -f "${OCF_RESKEY_pid}" ocf_run -q touch ${OCF_RESKEY_log} ${OCF_RESKEY_retention} ${OCF_RESKEY_pid} chown ${OCF_RESKEY_user}:${OCF_RESKEY_group} ${OCF_RESKEY_log} ${OCF_RESKEY_retention} ${OCF_RESKEY_pid} rm -f "${OCF_RESKEY_command}" [ -x /sbin/restorecon ] && /sbin/restorecon ${OCF_RESKEY_pid} ocf_run -q ${OCF_RESKEY_binary} -d ${OCF_RESKEY_config} while ! nagios_monitor; do sleep 1 done if [ $? -eq 0 ]; then ocf_log info "Nagios started" return ${OCF_SUCCESS} fi return $OCF_SUCCESS } nagios_stop() { nagios_monitor if [ $? -ne $OCF_SUCCESS ]; then # Currently not running. Nothing to do. ocf_log info "Resource is already stopped" rm -f ${OCF_RESKEY_pid} return $OCF_SUCCESS fi kill `cat ${OCF_RESKEY_pid}` # Wait for process to stop while nagios_monitor; do sleep 1 done return $OCF_SUCCESS } nagios_monitor(){ ocf_pidfile_status ${OCF_RESKEY_pid} > /dev/null 2>&1 case "$?" in 0) rc=$OCF_SUCCESS ;; 1|2) rc=$OCF_NOT_RUNNING ;; *) rc=$OCF_ERR_GENERIC ;; esac return $rc } nagios_validate_all(){ check_binary "${OCF_RESKEY_binary}" if [ ! -f "${OCF_RESKEY_config}" ]; then ocf_exit_reason "Configuration file ${OCF_RESKEY_config} not found" return ${OCF_ERR_INSTALLED} fi ${OCF_RESKEY_binary} -v ${OCF_RESKEY_config} >/dev/null 2>&1 if [ $? -ne 0 ]; then ocf_exit_reason "Configuration check failed" return ${OCF_ERR_INSTALLED} fi } # **************************** MAIN SCRIPT ************************************ # Make sure meta-data and usage always succeed case $__OCF_ACTION in meta-data) nagios_meta_data exit $OCF_SUCCESS ;; usage|help) nagios_usage exit $OCF_SUCCESS ;; esac # This OCF agent script need to be run as root user. if ! ocf_is_root; then echo "$0 agent script need to be run as root user." ocf_log debug "$0 agent script need to be run as root user." exit $OCF_ERR_GENERIC fi # Translate each action into the appropriate function call case $__OCF_ACTION in start) nagios_start;; stop) nagios_stop;; status|monitor) nagios_monitor;; validate-all) nagios_validate_all;; *) nagios_usage exit $OCF_ERR_UNIMPLEMENTED ;; esac rc=$? exit $rc # End of this script diff --git a/heartbeat/ocf-shellfuncs.in b/heartbeat/ocf-shellfuncs.in index 8e44f09eb..043ab9bf2 100644 --- a/heartbeat/ocf-shellfuncs.in +++ b/heartbeat/ocf-shellfuncs.in @@ -1,1056 +1,1056 @@ # # # Common helper functions for the OCF Resource Agents supplied by # heartbeat. # # Copyright (c) 2004 SUSE LINUX AG, Lars Marowsky-Brée # All Rights Reserved. # # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Build version: $Format:%H$ # TODO: Some of this should probably split out into a generic OCF # library for shell scripts, but for the time being, we'll just use it # ourselves... # # TODO wish-list: # - Generic function for evaluating version numbers # - Generic function(s) to extract stuff from our own meta-data # - Logging function which automatically adds resource identifier etc # prefixes # TODO: Move more common functionality for OCF RAs here. # # This was common throughout all legacy Heartbeat agents unset LC_ALL; export LC_ALL unset LANGUAGE; export LANGUAGE __SCRIPT_NAME=`basename $0` if [ -z "$OCF_ROOT" ]; then : ${OCF_ROOT=@OCF_ROOT_DIR@} fi if [ "$OCF_FUNCTIONS_DIR" = ${OCF_ROOT}/resource.d/heartbeat ]; then # old unset OCF_FUNCTIONS_DIR fi : ${OCF_FUNCTIONS_DIR:=${OCF_ROOT}/lib/heartbeat} . ${OCF_FUNCTIONS_DIR}/ocf-binaries . ${OCF_FUNCTIONS_DIR}/ocf-returncodes . ${OCF_FUNCTIONS_DIR}/ocf-directories . ${OCF_FUNCTIONS_DIR}/ocf-rarun . ${OCF_FUNCTIONS_DIR}/ocf-distro # Define OCF_RESKEY_CRM_meta_interval in case it isn't already set, # to make sure that ocf_is_probe() always works : ${OCF_RESKEY_CRM_meta_interval=0} ocf_is_root() { if [ X`id -u` = X0 ]; then true else false fi } ocf_maybe_random() { if test -c /dev/urandom; then od -An -N4 -tu4 /dev/urandom | tr -d '[:space:]' else awk -v pid=$$ 'BEGIN{srand(pid); print rand()}' | sed 's/^.*[.]//' fi } # Portability comments: # o The following rely on Bourne "sh" pattern-matching, which is usually # that for filename generation (note: not regexp). # o The "*) true ;;" clause is probably unnecessary, but is included # here for completeness. # o The negation in the pattern uses "!". This seems to be common # across many OSes (whereas the alternative "^" fails on some). # o If an OS is encountered where this negation fails, then a possible # alternative would be to replace the function contents by (e.g.): # [ -z "`echo $1 | tr -d '[0-9]'`" ] # ocf_is_decimal() { case "$1" in ""|*[!0-9]*) # empty, or at least one non-decimal false ;; *) true ;; esac } ocf_is_true() { case "$1" in yes|true|1|YES|TRUE|ja|on|ON) true ;; *) false ;; esac } ocf_is_hex() { case "$1" in ""|*[!0-9a-fA-F]*) # empty, or at least one non-hex false ;; *) true ;; esac } ocf_is_octal() { case "$1" in ""|*[!0-7]*) # empty, or at least one non-octal false ;; *) true ;; esac } __ocf_set_defaults() { __OCF_ACTION="$1" # Return to sanity for the agents... unset LANG LC_ALL=C export LC_ALL # TODO: Review whether we really should source this. Or rewrite # to match some emerging helper function syntax...? This imports # things which no OCF RA should be using... # Strip the OCF_RESKEY_ prefix from this particular parameter if [ -z "$OCF_RESKEY_OCF_CHECK_LEVEL" ]; then : ${OCF_CHECK_LEVEL:=0} else : ${OCF_CHECK_LEVEL:=$OCF_RESKEY_OCF_CHECK_LEVEL} fi if [ ! -d "$OCF_ROOT" ]; then ha_log "ERROR: OCF_ROOT points to non-directory $OCF_ROOT." exit $OCF_ERR_GENERIC fi if [ -z "$OCF_RESOURCE_TYPE" ]; then : ${OCF_RESOURCE_TYPE:=$__SCRIPT_NAME} fi if [ "x$__OCF_ACTION" = "xmeta-data" ]; then : ${OCF_RESOURCE_INSTANCE:="RESOURCE_ID"} fi if [ -z "$OCF_RA_VERSION_MAJOR" ]; then : We are being invoked as an init script. : Fill in some things with reasonable values. : ${OCF_RESOURCE_INSTANCE:="default"} return 0 fi if [ -z "$OCF_RESOURCE_INSTANCE" ]; then ha_log "ERROR: Need to tell us our resource instance name." exit $OCF_ERR_ARGS fi } hadate() { date "+${HA_DATEFMT}" } set_logtag() { if [ -z "$HA_LOGTAG" ]; then if [ -n "$OCF_RESOURCE_INSTANCE" ]; then HA_LOGTAG="$__SCRIPT_NAME($OCF_RESOURCE_INSTANCE)[$$]" else HA_LOGTAG="$__SCRIPT_NAME[$$]" fi fi } __ha_log() { local ignore_stderr=false local loglevel [ "x$1" = "x--ignore-stderr" ] && ignore_stderr=true && shift [ none = "$HA_LOGFACILITY" ] && HA_LOGFACILITY="" # if we're connected to a tty, then output to stderr if tty >/dev/null; then if [ "x$HA_debug" = "x0" -a "x$loglevel" = xdebug ] ; then return 0 elif [ "$ignore_stderr" = "true" ]; then # something already printed this error to stderr, so ignore return 0 fi if [ "$HA_LOGTAG" ]; then echo "$HA_LOGTAG: $*" else echo "$*" fi >&2 return 0 fi set_logtag if [ "x${HA_LOGD}" = "xyes" ] ; then ha_logger -t "${HA_LOGTAG}" "$@" if [ "$?" -eq "0" ] ; then return 0 fi fi if [ -n "$HA_LOGFACILITY" ] then : logging through syslog # loglevel is unknown, use 'notice' for now loglevel=notice case "${*}" in *ERROR*) loglevel=err;; *WARN*) loglevel=warning;; *INFO*|info) loglevel=info;; esac logger -t "$HA_LOGTAG" -p ${HA_LOGFACILITY}.${loglevel} "${*}" fi if [ -n "$HA_LOGFILE" ] then : appending to $HA_LOGFILE echo `hadate`" $HA_LOGTAG: ${*}" >> $HA_LOGFILE fi if [ -z "$HA_LOGFACILITY" -a -z "$HA_LOGFILE" ] && ! [ "$ignore_stderr" = "true" ] then : appending to stderr echo `hadate`"${*}" >&2 fi if [ -n "$HA_DEBUGLOG" ] then : appending to $HA_DEBUGLOG if [ "$HA_LOGFILE"x != "$HA_DEBUGLOG"x ]; then echo "$HA_LOGTAG: "`hadate`"${*}" >> $HA_DEBUGLOG fi fi } ha_log() { __ha_log "$@" } ha_debug() { if [ "x${HA_debug}" = "x0" ] ; then return 0 fi if tty >/dev/null; then if [ "$HA_LOGTAG" ]; then echo "$HA_LOGTAG: $*" else echo "$*" fi >&2 return 0 fi set_logtag if [ "x${HA_LOGD}" = "xyes" ] ; then ha_logger -t "${HA_LOGTAG}" -D "ha-debug" "$@" if [ "$?" -eq "0" ] ; then return 0 fi fi [ none = "$HA_LOGFACILITY" ] && HA_LOGFACILITY="" if [ -n "$HA_LOGFACILITY" ] then : logging through syslog logger -t "$HA_LOGTAG" -p "${HA_LOGFACILITY}.debug" "${*}" fi if [ -n "$HA_DEBUGLOG" ] then : appending to $HA_DEBUGLOG echo "$HA_LOGTAG: "`hadate`"${*}" >> $HA_DEBUGLOG fi if [ -z "$HA_LOGFACILITY" -a -z "$HA_DEBUGLOG" ] then : appending to stderr echo "$HA_LOGTAG: `hadate`${*}: ${HA_LOGFACILITY}" >&2 fi } ha_parameter() { local VALUE VALUE=`sed -e 's%[ ][ ]*% %' -e 's%^ %%' -e 's%#.*%%' $HA_CF | grep -i "^$1 " | sed 's%[^ ]* %%'` if [ "X$VALUE" = X ] then case $1 in keepalive) VALUE=2;; deadtime) ka=`ha_parameter keepalive` VALUE=`expr $ka '*' 2 '+' 1`;; esac fi echo $VALUE } ocf_log() { # TODO: Revisit and implement internally. if [ $# -lt 2 ] then ocf_log err "Not enough arguments [$#] to ocf_log." fi __OCF_PRIO="$1" shift __OCF_MSG="$*" case "${__OCF_PRIO}" in crit) __OCF_PRIO="CRIT";; err) __OCF_PRIO="ERROR";; warn) __OCF_PRIO="WARNING";; info) __OCF_PRIO="INFO";; debug)__OCF_PRIO="DEBUG";; *) __OCF_PRIO=`echo ${__OCF_PRIO}| tr '[a-z]' '[A-Z]'`;; esac if [ "${__OCF_PRIO}" = "DEBUG" ]; then ha_debug "${__OCF_PRIO}: $__OCF_MSG" else ha_log "${__OCF_PRIO}: $__OCF_MSG" fi } # # ocf_exit_reason: print exit error string to stderr # Usage: Allows the OCF script to provide a string # describing why the exit code was returned. # Arguments: reason - required, The string that represents why the error # occured. # ocf_exit_reason() { local cookie="$OCF_EXIT_REASON_PREFIX" local fmt local msg # No argument is likely not intentional. # Just one argument implies a printf format string of just "%s". # "Least surprise" in case some interpolated string from variable # expansion or other contains a percent sign. # More than one argument: first argument is going to be the format string. case $# in 0) ocf_log err "Not enough arguments to ocf_log_exit_msg." ;; 1) fmt="%s" ;; *) fmt=$1 shift case $fmt in *%*) : ;; # ok, does look like a format string *) ocf_log warn "Does not look like format string: [$fmt]" ;; esac ;; esac if [ -z "$cookie" ]; then # use a default prefix cookie="ocf-exit-reason:" fi msg=$(printf "${fmt}" "$@") printf >&2 "%s%s\n" "$cookie" "$msg" __ha_log --ignore-stderr "ERROR: $msg" } # # ocf_deprecated: Log a deprecation warning # Usage: ocf_deprecated [param-name] # Arguments: param-name optional, name of a boolean resource # parameter that can be used to suppress # the warning (default # "ignore_deprecation") ocf_deprecated() { local param param=${1:-ignore_deprecation} # don't use ${!param} here, it's a bashism if ! ocf_is_true $(eval echo \$OCF_RESKEY_$param); then ocf_log warn "This resource agent is deprecated" \ "and may be removed in a future release." \ "See the man page for details." \ "To suppress this warning, set the \"${param}\"" \ "resource parameter to true." fi } # # Ocf_run: Run a script, and log its output. # Usage: ocf_run [-q] [-info|-warn|-err] # -q: don't log the output of the command if it succeeds # -info|-warn|-err: log the output of the command at given # severity if it fails (defaults to err) # ocf_run() { local rc local output local verbose=1 local loglevel=err local var for var in 1 2 do case "$1" in "-q") verbose="" shift 1;; "-info"|"-warn"|"-err") loglevel=`echo $1 | sed -e s/-//g` shift 1;; *) ;; esac done output=`"$@" 2>&1` rc=$? [ -n "$output" ] && output="$(echo "$output" | tr -s ' \t\r\n' ' ')" if [ $rc -eq 0 ]; then if [ "$verbose" -a ! -z "$output" ]; then ocf_log info "$output" fi else if [ ! -z "$output" ]; then ocf_log $loglevel "$output" else ocf_log $loglevel "command failed: $*" fi fi return $rc } ocf_pidfile_status() { local pid pidfile=$1 if [ ! -e $pidfile ]; then # Not exists return 2 fi pid=`cat $pidfile` - kill -0 $pid 2>&1 > /dev/null + kill -0 $pid > /dev/null 2>&1 if [ $? = 0 ]; then return 0 fi # Stale return 1 } # mkdir(1) based locking # first the directory is created with the name given as $1 # then a file named "pid" is created within that directory with # the process PID # stale locks are handled carefully, the inode of a directory # needs to match before and after test if the process is running # empty directories are also handled appropriately # we relax (sleep) occasionally to allow for other processes to # finish managing the lock in case they are in the middle of the # business relax() { sleep 0.5; } ocf_get_stale_pid() { local piddir pid dir_inode piddir="$1" [ -z "$piddir" ] && return 2 dir_inode="`ls -di $piddir 2>/dev/null`" [ -z "$dir_inode" ] && return 1 pid=`cat $piddir/pid 2>/dev/null` if [ -z "$pid" ]; then # empty directory? relax if [ "$dir_inode" = "`ls -di $piddir 2>/dev/null`" ]; then echo $dir_inode else return 1 fi elif kill -0 $pid >/dev/null 2>&1; then return 1 elif relax && [ -e "$piddir/pid" ] && [ "$dir_inode" = "`ls -di $piddir 2>/dev/null`" ]; then echo $pid else return 1 fi } # There is a race when the following two functions to manage the # lock file (mk and rm) are invoked in parallel by different # instances. It is up to the caller to reduce probability of that # taking place (see ocf_take_lock() below). ocf_mk_pid() { mkdir $1 2>/dev/null && echo $$ > $1/pid } ocf_rm_pid() { rm -f $1/pid rmdir $1 2>/dev/null } # Testing and subsequently removing a stale lock (containing the # process pid) is inherently difficult to do in such a way as to # prevent a race between creating a pid file and removing it and # its directory. We reduce the probability of that happening by # checking if the stale lock persists over a random period of # time. ocf_take_lock() { local lockdir=$1 local rnd local stale_pid # we don't want it too short, so strip leading zeros rnd=$(ocf_maybe_random | sed 's/^0*//') stale_pid=`ocf_get_stale_pid $lockdir` if [ -n "$stale_pid" ]; then sleep 0.$rnd # remove "stale pid" only if it persists [ "$stale_pid" = "`ocf_get_stale_pid $lockdir`" ] && ocf_rm_pid $lockdir fi while ! ocf_mk_pid $lockdir; do ocf_log info "Sleeping until $lockdir is released..." sleep 0.$rnd done } ocf_release_lock_on_exit() { trap "ocf_rm_pid $1" EXIT } # returns true if the CRM is currently running a probe. A probe is # defined as a monitor operation with a monitoring interval of zero. ocf_is_probe() { [ "$__OCF_ACTION" = "monitor" -a "$OCF_RESKEY_CRM_meta_interval" = 0 ] } # returns true if the resource is configured as a clone. This is # defined as a resource where the clone-max meta attribute is present, # and set to greater than zero. ocf_is_clone() { [ ! -z "${OCF_RESKEY_CRM_meta_clone_max}" ] && [ "${OCF_RESKEY_CRM_meta_clone_max}" -gt 0 ] } # returns true if the resource is configured as a multistate # (master/slave) resource. This is defined as a resource where the # master-max meta attribute is present, and set to greater than zero. ocf_is_ms() { [ ! -z "${OCF_RESKEY_CRM_meta_master_max}" ] && [ "${OCF_RESKEY_CRM_meta_master_max}" -gt 0 ] } # version check functions # allow . and - to delimit version numbers # max version number is 999 # letters and such are effectively ignored # ocf_is_ver() { echo $1 | grep '^[0-9][0-9.-]*[0-9]$' >/dev/null 2>&1 } ocf_ver2num() { echo $1 | awk -F'[.-]' ' {for(i=1; i<=NF; i++) s=s*1000+$i; print s} ' } ocf_ver_level(){ echo $1 | awk -F'[.-]' '{print NF}' } ocf_ver_complete_level(){ local ver="$1" local level="$2" local i=0 while [ $i -lt $level ]; do ver=${ver}.0 i=`expr $i + 1` done echo $ver } # usage: ocf_version_cmp VER1 VER2 # version strings can contain digits, dots, and dashes # must start and end with a digit # returns: # 0: VER1 smaller (older) than VER2 # 1: versions equal # 2: VER1 greater (newer) than VER2 # 3: bad format ocf_version_cmp() { ocf_is_ver "$1" || return 3 ocf_is_ver "$2" || return 3 local v1=$1 local v2=$2 local v1_level=`ocf_ver_level $v1` local v2_level=`ocf_ver_level $v2` local level_diff if [ $v1_level -lt $v2_level ]; then level_diff=`expr $v2_level - $v1_level` v1=`ocf_ver_complete_level $v1 $level_diff` elif [ $v1_level -gt $v2_level ]; then level_diff=`expr $v1_level - $v2_level` v2=`ocf_ver_complete_level $v2 $level_diff` fi v1=`ocf_ver2num $v1` v2=`ocf_ver2num $v2` if [ $v1 -eq $v2 ]; then return 1 elif [ $v1 -lt $v2 ]; then return 0 else return 2 # -1 would look funny in shell ;-) fi } ocf_local_nodename() { # use crm_node -n for pacemaker > 1.1.8 which pacemakerd > /dev/null 2>&1 if [ $? -eq 0 ]; then local version=$(pacemakerd -$ | grep "Pacemaker .*" | awk '{ print $2 }') version=$(echo $version | awk -F- '{ print $1 }') ocf_version_cmp "$version" "1.1.8" if [ $? -eq 2 ]; then which crm_node > /dev/null 2>&1 if [ $? -eq 0 ]; then crm_node -n return fi fi fi # otherwise use uname -n uname -n } # usage: dirname DIR dirname() { local a local b [ $# = 1 ] || return 1 a="$1" while [ 1 ]; do b="${a%/}" [ "$a" = "$b" ] && break a="$b" done b=${a%/*} [ -z "$b" -o "$a" = "$b" ] && b="." echo "$b" return 0 } # usage: systemd_is_running # returns: # 0 PID 1 is systemd # 1 otherwise systemd_is_running() { [ "$(cat /proc/1/comm 2>/dev/null)" = "systemd" ] } # usage: systemd_drop_in systemd_drop_in() { local conf_file if [ $# -ne 3 ]; then ocf_log err "Incorrect number of arguments [$#] for systemd_drop_in." fi systemdrundir="/run/systemd/system/resource-agents-deps.target.d" mkdir -p "$systemdrundir" conf_file="$systemdrundir/$1.conf" cat >"$conf_file" </dev/null # try to leave early, and yet leave processes time to exit sleep 0.2 for i in `seq $wait_time`; do kill -s 0 $pids 2>/dev/null || return 0 sleep 1 done done return 1 } # # create a given status directory # if the directory path doesn't start with $HA_VARRUN, then # we return with error (most of the calls would be with the user # supplied configuration, hence we need to do necessary # protection) # used mostly for PID files # # usage: ocf_mkstatedir owner permissions path # # owner: user.group # permissions: permissions # path: directory path # # example: # ocf_mkstatedir named 755 `dirname $pidfile` # ocf_mkstatedir() { local owner local perms local path owner=$1 perms=$2 path=$3 test -d $path && return 0 [ $(id -u) = 0 ] || return 1 case $path in ${HA_VARRUN%/}/*) : this path is ok ;; *) ocf_log err "cannot create $path (does not start with $HA_VARRUN)" return 1 ;; esac mkdir -p $path && chown $owner $path && chmod $perms $path } # # create a unique status directory in $HA_VARRUN # used mostly for PID files # the directory is by default set to # $HA_VARRUN/$OCF_RESOURCE_INSTANCE # the directory name is printed to stdout # # usage: ocf_unique_rundir owner permissions name # # owner: user.group (default: "root") # permissions: permissions (default: "755") # name: some unique string (default: "$OCF_RESOURCE_INSTANCE") # # to use the default either don't set the parameter or set it to # empty string ("") # example: # # STATEDIR=`ocf_unique_rundir named "" myownstatedir` # ocf_unique_rundir() { local path local owner local perms local name owner=${1:-"root"} perms=${2:-"755"} name=${3:-"$OCF_RESOURCE_INSTANCE"} path=$HA_VARRUN/$name if [ ! -d $path ]; then [ $(id -u) = 0 ] || return 1 mkdir -p $path && chown $owner $path && chmod $perms $path || return 1 fi echo $path } # # RA tracing may be turned on by setting OCF_TRACE_RA # the trace output will be saved to OCF_TRACE_FILE, if set, or # by default to # $HA_VARLIB/trace_ra//.. # e.g. $HA_VARLIB/trace_ra/oracle/db.start.2012-11-27.08:37:08 # # OCF_TRACE_FILE: # - FD (small integer [3-9]) in that case it is up to the callers # to capture output; the FD _must_ be open for writing # - absolute path # # NB: FD 9 may be used for tracing with bash >= v4 in case # OCF_TRACE_FILE is set to a path. # ocf_is_bash4() { echo "$SHELL" | grep bash > /dev/null && [ ${BASH_VERSINFO[0]} = "4" ] } ocf_trace_redirect_to_file() { local dest=$1 if ocf_is_bash4; then exec 9>$dest BASH_XTRACEFD=9 else exec 2>$dest fi } ocf_trace_redirect_to_fd() { local fd=$1 if ocf_is_bash4; then BASH_XTRACEFD=$fd else exec 2>&$fd fi } __ocf_test_trc_dest() { local dest=$1 if ! touch $dest; then ocf_log warn "$dest not writable, trace not going to happen" __OCF_TRC_DEST="" __OCF_TRC_MANAGE="" return 1 fi return 0 } ocf_default_trace_dest() { tty >/dev/null && return if [ -n "$OCF_RESOURCE_TYPE" -a \ -n "$OCF_RESOURCE_INSTANCE" -a -n "$__OCF_ACTION" ]; then local ts=`date +%F.%T` __OCF_TRC_DEST=$HA_VARLIB/trace_ra/${OCF_RESOURCE_TYPE}/${OCF_RESOURCE_INSTANCE}.${__OCF_ACTION}.$ts __OCF_TRC_MANAGE="1" fi } ocf_start_trace() { export __OCF_TRC_DEST="" __OCF_TRC_MANAGE="" case "$OCF_TRACE_FILE" in [3-9]) ocf_trace_redirect_to_fd "$OCF_TRACE_FILE" ;; /*/*) __OCF_TRC_DEST=$OCF_TRACE_FILE ;; "") ocf_default_trace_dest ;; *) ocf_log warn "OCF_TRACE_FILE must be set to either FD (open for writing) or absolute file path" ocf_default_trace_dest ;; esac if [ "$__OCF_TRC_DEST" ]; then mkdir -p `dirname $__OCF_TRC_DEST` __ocf_test_trc_dest $__OCF_TRC_DEST || return ocf_trace_redirect_to_file "$__OCF_TRC_DEST" fi if [ -n "$BASH_VERSION" ]; then PS4='+ `date +"%T"`: ${FUNCNAME[0]:+${FUNCNAME[0]}:}${LINENO}: ' fi set -x env=$( echo; printenv | sort ) } ocf_stop_trace() { set +x } # Helper functions to map from nodename/bundle-name and physical hostname # list_index_for_word "node0 node1 node2 node3 node4 node5" node4 --> 5 # list_word_at_index "NA host1 host2 host3 host4 host5" 3 --> host2 # list_index_for_word "node1 node2 node3 node4 node5" node7 --> "" # list_word_at_index "host1 host2 host3 host4 host5" 8 --> "" # attribute_target node1 --> host1 list_index_for_word() { echo $1 | tr ' ' '\n' | awk -v x="$2" '$0~x {print NR}' } list_word_at_index() { echo $1 | tr ' ' '\n' | awk -v n="$2" 'n == NR' } ocf_attribute_target() { if [ x$1 = x ]; then if [ x$OCF_RESKEY_CRM_meta_container_attribute_target = xhost -a x$OCF_RESKEY_CRM_meta_physical_host != x ]; then echo $OCF_RESKEY_CRM_meta_physical_host else if [ x$OCF_RESKEY_CRM_meta_on_node != x ]; then echo $OCF_RESKEY_CRM_meta_on_node else ocf_local_nodename fi fi return elif [ x"$OCF_RESKEY_CRM_meta_notify_all_uname" != x ]; then index=$(list_index_for_word "$OCF_RESKEY_CRM_meta_notify_all_uname" $1) mapping="" if [ x$index != x ]; then mapping=$(list_word_at_index "$OCF_RESKEY_CRM_meta_notify_all_hosts" $index) fi if [ x$mapping != x -a x$mapping != xNA ]; then echo $mapping return fi fi echo $1 } __ocf_set_defaults "$@" : ${OCF_TRACE_RA:=$OCF_RESKEY_trace_ra} ocf_is_true "$OCF_TRACE_RA" && ocf_start_trace # pacemaker sets HA_use_logd, some others use HA_LOGD :/ if ocf_is_true "$HA_use_logd"; then : ${HA_LOGD:=yes} fi diff --git a/heartbeat/sybaseASE.in b/heartbeat/sybaseASE.in index b4809ea23..9ddd429be 100755 --- a/heartbeat/sybaseASE.in +++ b/heartbeat/sybaseASE.in @@ -1,890 +1,890 @@ #!@BASH_SHELL@ # # Sybase Availability Agent for Red Hat Cluster v15.0.2 # Copyright (C) - 2007 # Sybase, Inc. All rights reserved. # # Sybase Availability Agent for Red Hat Cluster v15.0.2 is licensed # under the GNU General Public License Version 2. # # Author(s): # Jian-ping Hui # # Description: Service script for starting/stopping/monitoring \ # Sybase Adaptive Server on: \ # Red Hat Enterprise Linux 7 ES \ # Red Hat Enterprise Linux 7 AS # # NOTES: # # (1) Before running this script, we assume that user has installed # Sybase ASE 15.0.2 or higher version on the machine. Please # customize your configuration in /etc/cluster/cluster.conf according # to your actual environment. We assume the following files exist before # you start the service: # /$sybase_home/SYBASE.sh # /$sybase_home/$sybase_ase/install/RUN_$server_name # # (2) You can customize the interval value in the meta-data section if needed: # # # # # # # # # # # # # # The timeout value is not supported by Redhat in RHCS5.0. # ####################################################################### # Initialization: if [ -f /etc/init.d/functions ]; then . /etc/init.d/functions fi : ${OCF_FUNCTIONS_DIR=${OCF_ROOT}/lib/heartbeat} . ${OCF_FUNCTIONS_DIR}/ocf-shellfuncs ####################################################################### # Default timeouts when we aren't using the rgmanager wrapper if ! ocf_is_true "$OCF_RESKEY_is_rgmanager_wrapper"; then if [ -z "$OCF_RESKEY_CRM_meta_timeout" ]; then case $1 in start|stop) OCF_RESKEY_CRM_meta_timeout=300000 ;; *) OCF_RESKEY_CRM_meta_timeout=100000 ;; esac fi default_timeout=$(((${OCF_RESKEY_CRM_meta_timeout}/1000) - 5)) default_force_stop_timeout=$(((${OCF_RESKEY_CRM_meta_timeout}/1000) - 5)) : ${OCF_RESKEY_shutdown_timeout=${default_force_stop_timeout}} : ${OCF_RESKEY_deep_probe_timeout=${default_timeout}} : ${OCF_RESKEY_start_timeout=${default_timeout}} fi sybase_user_default="sybase" sybase_home_default="detect" ase_default="detect" ocs_default="detect" : ${OCF_RESKEY_sybase_user=${sybase_user_default}} : ${OCF_RESKEY_sybase_ase=${ase_default}} : ${OCF_RESKEY_sybase_ocs=${ocs_default}} : ${OCF_RESKEY_sybase_home=${sybase_home_default}} if [ "$__OCF_ACTION" != "meta-data" ]; then if [ "$OCF_RESKEY_sybase_home" = "detect" ]; then if [ -d "/opt/sap" ]; then OCF_RESKEY_sybase_home="/opt/sap" elif [ -d "/opt/sybase" ]; then OCF_RESKEY_sybase_home="/opt/sybase" else ocf_log err "sybaseASE: Unable to detect 'sybase_home'." exit $OCF_ERR_ARGS fi fi sybase_env="$OCF_RESKEY_sybase_home/SYBASE.env" if [ "$OCF_RESKEY_sybase_ase" = "detect" ]; then if [ -f "$sybase_env" ]; then OCF_RESKEY_sybase_ase=$(grep "SYBASE_ASE" "$sybase_env" | cut -d= -f2) else ocf_log err "sybaseASE: Unable to detect 'sybase_ase'." exit $OCF_ERR_ARGS fi fi if [ "$OCF_RESKEY_sybase_ocs" = "detect" ]; then if [ -f "$sybase_env" ]; then OCF_RESKEY_sybase_ocs=$(grep "SYBASE_OCS" "$sybase_env" | cut -d= -f2) else ocf_log err "sybaseASE: Unable to detect 'sybase_ocs'." exit $OCF_ERR_ARGS fi fi fi interfaces_file_default="${OCF_RESKEY_sybase_home}/interfaces" : ${OCF_RESKEY_interfaces_file=${interfaces_file_default}} export LD_POINTER_GUARD=0 ####################################################################################### # Declare some variables we will use in the script. # ####################################################################################### declare login_string="" declare RUNSERVER_SCRIPT=$OCF_RESKEY_sybase_home/$OCF_RESKEY_sybase_ase/install/RUN_$OCF_RESKEY_server_name declare CONSOLE_LOG=$OCF_RESKEY_sybase_home/$OCF_RESKEY_sybase_ase/install/$OCF_RESKEY_server_name.log ################################################################################################## # This function will be called by Pacemaker to get the meta data of resource agent "sybaseASE". # ################################################################################################## meta_data() { cat < 1.0 Sybase ASE Failover Instance Sybase ASE Failover Instance The home directory of sybase products SYBASE home directory The directory name under sybase_home where ASE products are installed SYBASE_ASE directory name The directory name under sybase_home where OCS products are installed, i.e. ASE-15_0 SYBASE_OCS directory name The ASE server name which is configured for the HA service ASE server name The full path of interfaces file which is used to start/access the ASE server Interfaces file The user who can run ASE server Sybase user The database user required to login to isql. Sybase user The database user's password required to login to isql. Sybase user - - + + EOT } ase_engine0_process() { sed -n -e '/engine 0/s/^.*os pid \([0-9]*\).*online$/\1/p' $CONSOLE_LOG } ase_engine0_thread() { sed -n -e 's/.*Thread.*LWP \([0-9]*\).*online as engine 0.*/\1/p' $CONSOLE_LOG } ase_engine_threadpool_pid() { sed -n -e 's/.*Adaptive Server is running as process id \([0-9]*\).*/\1/p' $CONSOLE_LOG } ase_all_pids() { local PIDS=$(sed -n -e '/engine /s/^.*os pid \([0-9]*\).*online$/\1/p' $CONSOLE_LOG) if [ -z "$PIDS" ]; then #engines are running in a threadpool PIDS=$(ase_engine_threadpool_pid) fi echo $PIDS } ################################################################################################## # Function Name: verify_all # # Parameter: None # # Return value: # # 0 SUCCESS # # OCF_ERR_ARGS Parameters are invalid # # Description: Do some validation on the user-configurable stuff at the beginning of the script. # ################################################################################################## verify_all() { ocf_log debug "sybaseASE: Start 'verify_all'" check_binary "ksh" # Check if the parameter 'sybase_home' is set. if [[ -z "$OCF_RESKEY_sybase_home" ]] then ocf_log err "sybaseASE: The parameter 'sybase_home' is not set." return $OCF_ERR_ARGS fi # Check if the parameter 'sybase_home' is a valid path. if [[ ! -d $OCF_RESKEY_sybase_home ]] then ocf_log err "sybaseASE: The sybase_home '$OCF_RESKEY_sybase_home' doesn't exist." return $OCF_ERR_ARGS fi # Check if the script file SYBASE.sh exists if [[ ! -f $OCF_RESKEY_sybase_home/SYBASE.sh ]] then ocf_log err "sybaseASE: The file $OCF_RESKEY_sybase_home/SYBASE.sh is required to run this script. Failed to run the script." return $OCF_ERR_ARGS fi # Check if the parameter 'sybase_ase' is set. if [[ -z "$OCF_RESKEY_sybase_ase" ]] then ocf_log err "sybaseASE: The parameter 'sybase_ase' is not set." return $OCF_ERR_ARGS fi # Check if the directory /$OCF_RESKEY_sybase_home/$OCF_RESKEY_sybase_ase exists. if [[ ! -d $OCF_RESKEY_sybase_home/$OCF_RESKEY_sybase_ase ]] then ocf_log err "sybaseASE: The directory '$OCF_RESKEY_sybase_home/$OCF_RESKEY_sybase_ase' doesn't exist." return $OCF_ERR_ARGS fi # Check if the parameter 'sybase_ocs' is set. if [[ -z "$OCF_RESKEY_sybase_ocs" ]] then ocf_log err "sybaseASE: The parameter 'sybase_ocs' is not set." return $OCF_ERR_ARGS fi # Check if the directory /$OCF_RESKEY_sybase_home/$OCF_RESKEY_sybase_ocs exists. if [[ ! -d $OCF_RESKEY_sybase_home/$OCF_RESKEY_sybase_ocs ]] then ocf_log err "sybaseASE: The directory '$OCF_RESKEY_sybase_home/$OCF_RESKEY_sybase_ocs' doesn't exist." return $OCF_ERR_ARGS fi # Check if the parameter 'server_name' is set. if [[ -z "$OCF_RESKEY_server_name" ]] then ocf_log err "sybaseASE: The parameter 'server_name' is not set." return $OCF_ERR_ARGS fi # Check if the Run_server file exists. if [[ ! -f $RUNSERVER_SCRIPT ]] then ocf_log err "sybaseASE: The file $RUNSERVER_SCRIPT doesn't exist. The sybase directory may be incorrect." return $OCF_ERR_ARGS fi # Check if the user 'sybase_user' exist id -u $OCF_RESKEY_sybase_user if [[ $? != 0 ]] then ocf_log err "sybaseASE: The user '$OCF_RESKEY_sybase_user' doesn't exist in the system." return $OCF_ERR_ARGS fi # Check if the parameter 'interfaces_file' is set if [[ -z "$OCF_RESKEY_interfaces_file" ]] then ocf_log err "sybaseASE: The parameter 'interfaces_file' is not set." return $OCF_ERR_ARGS fi # Check if the file 'interfaces_file' exists if [[ ! -f $OCF_RESKEY_interfaces_file ]] then ocf_log err "sybaseASE: The interfaces file '$OCF_RESKEY_interfaces_file' doesn't exist." return $OCF_ERR_ARGS fi # Check if the parameter 'db_user' is set if [[ -z "$OCF_RESKEY_db_user" ]] then ocf_log err "sybaseASE: The parameter 'db_user' is not set." return $OCF_ERR_ARGS fi # Check if the parameter 'shutdown_timeout' is a valid value if [[ $OCF_RESKEY_shutdown_timeout -eq 0 ]] then ocf_log err "sybaseASE: The parameter 'shutdown_timeout' is not set. Its value cannot be zero." return $OCF_ERR_ARGS fi # Check if the parameter 'start_timeout' is a valid value if [[ $OCF_RESKEY_start_timeout -eq 0 ]] then ocf_log err "sybaseASE: The parameter 'start_timeout' is not set. Its value cannot be zero." return $OCF_ERR_ARGS fi # Check if the parameter 'deep_probe_timeout' is a valid value if [[ $OCF_RESKEY_deep_probe_timeout -eq 0 ]] then ocf_log err "sybaseASE: The parameter 'deep_probe_timeout' is not set. Its value cannot be zero." return $OCF_ERR_ARGS fi ocf_log debug "sybaseASE: End 'verify_all' successfully." return $OCF_SUCCESS } set_login_string() { tmpstring="" login_sting="" login_string="-U$OCF_RESKEY_db_user -P$OCF_RESKEY_db_passwd" return 0 } ############################################################################################## # Function name: ase_start # # Parameter: None # # Return value: # # 0 SUCCESS # # 1 FAIL # # Description: This function is used to start the ASE server in primary or secondary server. # ############################################################################################## ase_start() { ocf_log debug "sybaseASE: Start 'ase_start'" # Check if the server is running. If yes, return SUCCESS directly. Otherwise, continue the start work. ase_is_running if [[ $? = 0 ]] then # The server is running. ocf_log info "sybaseASE: Server is running. Start is success." return $OCF_SUCCESS fi # The server is not running. We need to start it. # If the log file existed, delete it. if [[ -f $CONSOLE_LOG ]] then rm -f $CONSOLE_LOG fi ocf_log debug "sybaseASE: Starting '$OCF_RESKEY_server_name'..." # Run runserver script to start the server. Since this script will be run by root and ASE server # needs to be run by another user, we need to change the user to sybase_user first. Then, run # the script to start the server. su $OCF_RESKEY_sybase_user -c ksh << EOF # set required SYBASE environment by running SYBASE.sh. . $OCF_RESKEY_sybase_home/SYBASE.sh # Run the RUNSERVER_SCRIPT to start the server. . $RUNSERVER_SCRIPT > $CONSOLE_LOG 2>&1 & EOF # Monitor every 1 seconds if the server has # recovered, until RECOVERY_TIMEOUT. t=0 while [[ $t -le $OCF_RESKEY_start_timeout ]] do grep -s "Recovery complete." $CONSOLE_LOG > /dev/null 2>&1 if [[ $? != 0 ]] then # The server has not completed the recovery. We need to continue to monitor the recovery # process. t=`expr $t + 1` else # The server has completed the recovery. ocf_log info "sybaseASE: ASE server '$OCF_RESKEY_server_name' started successfully." break fi sleep 1 done # If $t is larger than start_timeout, it means the ASE server cannot start in given time. Otherwise, it # means the ASE server has started successfully. if [[ $t -gt $OCF_RESKEY_start_timeout ]] then # The server cannot start in specified time. We think the start is failed. ocf_log err "sybaseASE: Failed to start ASE server '$OCF_RESKEY_server_name'. Please check the server error log $CONSOLE_LOG for possible problems." return $OCF_ERR_GENERIC fi ase_is_running if [ $? -ne 0 ]; then ocf_log err "sybaseASE: ase_start could not detect database initialized properly." return $OCF_ERR_GENERIC fi ocf_log debug "sybaseASE: End 'ase_start' successfully." return $OCF_SUCCESS } ############################################################################################# # Function name: ase_stop # # Parameter: None # # Return value: # # 0 SUCCESS # # 1 FAIL # # Description: This function is used to stop the ASE server in primary or secondary server. # ############################################################################################# ase_stop() { ocf_log debug "sybaseASE: Start 'ase_stop'" # Check if the ASE server is still running. ase_is_running if [[ $? != 0 ]] then # The ASE server is not running. We need not to shutdown it. ocf_log info "sybaseASE: The dataserver $OCF_RESKEY_server_name is not running." return $OCF_SUCCESS fi set_login_string # Just in case things are hung, start a process that will wait for the # timeout period, then kill any remaining porcesses. We'll need to # monitor this process (set -m), so we can terminate it later if it is # not needed. set -m kill_ase $OCF_RESKEY_shutdown_timeout & KILL_PID=$! # If successful, we will also terminate watchdog process # Run "shutdown with nowait" from isql command line to shutdown the server su $OCF_RESKEY_sybase_user -c ksh << EOF # set required SYBASE environment by running SYBASE.sh. . $OCF_RESKEY_sybase_home/SYBASE.sh # Run "shutdown with nowait" to shutdown the server immediately. (echo "use master" ; echo go ; echo "shutdown with nowait"; echo go) | \ \$SYBASE/\$SYBASE_OCS/bin/isql $login_string -S$OCF_RESKEY_server_name -I$OCF_RESKEY_interfaces_file & EOF sleep 5 # Check if the server has been shut down successfully t=0 while [[ $t -lt $OCF_RESKEY_shutdown_timeout ]] do # Search "ueshutdown: exiting" in the server log. If found, it means the server has been shut down. # Otherwise, we need to wait. tail $CONSOLE_LOG | grep "ueshutdown: exiting" > /dev/null 2>&1 if [[ $? != 0 ]] then # The shutdown is still in processing. Wait... sleep 2 t=`expr $t+2` else # The shutdown is success. ocf_log info "sybaseASE: ASE server '$OCF_RESKEY_server_name' shutdown with isql successfully." break fi done # If $t is larger than shutdown_timeout, it means the ASE server cannot be shut down in given time. We need # to wait for the background kill process to kill the OS processes directly. if [[ $t -ge $OCF_RESKEY_shutdown_timeout ]] then ocf_log err "sybaseASE: Shutdown of '$OCF_RESKEY_server_name' from isql failed. Server is either down or unreachable." fi # Here, the ASE server has been shut down by isql command or killed by background process. We need to do # further check to make sure all processes have gone away before saying shutdown is complete. This stops the # other node from starting up the package before it has been stopped and the file system has been unmounted. # Get all processes ids from log file declare -a ENGINE_ALL=$(ase_all_pids) typeset -i num_procs=${#ENGINE_ALL[@]} # We cannot find any process id from log file. It may be because the log file is corrupted or be deleted. # In this case, we determine the shutdown is failed. if [[ ${#ENGINE_ALL[@]} -lt 1 ]] then ocf_log err "sybaseASE: Unable to find the process id from $CONSOLE_LOG." ocf_log err "sybaseASE: Stop ASE server failed." return $OCF_ERR_GENERIC fi # Monitor the system processes to make sure all ASE related processes have gone away. while true do # To every engine process, search it in system processes list. If it is not in the # list, it means this process has gone away. Otherwise, we need to wait for it is # killed by background process. for i in "${ENGINE_ALL[@]}" do ps -fu $OCF_RESKEY_sybase_user | awk '{print $2}' | grep $i | grep -v grep if [[ $? != 0 ]] then ocf_log debug "sybaseASE: $i process has stopped." c=0 while (( c < $num_procs )) do if [[ ${ENGINE_ALL[$c]} = $i ]] then unset ENGINE_ALL[$c] c=$num_procs fi (( c = c + 1 )) done fi done # To here, all processes should have gone away. if [[ ${#ENGINE_ALL[@]} -lt 1 ]] then # # Looks like shutdown was successful, so kill the # script to kill any hung processes, which we started earlier. # Check to see if the script is still running. If jobs # returns that the script is done, then we don't need to kill # it. # job=$(jobs | grep -v Done) if [[ ${job} != "" ]] then ocf_log debug "sybaseASE: Killing the kill_ase script." kill -15 $KILL_PID > /dev/null 2>&1 fi break fi sleep 5 done ocf_log debug "sybaseASE: End 'ase_stop'." return $OCF_SUCCESS } #################################################################################### # Function name: ase_is_running # # Parameter: None # # Return value: # # 0 ASE server is running # # 1 ASE server is not running or there are errors # # Description: This function is used to check if the ASE server is still running . # #################################################################################### ase_is_running() { local PID local THREAD # If the error log doesn't exist, we can say there is no ASE is running. if [[ ! -f $CONSOLE_LOG ]] then ocf_log debug "could not find console log $CONSOLE_LOG" return $OCF_NOT_RUNNING fi # The error log file exists. Check if the engine 0 is alive. PID=$(ase_engine0_process) if [ -n "$PID" ]; then kill -s 0 $PID > /dev/null 2>&1 if [ $? -eq 0 ]; then # The engine 0 is running. ocf_log debug "Found engine 0 pid $PID to be running" return $OCF_SUCCESS fi # The engine 0 is not running. return $OCF_NOT_RUNNING fi PID=$(ase_engine_threadpool_pid) THREAD=$(ase_engine0_thread) if [ -n "$PID" ] && [ -n "$THREAD" ]; then ps -AL | grep -q "${PID}[[:space:]]*${THREAD} " if [ $? -eq 0 ]; then # engine 0 thread is running ocf_log debug "Found engine 0 thread $THREAD in pid $PID to be running" return $OCF_SUCCESS fi # The engine 0 is not running. return $OCF_NOT_RUNNING fi return $OCF_ERR_GENERIC } #################################################################################### # Function name: kill_ase # # Parameter: # # DELAY The seconds to wait before killing the ASE processes. 0 means # # kill the ASE processes immediately. # # Return value: None # # 1 ASE server is not running or there are errors # # Description: This function is used to check if the ASE server is still running . # #################################################################################### kill_ase() { ocf_log debug "sybaseASE: Start 'kill_ase'." DELAY=$1 # Wait for sometime before sending a kill signal. t=0 while [[ $t -lt $DELAY ]] do sleep 1 t=`expr $t+1` done # Get the process ids from log file declare -a ENGINE_ALL=$(ase_all_pids) # If there is no process id found in the log file, we need not to continue. if [[ ${#ENGINE_ALL[@]} -lt 1 ]] then ocf_log err "sybaseASE: Unable to find the process id from $CONSOLE_LOG." return $OCF_ERR_GENERIC fi # Kill the datasever process(es) for pid in "${ENGINE_ALL[@]}" do kill -9 $pid > /dev/null 2>&1 if [[ $? != 0 ]] then ocf_log info "sybaseASE: kill_ase function did NOT find process $pid running." else ocf_log info "sybaseASE: kill_ase function did find process $pid running. Sent SIGTERM." fi done ocf_log debug "sybaseASE: End 'kill_ase'." return $OCF_SUCCESS } ##################################################################################### # Function name: ase_status # # Parameter: # # 0 Level 0 probe. In this level, we just check if engine 0 is alive # # 10 Level 10 probe. In this level, we need to probe if the ASE server # # still has response. # # Return value: # # 0 The server is still alive # # 1 The server is down # # Description: This function is used to check if the ASE server is still running. # ##################################################################################### ase_status() { local rc ocf_log debug "sybaseASE: Start 'ase_status'." # Step 1: Check if the engine 0 is alive ase_is_running rc=$? if [ $rc -ne 0 ]; then # ASE is down. Return fail to Pacemaker to trigger the failover process. ocf_log err "sybaseASE: ASE server is down." return $rc fi # ASE process is still alive. # Step2: If this is level 10 probe, We need to check if the ASE server still has response. if [[ $1 -gt 0 ]] then ocf_log debug "sybaseASE: Need to run deep probe." # Run deep probe deep_probe if [[ $? = 1 ]] then # Deep probe failed. This means the server has been down. ocf_log err "sybaseASE: Deep probe found the ASE server is down." return $OCF_ERR_GENERIC fi fi ocf_log debug "sybaseASE: End 'ase_status'." return $OCF_SUCCESS } #################################################################################### # Function name: deep_probe # # Parameter: None # # Return value: # # 0 ASE server is alive # # 1 ASE server is down # # Description: This function is used to run deep probe to make sure the ASE server # # still has response. # #################################################################################### deep_probe() { declare -i rv ocf_log debug "sybaseASE: Start 'deep_probe'." # Declare two temporary files which will be used in this probe. tmpfile1="$(mktemp /tmp/sybaseASE.1.XXXXXX)" tmpfile2="$(mktemp /tmp/sybaseASE.2.XXXXXX)" set_login_string rm -f $tmpfile1 rm -f $tmpfile2 # The login file is correct. We have gotten the login account and password from it. # Run isql command in background. su $OCF_RESKEY_sybase_user -c ksh << EOF # set required SYBASE environment by running SYBASE.sh. . $OCF_RESKEY_sybase_home/SYBASE.sh # Run a very simple SQL statement to make sure the server is still ok. The output will be put to # tmpfile1. (echo "select 1"; echo "go") | \$SYBASE/\$SYBASE_OCS/bin/isql $login_string -S$OCF_RESKEY_server_name -I$OCF_RESKEY_interfaces_file -t $OCF_RESKEY_deep_probe_timeout -e -o$tmpfile1 & # Record the isql command process id to temporary file. If the isql is hung, we need this process id # to kill the hung process. echo \$! > $tmpfile2 EOF declare -i t=0 # Monitor the output file tmpfile1. while [[ $t -lt $OCF_RESKEY_deep_probe_timeout ]] do # If the SQL statement is executed successfully, we will get the following output: # 1> select 1 # # ----------- # 1 # # (1 row affected) # So, we determine if the execution is success by searching the keyword "(1 row affected)". grep "(1 row affected)" $tmpfile1 if [[ $? = 0 ]] then ocf_log debug "sybaseASE: Deep probe sucess." break else sleep 1 t=`expr $t+1` fi done # If $t is larger than deep_probe_timeout, it means the isql command line cannot finish in given time. # This means the deep probe failed. We need to kill the isql process manually. if [[ $t -ge $OCF_RESKEY_deep_probe_timeout ]] then ocf_log err "sybaseASE: Deep probe fail. The dataserver has no response." # Read the process id of isql process from tmpfile2 pid=`cat $tmpfile2 | awk '{print $1}'` rm -f $tmpfile1 rm -f $tmpfile2 # Kill the isql process directly. kill -9 $pid return 1 fi rm -f $tmpfile1 rm -f $tmpfile2 ocf_log debug "sybaseASE: End 'deep_probe'." return 0 } ############################# # Do some real work here... # ############################# case $__OCF_ACTION in start) verify_all || exit $OCF_ERR_GENERIC ase_start exit $? ;; stop) verify_all || exit $OCF_ERR_GENERIC ase_stop exit $? ;; status | monitor) verify_all || exit $OCF_ERR_GENERIC ase_status $OCF_CHECK_LEVEL exit $? ;; meta-data) meta_data exit $OCF_SUCCESS ;; validate-all) verify_all exit $? ;; *) echo "Usage: $SCRIPT {start|stop|monitor|status|validate-all|meta-data}" exit $OCF_ERR_UNIMPLEMENTED ;; esac exit 0