repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
DossierSansTitreEx/MiaouOS
src/libc/string/strncat.c
#include <string.h> char* strncat(char* __restrict s1, const char* __restrict s2, size_t n) { size_t i; size_t j; i = 0; j = 0; while (s1[i]) i++; while (s2[j] && j < n) { s1[i + j] = s2[j]; j++; } s1[i + j] = 0; return s1; }
DossierSansTitreEx/MiaouOS
src/sh/main.c
#include <unistd.h> int main() { write(1, "Hello\n", 6); for (;;) {} return 0; } void _start() { /* No CRT yet */ main(); }
DossierSansTitreEx/MiaouOS
include/sys/_types/_uint32_t.h
#ifndef _SYS__TYPES__UINT32_T_H_ #define _SYS__TYPES__UINT32_T_H_ #if defined(__UINT32_TYPE__) typedef __UINT32_TYPE__ uint32_t; #endif #endif
DossierSansTitreEx/MiaouOS
src/libc/string/memcpy.c
#include <string.h> void* memcpy(void* __restrict dst, const void* __restrict src, size_t n) { for (size_t i = 0; i < n; ++i) *((char*)dst + i) = *((char*)src + i); return dst; }
DossierSansTitreEx/MiaouOS
include/sys/_types/_uint64_t.h
<filename>include/sys/_types/_uint64_t.h #ifndef _SYS__TYPES__UINT64_T_H_ #define _SYS__TYPES__UINT64_T_H_ #if defined(__UINT64_TYPE__) typedef __UINT64_TYPE__ uint64_t; #endif #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_ptrdiff_t.h
#ifndef _SYS__TYPES__PTRDIFF_T_H_ #define _SYS__TYPES__PTRDIFF_T_H_ #if defined(__PTRDIFF_TYPE__) typedef __PTRDIFF_TYPE__ ptrdiff_t; #endif #endif
DossierSansTitreEx/MiaouOS
src/effel/proc.c
#include <proc.h> #include <vmm.h> #include <screen.h> #include <mfs.h> #include <string.h> #include <util.h> #include <tss.h> #include <interrupt.h> #include <x86.h> void int_pit(); void int_real_time_clock(); struct proc_table ptable; static void procjmp(struct proc* p) { __asm__ __volatile__ ("mov %0, %%cr3\r\n" :: "r" (p->pml4)); __asm__ __volatile__ ( "pushq 0(%%rax)\r\n" "pushq 8(%%rax)\r\n" "pushq 16(%%rax)\r\n" "pushq 24(%%rax)\r\n" "pushq 32(%%rax)\r\n" "movq 48(%%rax), %%rbx\r\n" "movq 56(%%rax), %%rcx\r\n" "movq 64(%%rax), %%rdx\r\n" "movq 72(%%rax), %%rsi\r\n" "movq 80(%%rax), %%rdi\r\n" "movq 88(%%rax), %%rbp\r\n" "movq 96(%%rax), %%r8\r\n" "movq 104(%%rax), %%r9\r\n" "movq 112(%%rax), %%r10\r\n" "movq 120(%%rax), %%r11\r\n" "movq 128(%%rax), %%r12\r\n" "movq 136(%%rax), %%r13\r\n" "movq 144(%%rax), %%r14\r\n" "movq 152(%%rax), %%r15\r\n" "movq 40(%%rax), %%rax\r\n" "iretq\r\n" :: "a" (p->cpu_state)); } static uint64_t rflags() { uint64_t v; __asm__ __volatile__ ("pushfq\r\n" "popq %0\r\n" : "=r" (v)); return v; } struct proc* proc_current() { return ptable.procs + ptable.running; } void proc_init() { ptable.procs = vmm_alloc(sizeof(struct proc) * 8092, 0); ptable.proc_count = 0; ptable.running = 0; /* Init the PIT */ interrupt_register(0x20, &int_pit); irq_enable(0x00); } static void load_elf(struct proc* p, const mfs_fileinfo* info) { char* ptr; char elf_header[64]; char section_header[256]; uint64_t entry; uint64_t section_offset; uint64_t flags; uint16_t section_size; uint16_t section_count; uint32_t type; uint64_t p_offset; uint64_t p_vaddr; uint64_t p_filesz; uint64_t p_memsz; mfs_read(elf_header, info, 0, 64); entry = *(uint64_t*)(elf_header + 24); section_offset = *(uint64_t*)(elf_header + 32); section_size = *(uint16_t*)(elf_header + 54); section_count = *(uint16_t*)(elf_header + 56); for (size_t i = 0; i < section_count; ++i) { mfs_read(section_header, info, section_offset + section_size * i, section_size); type = *(uint32_t*)(section_header + 0); if (type != 0x01) continue; p_offset = *(uint64_t*)(section_header + 8); p_vaddr = *(uint64_t*)(section_header + 16); p_filesz = *(uint64_t*)(section_header + 32); p_memsz = *(uint64_t*)(section_header + 40); ptr = vmm_allocv(p_vaddr, p_memsz, VMM_USER | VMM_WRITE); if (p_filesz) mfs_read(ptr, info, p_offset, p_filesz); if (p_memsz > p_filesz) memset(ptr + p_filesz, 0, p_memsz - p_filesz); } /* Alloc the CPU state */ struct cpu_state* state; state = vmm_alloc(0x1000, VMM_WRITE); p->cpu_state = state; memset(state, 0, sizeof(*state)); /* Allocate a stack */ vmm_allocv(0xa0000000, 0x4000, VMM_USER | VMM_WRITE); /* Setup the state */ state->ss = 0x23; state->rsp = state->rbp = 0xa0004000; flags = rflags(); flags &= 0xfffffffffffffffe; flags |= 0x0200; state->rflags = flags; state->cs = 0x2b; state->rip = entry; } void proc_create(const char* s) { mfs_fileinfo info; struct proc* p; mfs_read_info(&info, s); kprint("Loading "); kprint(s); kputchar('\n'); p = &ptable.procs[ptable.proc_count++]; p->flags = 0; p->pml4 = vmm_kfork(); load_elf(p, &info); } void proc_schedule() { ptable.running = 0; procjmp(ptable.procs); } void proc_scheduler_main() { ptable.running++; if (ptable.running >= ptable.proc_count) ptable.running = 0; procjmp(ptable.procs + ptable.running); }
DossierSansTitreEx/MiaouOS
include/sys/_types/_wchar_t.h
<gh_stars>1-10 #ifndef _SYS__TYPES__WCHAR_T_H_ #define _SYS__TYPES__WCHAR_T_H_ #if defined(__INT32_TYPE__) typedef __INT32_TYPE__ wchar_t; #endif #endif
DossierSansTitreEx/MiaouOS
include/effel/effel.h
#ifndef _EFFEL_H #define _EFFEL_H 1 #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_uintptr_t.h
<filename>include/sys/_types/_uintptr_t.h #ifndef _SYS__TYPES__UINTPTR_T_H_ #define _SYS__TYPES__UINTPTR_T_H_ #if defined(__UINTPTR_TYPE__) typedef __UINTPTR_TYPE__ uintptr_t; #endif #endif
DossierSansTitreEx/MiaouOS
src/effel/tss.c
#include <tss.h> #include <string.h> __attribute__ ((aligned (16))) static char tss_default_stack[4096]; struct tss tss; void tss_init() { memset(&tss, 0, sizeof(tss)); tss.rsp[0] = ((uint64_t)tss_default_stack) + 4096; tss.iomb = sizeof(tss); __asm__ __volatile__ ("ltr %%ax\r\n" :: "a" (0x30)); }
DossierSansTitreEx/MiaouOS
src/libc/string/strlen.c
#include <string.h> __attribute__((pure)) size_t strlen(const char* s) { size_t len; len = 0; while (s[len]) len++; return len; }
DossierSansTitreEx/MiaouOS
src/libc/string/strncmp.c
<gh_stars>1-10 #include <string.h> int strncmp(const char* s1, const char* s2, size_t n) { size_t i; int diff; int c1; int c2; for (i = 0; i < n; ++i) { c1 = (unsigned char)(s1[i]); c2 = (unsigned char)(s2[i]); diff = c1 - c2; if (diff) return diff; if (c1 == 0) return 0; } return 0; }
DossierSansTitreEx/MiaouOS
src/effel/mfs.c
<filename>src/effel/mfs.c #include <mfs.h> #include <ata.h> #include <vmm.h> #include <string.h> static struct mfs mfs; static void read_inode(char* dst, uint64_t inode) { ata_read(dst, mfs.lba + 40 + inode * 8, 8, &mfs.dpte); } void mfs_init(const boot_params* params) { mfs.device = params->drive; mfs.lba = params->mbr->lba_base; mfs.dpte = params->dpte; } void mfs_init_buffers() { for (size_t i = 0; i < 4; ++i) mfs.buffers[i] = vmm_alloc(4096, 0); read_inode(mfs.buffers[0], 0); mfs.root = *(uint64_t*)(mfs.buffers[0] + 0x18); } static void read_info_inode(mfs_fileinfo* info, uint64_t inode) { info->inode = inode; read_inode(mfs.buffers[0], inode); info->size = *(uint64_t*)(mfs.buffers[0] + 0x38); for (size_t i = 0; i < 12; ++i) info->data[i] = *(uint64_t*)(mfs.buffers[0] + 0x40 + 8 * i); info->idata = *(uint64_t*)(mfs.buffers[0] + 0x100); } static uint64_t find_child(uint64_t parent, const char* name) { mfs_fileinfo info; uint16_t namelen; uint64_t inode; char namebuf[256]; size_t i; read_info_inode(&info, parent); mfs_read(mfs.buffers[0], &info, 0, 4096); i = 0; for (;;) { namelen = *(uint16_t*)(mfs.buffers[0] + i); i += 2; memcpy(namebuf, mfs.buffers[0] + i, namelen); namebuf[namelen] = 0; i += namelen; inode = *(uint64_t*)(mfs.buffers[0] + i); if (strcmp(name, namebuf) == 0) return inode; } } void mfs_read_info(mfs_fileinfo* info, const char* path) { uint64_t inode; char name[256]; size_t i; inode = mfs.root; for (;;) { while (*path == '/') path++; if (*path == 0) break; for (i = 0; path[i] && path[i] != '/'; i++) name[i] = path[i]; name[i] = 0; path += i; inode = find_child(inode, name); } read_info_inode(info, inode); } void mfs_read(char* dst, const mfs_fileinfo* info, size_t offset, size_t length) { size_t chunk_first; size_t chunk_last; size_t chunk_count; size_t chunk; uint64_t inode; size_t len; chunk_first = offset / 4096; chunk_last = (offset + length - 1) / 4096; chunk_count = chunk_last - chunk_first + 1; size_t range_start; size_t range_end; for (size_t i = 0; i < chunk_count; ++i) { chunk = chunk_first + i; if (chunk < 12) inode = info->data[chunk]; else { read_inode(mfs.buffers[0], info->idata); inode = *(uint64_t*)(mfs.buffers[0] + (chunk - 12) * 8); } if (i == 0) range_start = (offset % 4096); else range_start = 0; if (i == chunk_count - 1) range_end = ((offset + length - 1) % 4096) + 1; else range_end = 4096; len = range_end - range_start; if (len == 4096) read_inode(dst, inode); else { read_inode(mfs.buffers[3], inode); memcpy(dst, mfs.buffers[3] + range_start, len); } dst += len; } }
DossierSansTitreEx/MiaouOS
src/effel/gdt.c
#include <gdt.h> #include <tss.h> #include <stdint.h> #include <stddef.h> #include <string.h> #include <util.h> struct gdt_entry { unsigned int limit_low:16; unsigned int base_low:24; unsigned int accessed:1; unsigned int read_write:1; unsigned int conforming_expand_down:1; unsigned int code:1; unsigned int sys:1; unsigned int dpl:2; unsigned int present:1; unsigned int limit_high:4; unsigned int zero:1; unsigned int long_mode:1; unsigned int big:1; unsigned int gran:1; unsigned int base_high:8; } __attribute__ ((packed)); struct gdt { uint16_t length; uint64_t ptr; } __attribute__ ((packed)); __attribute__ ((aligned (16))) static struct gdt gdt; static struct gdt_entry entries[8]; static void gdt_init_tss(uint16_t seg, void* ptr, size_t size) { struct gdt_entry* e; uint64_t base; uint64_t limit; e = entries + (seg >> 3); base = (uint64_t)ptr; limit = size - 1; e->limit_low = limit & 0xffff; e->base_low = base & 0xffffff; e->accessed = 1; e->code = 1; e->dpl = 3; e->present = 1; e->limit_high = ((limit & 0xff0000) >> 16); e->base_high = ((base & 0xff000000) >> 24); *((uint32_t*)(e + 1)) = ((base & 0xffffffff00000000) >> 32); } static void gdt_init_seg(size_t seg, int code, int ring) { struct gdt_entry* e; e = entries + (seg >> 3); e->limit_low = 0; e->base_low = 0; e->accessed = 0; if (code) { e->read_write = 0; e->code = 1; } else { e->read_write = 1; e->code = 0; } e->conforming_expand_down = 0; e->sys = 1; e->dpl = ring & 0x03; e->present = 1; e->limit_high = 0; e->zero = 0; e->long_mode = 1; e->big = 0; e->gran = 0; e->base_high = 0; } void gdt_switch(void* addr, uint64_t code_seg, uint64_t data_seg); void gdt_init() { memset(entries, 0, sizeof(entries)); gdt_init_seg(0x08, 1, 0); gdt_init_seg(0x10, 0, 0); gdt_init_seg(0x20, 0, 3); gdt_init_seg(0x28, 1, 3); gdt_init_tss(0x30, &tss, sizeof(tss)); gdt.ptr = (uint64_t)entries; gdt.length = (sizeof(entries) - 1); gdt_switch(&gdt, 0x08, 0x10); }
DossierSansTitreEx/MiaouOS
src/effel/screen.h
<reponame>DossierSansTitreEx/MiaouOS #ifndef _SCREEN_H #define _SCREEN_H 1 #include <stddef.h> void kscroll(); void kputchar(char c); void kprint(const char* s); void kprint_raw(const char* s, size_t size); void kputs(const char* s); void kprint_hex(uint64_t num); void screen_init(); #endif
DossierSansTitreEx/MiaouOS
include/sys/cpuid.h
<gh_stars>1-10 #ifndef _SYS_CPUID_H_ #define _SYS_CPUID_H_ #include <stdint.h> #include <sys/cdefs.h> __BEGIN_DECL inline void cpuid4(uint32_t* dst, uint32_t a, uint32_t b, uint32_t c, uint32_t d) { __asm__ __volatile__ ("cpuid\r\n" : "=a"(dst[0]), "=b"(dst[1]), "=c"(dst[2]), "=d"(dst[3]) : "a"(a), "b"(b), "c"(c), "d"(d)); } inline void cpuid(uint32_t* dst, uint32_t code) { __asm__ __volatile__ ("cpuid\r\n" : "=a"(dst[0]), "=b"(dst[1]), "=c"(dst[2]), "=d"(dst[3]) : "a"(code)); } __END_DECL #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_intptr_t.h
<gh_stars>1-10 #ifndef _SYS__TYPES__INTPTR_T_H_ #define _SYS__TYPES__INTPTR_T_H_ #if defined(__INTPTR_TYPE__) typedef __INTPTR_TYPE__ intptr_t; #endif #endif
DossierSansTitreEx/MiaouOS
src/effel/x86.h
#ifndef X86_H #define X86_H #include <stdint.h> static inline void outb(uint16_t port, uint8_t v) { __asm__ __volatile__ ("outb %0, %1" :: "a"(v), "Nd"(port)); } static inline void outw(uint16_t port, uint16_t v) { __asm__ __volatile__ ("outw %0, %1" :: "a"(v), "d"(port)); } static inline void outl(uint16_t port, uint32_t v) { __asm__ __volatile__ ("outl %0, %1" :: "a"(v), "d"(port)); } static inline uint8_t inb(uint16_t port) { uint8_t v; __asm__ __volatile__ ("inb %1, %0" : "=a"(v) : "Nd"(port)); return v; } static inline uint16_t inw(uint16_t port) { uint16_t v; __asm__ __volatile__ ("inw %1, %0" : "=a"(v) : "d"(port)); return v; } static inline uint32_t inl(uint16_t port) { uint32_t v; __asm__ __volatile__ ("inl %1, %0" : "=a"(v) : "d"(port)); return v; } static inline void io_wait() { outb(0x80, 0x00); } #endif
DossierSansTitreEx/MiaouOS
src/effel/main.c
<filename>src/effel/main.c #include <gdt.h> #include <tss.h> #include <vmm.h> #include <screen.h> #include <proc.h> #include <mfs.h> #include <syscall.h> #include <interrupt.h> void kmain(boot_params* params) { gdt_init(); tss_init(); mfs_init(params); vmm_init(params); interrupt_init(); screen_init(); proc_init(); mfs_init_buffers(); syscall_init(); kputs("Hello from the kernel!"); for (int i = 0; i < 4; ++i) proc_create("/bin/sh"); proc_schedule(); for (;;) {} }
DossierSansTitreEx/MiaouOS
src/libc/string/strchr.c
#include <string.h> char* strchr(const char* s, int c) { size_t i; char cc; char sc; i = 0; cc = c; for (;;) { sc = s[i]; if (sc == cc) return (char*)s + i; if (sc == 0) return NULL; i++; } }
DossierSansTitreEx/MiaouOS
include/sys/_types/_null.h
#ifndef _SYS__TYPES__NULL_H_ #define _SYS__TYPES__NULL_H_ #if defined(__cplusplus) # define NULL (0) #else # define NULL ((void *)0) #endif #endif
DossierSansTitreEx/MiaouOS
include/boot/boot_params.h
<reponame>DossierSansTitreEx/MiaouOS<gh_stars>1-10 #ifndef INCLUDED_BOOT_PARAMS_H #define INCLUDED_BOOT_PARAMS_H #include <stdint.h> struct mbr_entry_ { uint8_t status; uint8_t chs[3]; uint8_t type; uint8_t chs_end[3]; uint32_t lba_base; uint32_t lba_length; } __attribute__ ((packed)); typedef struct mbr_entry_ mbr_entry; struct memory_zone_ { uint64_t base; uint64_t length; uint32_t type; uint32_t flags; } __attribute__ ((packed)); typedef struct memory_zone_ memory_zone; struct dpte { uint16_t port_io; uint16_t port_ctl; uint8_t head; uint8_t padding[11]; } __attribute__ ((packed)); struct boot_params_ { uint64_t memory_size; memory_zone* memory_zones; mbr_entry* mbr; struct dpte dpte; uint8_t drive; } __attribute__ ((packed)); typedef struct boot_params_ boot_params; #endif
DossierSansTitreEx/MiaouOS
src/effel/syscall.h
#ifndef _SYSCALL_H #define _SYSCALL_H 1 void syscall_init(); #endif
DossierSansTitreEx/MiaouOS
src/effel/ata.h
<gh_stars>1-10 #ifndef _EFFEL_ATA #define _EFFEL_ATA 1 #include <stdint.h> void ata_read(void* dst, uint64_t lba, size_t size, void* dpte); #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_uint8_t.h
<gh_stars>1-10 #ifndef _SYS__TYPES__UINT8_T_H_ #define _SYS__TYPES__UINT8_T_H_ #if defined(__UINT8_TYPE__) typedef __UINT8_TYPE__ uint8_t; #endif #endif
DossierSansTitreEx/MiaouOS
include/errno.h
<reponame>DossierSansTitreEx/MiaouOS #ifndef _ERRNO_H #define _ERRNO_H 1 #include <sys/cdefs.h> #define errno (*(__errno())) int* __errno(void) __attribute__((const)); #define E2BIG 1 #define EACCES 2 #define EADDRINUSE 3 #define EADDRNOTAVAIL 4 #define EAFNOSUPPORT 5 #define EAGAIN 6 #define EALREADY 7 #define EBADF 8 #define EBADMSG 9 #define EBUSY 10 #define ECANCELED 11 #define ECHILD 12 #define ECONNABORTED 13 #define ECONNREFUSED 14 #define ECONNRESET 15 #define EDEADLK 16 #define EDESTADDRREQ 17 #define EDOM 18 #define EDQUOT 19 #define EEXIST 20 #define EFAULT 21 #define EFBIG 22 #define EHOSTUNREACH 23 #define EIDRM 24 #define EILSEQ 25 #define EINPROGRESS 26 #define EINTR 27 #define EINVAL 28 #define EIO 29 #define EISCONN 30 #define EISDIR 31 #define ELOOP 32 #define EMFILE 33 #define EMLINK 34 #define EMSGSIZE 35 #define EMULTIHOP 36 #define ENAMETOOLONG 37 #define ENETDOWN 38 #define ENETRESET 39 #define ENETUNREACH 40 #define ENFILE 41 #define ENOBUFS 42 #define ENODATA 43 #define ENODEV 44 #define ENOENT 45 #define ENOEXEC 46 #define ENOLCK 47 #define ENOLINK 48 #define ENOMEM 49 #define ENOMSG 50 #define ENOPROTOOPT 51 #define ENOSPC 52 #define ENOSR 53 #define ENOSTR 54 #define ENOSYS 55 #define ENOTCONN 56 #define ENOTDIR 57 #define ENOTEMPTY 58 #define ENOTRECOVERABLE 59 #define ENOTSOCK 60 #define ENOTSUP 61 #define ENOTTY 62 #define ENXIO 63 #define EOPNOTSUPP ENOTSUP #define EOVERFLOW 64 #define EOWNERDEAD 65 #define EPERM 66 #define EPIPE 67 #define EPROTO 68 #define EPROTONOSUPPORT 69 #define EPROTOTYPE 70 #define ERANGE 71 #define EROFS 72 #define ESPIPE 73 #define ESRCH 74 #define ESTALE 75 #define ETIME 76 #define ETIMEDOUT 77 #define ETXTBSY 78 #define EWOULDBLOCK EAGAIN #define EXDEV 79 #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_int8_t.h
#ifndef _SYS__TYPES__INT8_T_H_ #define _SYS__TYPES__INT8_T_H_ #if defined(__INT8_TYPE__) typedef __INT8_TYPE__ int8_t; #endif #endif
DossierSansTitreEx/MiaouOS
src/effel/interrupt.c
#include <stdint.h> #include <interrupt.h> #include <x86.h> #include <string.h> struct idt_entry { uint16_t offset_low; uint16_t selector; uint8_t zero1; uint8_t type; uint16_t offset_mid; uint32_t offset_high; uint32_t zero2; } __attribute__ ((packed)); struct idt { uint16_t size; struct idt_entry* ptr; } __attribute__ ((packed)); __attribute__ ((aligned (16))) static struct idt idt; static struct idt_entry entries[256]; static void pic_init() { outb(0x20, 0x11); io_wait(); outb(0xa0, 0x11); io_wait(); outb(0x21, 0x20); io_wait(); outb(0xa1, 0x28); io_wait(); outb(0x21, 0x04); io_wait(); outb(0xa1, 0x02); io_wait(); outb(0x21, 0x01); io_wait(); outb(0xa1, 0x01); io_wait(); outb(0x21, 0xff); io_wait(); outb(0xa1, 0xff); io_wait(); } void irq_enable(uint8_t line) { uint16_t port; uint8_t mask; if (line < 8) { port = 0x21; } else { port = 0xa1; line -= 8; } mask = inb(port); mask &= ~(1 << line); outb(port, mask); } void irq_disable(uint8_t line) { uint16_t port; uint8_t mask; if (line < 8) { port = 0x21; } else { port = 0xa1; line -= 8; } mask = inb(port); mask |= (1 << line); outb(port, mask); } void interrupt_register(uint8_t slot, void* isr) { uint64_t isr_value; struct idt_entry* e; isr_value = (uint64_t)isr; e = entries + slot; e->offset_low = isr_value & 0xffff; e->selector = 0x08; e->zero1 = 0; e->type = 0x8e; e->offset_mid = (isr_value >> 16) & 0xffff; e->offset_high = (isr_value >> 32) & 0xffffffff; } void interrupt_init() { pic_init(); memset(entries, 0, sizeof(entries)); idt.size = sizeof(entries) - 1; idt.ptr = entries; __asm__ __volatile__ ("lidt (%0)\r\n" :: "r" (&idt)); }
DossierSansTitreEx/MiaouOS
include/iso646.h
<reponame>DossierSansTitreEx/MiaouOS #ifndef _ISO646_H #define _ISO646_H 1 #if !defined(__cplusplus) # define and && # define and_eq &= # define bitand & # define bitor | # define compl ~ # define not ! # define not_eq != # define or || # define or_eq |= # define xor ^ # define xor_eq ^= #endif #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_int64_t.h
<reponame>DossierSansTitreEx/MiaouOS #ifndef _SYS__TYPES__INT64_T_H_ #define _SYS__TYPES__INT64_T_H_ #if defined(__INT64_TYPE__) typedef __INT64_TYPE__ int64_t; #endif #endif
DossierSansTitreEx/MiaouOS
include/sys/_types/_int16_t.h
#ifndef _SYS__TYPES__INT16_T_H_ #define _SYS__TYPES__INT16_T_H_ #if defined(__INT16_TYPE__) typedef __INT16_TYPE__ int16_t; #endif #endif
DossierSansTitreEx/MiaouOS
src/libc/string/strlcpy.c
#include <string.h> size_t strlcpy(char* __restrict dst, const char* __restrict src, size_t len) { size_t i; char c; for (i = 0; i < len; ++i) { c = src[i]; dst[i] = c; if (c == 0) return strlen(src); } dst[len] = 0; return strlen(src); }
AI-Pranto/OpenMOC
src/Point.h
<gh_stars>10-100 /** * @file Point.h * @brief The Point class. * @date January 18, 2012 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef POINT_H_ #define POINT_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "log.h" #include <math.h> #include <sstream> #endif /** * @class Point Point.h "src/Point.h" * @brief Class to represent a 2D/3D point in space. */ class Point { private: /** The Point's xyz coordinates */ double _xyz[3]; public: Point(); virtual ~Point(); void setCoords(const double x, const double y, const double z=0.0); double getX() const; double getY() const; double getZ() const; double* getXYZ(); void setX(const double x); void setY(const double y); void setZ(const double z); double distance(const double x, const double y, const double z) const; double distanceToPoint(const Point* point); void copyCoords(Point* point); std::string toString(); void setXYZ(double* xyz); }; /** * @brief Initializes a Point with two-dimensional coordinates. * @param x x-coordinate * @param y y-coordinate * @param z z-coordinate */ inline void Point::setCoords(const double x, const double y, const double z) { _xyz[0] = x; _xyz[1] = y; _xyz[2] = z; } /** * @brief Returns this Point's x-coordinate. * @return the x-coordinate */ inline double Point::getX() const { return _xyz[0]; } /** * @brief Returns this Point's y-coordinate. * @return the y-coordinate */ inline double Point::getY() const { return _xyz[1]; } /** * @brief Returns this Point's z-coordinate. * @return the z-coordinate */ inline double Point::getZ() const { return _xyz[2]; } /** * @brief Returns this Point's coordinates. * @return the xyz coordinates */ inline double* Point::getXYZ() { return _xyz; } /** * @brief Set the Point's x-coordinate. * @param x the new x-coordinate */ inline void Point::setX(const double x) { _xyz[0] = x; } /** * @brief Set the Point's y-coordinate. * @param y the new y-coordinate */ inline void Point::setY(const double y) { _xyz[1] = y; } /** * @brief Set the Point's z-coordinate. * @param z the new z-coordinate */ inline void Point::setZ(const double z) { _xyz[2] = z; } /** * @brief Set the Point's x, y and z-coordinates. * @param xyz array with the three coordinates */ inline void Point::setXYZ(double* xyz) { _xyz[0] = xyz[0]; _xyz[1] = xyz[1]; _xyz[2] = xyz[2]; } /** * @brief Compute the distance from this Point to another Point of interest. * @param x the x-coordinate of the Point of interest * @param y the y-coordinate of the Point of interest * @param z the z-coordinate of the Point of interest * @return distance to the Point of interest */ inline double Point::distance(const double x, const double y, const double z) const { double deltax = _xyz[0] - x; double deltay = _xyz[1] - y; double deltaz = _xyz[2] - z; return sqrt(deltax*deltax + deltay*deltay + deltaz*deltaz); } /** * @brief Compute the distance from this Point to another Point of interest. * @param point a pointer to the Point of interest * @return distance to the Point of interest */ inline double Point::distanceToPoint(const Point* point) { double deltax = _xyz[0] - point->getX(); double deltay = _xyz[1] - point->getY(); double deltaz = _xyz[2] - point->getZ(); return sqrt(deltax*deltax + deltay*deltay + deltaz*deltaz); } /** * @brief Copy the coordinates from another point. * @param point a pointer to the Point that has the coordinates of interest */ inline void Point::copyCoords(Point* point) { _xyz[0] = point->getX(); _xyz[1] = point->getY(); _xyz[2] = point->getZ(); } #endif /* POINT_H_ */
AI-Pranto/OpenMOC
src/accel/cuda/clone.h
<reponame>AI-Pranto/OpenMOC<gh_stars>10-100 /** * @file clone.h * @brief Routines to copy Material and Track objects to the GPU from CPU. * @author May 30, 2013 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #include "../DeviceMaterial.h" #include "../DeviceTrack.h" #include "GPUQuery.h" #include <map> void clone_material(Material* material_h, dev_material* material_d); void clone_track(Track* track_h, dev_track* track_d, std::map<int, int> &material_IDs_to_indices);
AI-Pranto/OpenMOC
src/TrackGenerator3D.h
<gh_stars>10-100 /** * @file TrackGenerator3D.h * @brief The TrackGenerator3D class. * @date March 13, 2016 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef TRACKGENERATOR3D_H_ #define TRACKGENERATOR3D_H_ #include "TrackGenerator.h" #include "Track3D.h" /** * @struct TrackChainIndexes * @brief A Track chain represents a list of Tracks connected via periodic BCs * that extend in the l-z plane and this struct contains the azim, x, polar, * lz, and link indexes of a Track. */ struct TrackChainIndexes { /** The azimuthal index (in 0 to _num_azim / 4) */ int _azim; /** The x index (in 0 to _num_x[_azim]) */ int _x; /** The polar index (in 0 to _num_polar) */ int _polar; /** The lz index (in 0 to _num_l[_azim][_polar] + _num_z[_azim][_polar]) */ int _lz; /** The link index of the chain */ int _link; /** Constructor initializes each attribute to -1 */ TrackChainIndexes() { _azim = -1; _x = -1; _polar = -1; _lz = -1; _link = -1; } }; /** * @struct TrackStackIndexes * @brief A stack track represents a track in a z-stack of tracks and this * struct contains the azim, xy, polar, and z indices of a track. */ struct TrackStackIndexes { /** The azimuthal index (in 0 to _num_azim / 2) */ int _azim; /** The xy index (in 0 to _num_x[_azim] + _num_y[_azim]) */ int _xy; /** The polar index (in 0 to _num_polar) */ int _polar; /** The z index in the z-stack (in 0 to _tracks_per_stack[_azim][_xy][_polar]) */ int _z; /** Constructor initializes each attribute to -1 */ TrackStackIndexes() { _azim = -1; _xy = -1; _polar = -1; _z = -1; } }; /** * @class TrackGenerator3D TrackGenerator3D.h "src/TrackGenerator3D.h" * @brief The TrackGenerator3D is dedicated to generating and storing Tracks * which cyclically wrap across the Geometry in three dimensions. * @details The TrackGenerator creates Track and initializes boundary * conditions (vacuum, reflective, or periodic) for each Track in * three dimensions. */ class TrackGenerator3D : public TrackGenerator { private: /** Number of polar angles in \f$ [0, \pi] \f$ */ int _num_polar; /** The requested track z-spacing (cm) */ double _z_spacing; /** A 2D ragged array of 2D track chains (azim, x index, link index) */ Track**** _tracks_2D_chains; /** An array of the # of 3D tracks in each z-stack (azim, 2D track, polar) */ int*** _tracks_per_stack; /** An array of the Track UID for the first Track and polar angle in each * z-stack (azim, xy, polar) */ long*** _cum_tracks_per_stack; /** An array of the Track UID for the first Track in each z-stack * (azim, xy) */ long** _cum_tracks_per_xy; /** An array of the first Track's l-z index for each z-stack */ int*** _first_lz_of_stack; /** The total number of Tracks for all azimuthal and polar angles */ int _num_3D_tracks; /** Arrays of the number of Tracks starting on each axis */ int** _num_z; int** _num_l; /* Arrays for the spacing along each axis */ double** _dz_eff; double** _dl_eff; /** An array of 3D tracks (azim, 2D track, polar, z-stack) */ Track3D**** _tracks_3D; /** The mesh defining axial heights of radial planes segmented in on-the-fly * calculations */ std::vector<double> _segmentation_heights; /** The global axial mesh to use in on-the-fly calculations */ std::vector<double> _global_z_mesh; /** Dimensions of temporary segments storage matrix */ int _num_seg_matrix_rows; int _num_seg_matrix_columns; /** A matrix of temporary segments are created for on-the-fly methods to * improve efficiency */ std::vector<segment*> _temporary_segments; bool _contains_temporary_segments; /** An array temporary Tracks are created for on-the-fly methods to * improve efficiency for every thread */ std::vector<Track3D*> _temporary_3D_tracks; std::vector<Track**> _temporary_tracks_array; bool _contains_temporary_tracks; /** Maximum number of tracks a single 3D track stack for on-the-fly * computation */ int _max_num_tracks_per_stack; /** Booleans to indicate whether the Tracks and segments have been generated * (true) or not (false) */ bool _contains_3D_tracks; bool _contains_3D_segments; bool _contains_global_z_mesh; bool _contains_segmentation_heights; /** Private class methods */ void initializeTracks(); void initialize2DTrackChains(); void recalibrateTracksToOrigin(); void segmentize(); void setContainsSegments(bool contains_segments); void allocateTemporarySegments(); void allocateTemporaryTracks(); void resetStatus(); void initializeDefaultQuadrature(); std::string getTestFilename(std::string directory); void getCycleTrackData(TrackChainIndexes* tcis, int num_cycles, bool save_tracks); void segmentizeExtruded(); void set3DTrackData(TrackChainIndexes* tci, Track3D* track, bool create_arrays, bool save_tracks); double getLStart(TrackChainIndexes* tci); int getFirst2DTrackLinkIndex(TrackChainIndexes* tci, Track3D* track_3D); void writeExtrudedFSRInfo(FILE* out); void readExtrudedFSRInfo(FILE* in); public: TrackGenerator3D(Geometry* geometry, int num_azim, int num_polar, double azim_spacing, double z_spacing); virtual ~TrackGenerator3D(); /* Get parameters */ int getNumPolar(); double getDesiredZSpacing(); long getNumTracks(); long getNumSegments(); long getNum3DTracks(); long getNum3DSegments(); Track3D**** get3DTracks(); double getZSpacing(int azim, int polar); int getNumRows(); int getNumColumns(); segment* getTemporarySegments(int thread_id); Track3D* getTemporary3DTracks(int thread_id); Track** getTemporaryTracksArray(int thread_id); int getNumZ(int azim, int polar); int getNumL(int azim, int polar); int*** getTracksPerStack(); int getMaxNumTracksPerStack(); bool containsTracks(); bool containsSegments(); bool containsTemporaryTracks(); long get3DTrackID(TrackStackIndexes* tsi); void convertTCItoTSI(TrackChainIndexes* tci, TrackStackIndexes* tsi); void convertTSItoTCI(TrackStackIndexes* tsi, TrackChainIndexes* tci); int getLinkIndex(TrackChainIndexes* tci); int getNum3DTrackChainLinks(TrackChainIndexes* tci); void getTSIByIndex(long id, TrackStackIndexes* tsi); void getTrackOTF(Track3D* track, TrackStackIndexes* tsi); /* Set parameters */ void setNumPolar(int num_polar); void setDesiredZSpacing(double spacing); void setSegmentFormation(segmentationType segmentation_type); void setSegmentationZones(std::vector<double> z_mesh); void setLinkingTracks(TrackStackIndexes* tsi, TrackChainIndexes* tci, bool outgoing, Track3D* track); void setLinkIndex(TrackChainIndexes* tci, TrackStackIndexes* tsi); void useGlobalZMesh(); /* Worker functions */ void retrieveTrackCoords(double* coords, long num_tracks); void retrieve3DTrackCoords(double* coords, long num_tracks); void retrieveGlobalZMesh(double*& z_mesh, int& num_fsrs); void retrieveSingle3DTrackCoords(double coords[6], long track_id); void retrieveSegmentCoords(double* coords, long num_segments); void retrieve3DSegmentCoords(double* coords, long num_segments); void create3DTracksArrays(); void checkBoundaryConditions(); }; #endif /* TRACKGENERATOR3D_H_ */
AI-Pranto/OpenMOC
src/LocalCoords.h
<reponame>AI-Pranto/OpenMOC /** * @file LocalCoords.h * @brief The LocalCoords class. * @date January 25, 2012 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef LOCALCOORDS_H_ #define LOCALCOORDS_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "Point.h" #include "Universe.h" #include "Cell.h" #include "constants.h" #endif /* Forward declarations to resolve circular dependencies */ class Universe; class Lattice; class Cell; /** * @enum coordType * @brief The type of Universe level on which the LocalCoords reside */ enum coordType { /** A Universe level coordinate type */ UNIV, /** A Lattice level coordinate type */ LAT }; /** * @class LocalCoords LocalCoords.h "openmoc/src/host/LocalCoords.h" * @brief The LocalCoords represents a set of local coordinates on some * level of nested Universes making up the geometry. * _next and _prev allow for use of LocalCoords as a linked list * but _next_array can also be used to access coordinates. */ class LocalCoords { private: /** The local coordinate type (UNIV or LAT) */ coordType _type; /** The Universe within which this LocalCoords resides */ Universe* _universe; /** The Cell within which this LocalCoords resides */ Cell* _cell; /** The Lattice within which this LocalCoords resides */ Lattice* _lattice; /** The first index of the Lattice cell within which this LocalCoords * resides */ int _lattice_x; /** The second index of the Lattice cell within which this LocalCoords * resides */ int _lattice_y; /** The third index of the Lattice cell within which this LocalCoords * resides */ int _lattice_z; /** A Point representing the 3D coordinates of this LocalCoords */ Point _coords; /** The direction angle in radians with respect to the x-axis */ double _phi; /** The direction angle in radians with respect to the z-axis */ double _polar; /** A pointer to the LocalCoords at the next lower nested Universe level */ LocalCoords* _next; /** A pointer to the LocalCoords at the next higher nested Universe level */ LocalCoords* _prev; /** An array that contains pointers to all the next LocalCoords */ LocalCoords* _next_array; /** Position in the _next_array of coordinates */ int _position; /** Size of the _next_array of coordinates */ int _array_size; /** An integer to differentiate otherwise matching coordinate FSR keys */ int _version_num; void setArrayPosition(LocalCoords* array, int position, int array_size); public: LocalCoords(double x=0.0, double y=0.0, double z=0.0, bool first=false); virtual ~LocalCoords(); coordType getType(); Universe* getUniverse() const; Cell* getCell() const; Lattice* getLattice() const; int getLatticeX() const; int getLatticeY() const; int getLatticeZ() const; double getX() const; double getY() const; double getZ() const; double getPhi() const; double getPolar() const; Point* getPoint(); LocalCoords* getNext() const; LocalCoords* getNextCreate(double x, double y, double z); LocalCoords* getPrev() const; int getVersionNum(); int getPosition(); void setType(coordType type); void setUniverse(Universe* universe); void setCell(Cell* cell); void setLattice(Lattice* lattice); void setLatticeX(int lattice_x); void setLatticeY(int lattice_y); void setLatticeZ(int lattice_z); void setX(double x); void setY(double y); void setZ(double z); void setPhi(double phi); void setPolar(double polar); void setNext(LocalCoords *next); void setPrev(LocalCoords* coords); void setVersionNum(int version_num); LocalCoords* getLowestLevel(); LocalCoords* getHighestLevel(); void adjustCoords(double delta_x, double delta_y, double delta_z=0.0); void updateMostLocal(Point* point); void prune(); void deleteArray(); void copyCoords(LocalCoords* coords); std::string toString(); void detectLoop(); }; #endif /* LOCALCOORDS_H_ */
AI-Pranto/OpenMOC
src/Mesh.h
<reponame>AI-Pranto/OpenMOC<filename>src/Mesh.h /** * @file Mesh.h * @brief The Mesh class for the alternative C++ build. * @date November, 2016 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef MESH_H #define MESH_H #include "Universe.h" #include "Solver.h" #include "Geometry.h" /* A Vector3D is simply a 3-dimensional std::vector of floats */ typedef std::vector<std::vector<std::vector<FP_PRECISION> > > Vector3D; /** * @enum RxType * @brief The type of reaction to be tallied */ enum RxType { FISSION_RX, NUFISSION_RX, TOTAL_RX, ABSORPTION_RX, FLUX_RX, VOLUME }; /** * @class Mesh Mesh.h "src/Mesh.h" * @brief A Mesh is a lattice overlaid on the Geometry across which reaction * rates can be tallied from converged scalar fluxes in a Solver */ class Mesh { /* The solver from which scalar fluxes and cross-sections are extracted */ Solver* _solver; /* The lattice defining the zones across which reaction rates are tallied */ Lattice* _lattice; /* A flag indicating whether a lattice has been allocated internally */ bool _lattice_allocated; public: Mesh(Solver* solver, Lattice* lattice=NULL); virtual ~Mesh(); void createLattice(int num_x, int num_y, int num_z=1); void setLattice(Lattice* lattice); std::vector<FP_PRECISION> getReactionRates(RxType rx, bool volume_average=false); Vector3D getFormattedReactionRates(RxType rx, bool volume_average=false); Vector3D getNonUniformFormattedReactionRates(std::vector<std::vector<double> > widths_offsets, RxType rx, bool volume_average=false); }; #endif
AI-Pranto/OpenMOC
src/pairwise_sum.h
<filename>src/pairwise_sum.h /** * @file pairwise_sum.h * @brief Utility function for the accurate pairwise sum of a list of floating * point numbers. * @author <NAME> (<EMAIL>) * @date June 13, 2013 */ /** * @brief Performs a pairwise sum of an array of numbers. * @details This type of summation uses a divide-and-conquer algorithm which * is necessary to bound the error for summations of large sequences * of numbers. * @param vector an array of numbers * @param length the length of the array * @return the sum of all numbers in the array */ template <typename T, typename L> inline double pairwise_sum(T* vector, L length) { double sum = 0; /* Base case: if length is less than SIMD vector length, perform summation */ if (length < VEC_LENGTH) { #pragma omp simd reduction(+:sum) for (L i=0; i < length; i++) sum += vector[i]; } else { L offset = length % 2; length = floor(length / 2); sum = pairwise_sum<T>(&vector[0], length) + pairwise_sum<T>(&vector[length], length+offset); } return sum; }
AI-Pranto/OpenMOC
src/boundary_type.h
<filename>src/boundary_type.h /** * @file boundary_type.h * @details The boundaryType enum. * @date January 10, 2015 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef BOUNDARY_TYPE_H_ #define BOUNDARY_TYPE_H_ /** * @enum boundaryType * @brief The types of boundary conditions supported by OpenMOC for Surfaces. */ enum boundaryType { /** A vacuum boundary condition */ VACUUM, /** A reflective boundary condition */ REFLECTIVE, /** A periodic boundary condition */ PERIODIC, /* Boundary between two domains (only in domain-decomposed geometry) */ INTERFACE, /** No boundary type (typically an interface between flat source regions) */ BOUNDARY_NONE }; #endif /* BOUNDARY_TYPE_H_ */
AI-Pranto/OpenMOC
src/MOCKernel.h
<reponame>AI-Pranto/OpenMOC<filename>src/MOCKernel.h /** * @file MOCKernel.h * @brief An MOCKernel object * @date May 5, 2015 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef MOCKERNEL_H_ #define MOCKERNEL_H_ #ifdef SWIG #include "Python.h" #endif #include "Track.h" #include "Track3D.h" #include "Geometry.h" #include "Quadrature.h" /* Forward declaration of TrackGenerator */ class TrackGenerator; /* Forward declaration of CPUSolver */ class CPUSolver; /** * @class MOCKernel MOCKernel.h "src/MOCKernel.h" * @brief An MOCKernel object specifies a functionality to apply to MOC * segments. * @details An MOCKernel is an object that owns some specified data and * contains an "execute" function which applies some functionality * to the data. This is useful in MOC where it is very common to * apply some function to segment data in either a nested loop * structure or from on-the-fly calculations. Kernels specify the * actions applied to the segments, reducing the need for repeated * code. This class is the parent class of CounterKernel, * VolumeKernel, and SegmentationKernel. A generic MOCKernel should * not be explicity instantiated. Instead, an inhereting class should * be instantiated which describes the "execute" function. */ class MOCKernel { protected: /** Count referring to the segment number */ int _count; /** Maximum optical path length when forming segments */ FP_PRECISION _max_tau; /** Number of energy groups in the current problem */ int _num_groups; public: MOCKernel(TrackGenerator* track_generator); virtual ~MOCKernel(); /* Function to get the current segment count */ int getCount(); /* Sets the max optical path length to a different value */ void setMaxOpticalLength(FP_PRECISION max_tau); /* Prepare MOCKernel for handling a new track */ virtual void newTrack(Track* track); /* Executing function describes kernel behavior */ virtual void execute(FP_PRECISION length, Material* mat, long fsr_id, int track_idx, int cmfd_surface_fwd, int cmfd_surface_bwd, FP_PRECISION x_start, FP_PRECISION y_start, FP_PRECISION z_start, FP_PRECISION phi, FP_PRECISION theta)=0; }; /** * @class CounterKernel MOCKernel.h "src/MOCKernel.h" * @brief Counts the number of segments of a track * @details A CounterKernel inherets from MOCKernel and is a kernel which * counts the number of segments in a track by incrementing the * _count variable by the number of legitimate segment lengths * (less than the max optical path length) in the input length. */ class CounterKernel: public MOCKernel { public: CounterKernel(TrackGenerator* track_generator); void execute(FP_PRECISION length, Material* mat, long fsr_id, int track_idx, int cmfd_surface_fwd, int cmfd_surface_bwd, FP_PRECISION x_start, FP_PRECISION y_start, FP_PRECISION z_start, FP_PRECISION phi, FP_PRECISION theta); }; /** * @class VolumeKernel MOCKernel.h "src/MOCKernel.h" * @brief Calculates the volume in FSRs by adding weighted segment lengths * @details A VolumeKernel inherets from MOCKernel and is a kernel which * is initialized with a pointer to floating point data and adds * the product of the length and the weight to the floating point data * at an input index. The weight corresponds to the weight of the * track associated with the segments. */ class VolumeKernel: public MOCKernel { private: /** Array of FSR locks */ omp_lock_t* _FSR_locks; /** Pointer to array of FSR volumes */ FP_PRECISION* _FSR_volumes; /** The Track's volume weight */ FP_PRECISION _weight; /** The associated quadrature from which weights are derived */ Quadrature* _quadrature; public: VolumeKernel(TrackGenerator* track_generator); void newTrack(Track* track); void execute(FP_PRECISION length, Material* mat, long fsr_id, int track_idx, int cmfd_surface_fwd, int cmfd_surface_bwd, FP_PRECISION x_start, FP_PRECISION y_start, FP_PRECISION z_start, FP_PRECISION phi, FP_PRECISION theta); }; /** * @class SegmentationKernel MOCKernel.h "src/MOCKernel.h" * @brief Forms segment data associated with a 3D track * @details A SegmentationKernel inherets from MOCKernel and is a kernel which * is initialized with a pointer to segment data. Input data of the * "execute" function is saved to the segment data, forming explicit * segments. */ class SegmentationKernel: public MOCKernel { private: /** Pointer to segment data */ segment* _segments; public: SegmentationKernel(TrackGenerator* track_generator); void execute(FP_PRECISION length, Material* mat, long fsr_id, int track_idx, int cmfd_surface_fwd, int cmfd_surface_bwd, FP_PRECISION x_start, FP_PRECISION y_start, FP_PRECISION z_start, FP_PRECISION phi, FP_PRECISION theta); }; /** * @class TransportKernel MOCKernel.h "src/MOCKernel.h" * @brief Applies transport equations to segment data * @details A TransportKernel inherets from MOCKernel and is a kernel which * is initialized with a pointer to a CPU Solver. Input data of the * "execute" function is used to apply the MOC equations in CPUSolver. */ class TransportKernel: public MOCKernel { private: /** Pointer to CPUSolver enabling use of transport functions */ CPUSolver* _cpu_solver; /** Pointer to TrackGenerator enabling use of ray tracer on the fly */ TrackGenerator* _track_generator; /** Pointer to angular flux data in the current direction */ FP_PRECISION* _thread_fsr_flux; /** Azimuthal index of the current track */ int _azim_index; /** XY index of the current track within tracks of that azimuthal angle */ int _xy_index; /** Polar index of the current track */ int _polar_index; /** Unique ID of the current track */ int _track_id; /** Direction of the current track (true = Forward / false = Backward) */ bool _direction; int _min_track_idx; int _max_track_idx; public: TransportKernel(TrackGenerator* track_generator); virtual ~TransportKernel(); void newTrack(Track* track); void setCPUSolver(CPUSolver* cpu_solver); void setTrackFlux(FP_PRECISION* fwd_flux, FP_PRECISION* bwd_flux, int track_id); void setTrackIndexes(int azim_index, int polar_index); void setDirection(bool direction); bool getDirection(); void execute(FP_PRECISION length, Material* mat, long fsr_id, int track_idx, int cmfd_surface_fwd, int cmfd_surface_bwd, FP_PRECISION x_start, FP_PRECISION y_start, FP_PRECISION z_start, FP_PRECISION phi, FP_PRECISION theta); void post(); }; #endif /* MOCKERNEL_H_ */
AI-Pranto/OpenMOC
src/accel/DeviceTrack.h
/** * @file DeviceTrack.h * @brief Structures for Tracks and Track segments on a GPU. * @date June 29, 2012 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef DEVICETRACK_H_ #define DEVICETRACK_H_ #ifdef __cplusplus #include "../Track.h" #endif /** * @struct dev_segment * @brief A dev_segment represents a line segment within a single flat source * region along a track. * @details The dev_segment is intended for use on the GPU. */ struct dev_segment { /** The length of the segment (cm) */ FP_PRECISION _length; /** An index into the _materials array that contains Material pointers */ int _material_index; /** The ID for flat source region in which this segment resides */ int _region_uid; }; /** * @struct dev_track * @brief A dev_track represents a characteristic line across the geometry. * @details A dev_track has particular starting and ending points on the * boundaries of the geometry and an azimuthal angle. The dev_track * is intended for use on the GPU. */ struct dev_track { /** A monotonically increasing unique ID for each Track created */ int _uid; /** The azimuthal angle index into the global 2D ragged array of Tracks */ int _azim_angle_index; /** A vector of segments making up this track */ dev_segment* _segments; /** The number of segments making up this Track */ int _num_segments; /** Index of the next Track when traveling along this Track in the "forward" * direction. */ long _next_track_fwd; /** Index of the next Track when traveling along this Track in the "reverse" * direction. */ long _next_track_bwd; /** A boolean to indicate whether to give the flux to the "forward" (true) * or "backward" (false) direction of the next Track going in the "forward" * direction. */ bool _next_fwd_is_fwd; /** A boolean to indicate whether to give the flux to the "forward" (true) * or "reverse" (false) direction of the next Track going in the "reverse" * direction. */ bool _next_bwd_is_fwd; /** A boolean to indicate whether the outgoing angular flux along this * Track's "forward" direction should be transferred to the outgoing * Track. */ bool _transfer_flux_fwd; /** A boolean to indicate whether the outgoing angular flux along this * Track's "reverse" direction should be transferred to the incoming * Track. */ bool _transfer_flux_bwd; }; #endif /* DEVICETRACK_H_ */
AI-Pranto/OpenMOC
src/TrackTraversingAlgorithms.h
<filename>src/TrackTraversingAlgorithms.h /** * @file TrackTraversingAlgorithms.h * @brief Contains classes which extend the TraverseSegments class to apply * algorithms to Tracks and possibly their segments. * @details The classes defined within this file extend the TraverseSegments * class so that they are capable of using the abstract looping * defined in TraverseSegments::loopOverTracks(...). Each class * contains a constructor which pulls data from a provided * TrackGenerator, an onTrack(...) function which specifies what to do * on each Track, and an execute() function which applies the * algorithm. The execute() function should contain a call to * TraverseSegments::loopOverTracks(...). To specify a behavior to * be applied once for each segment, the kernel should be initialized * using the TraverseSegments::getKernel<KernelType>() function and * passed to TraverseSegments::loopOverTracks(). * @date February 23, 2016 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef TRACK_TRAVERSING_ALGORITHMS_H_ #define TRACK_TRAVERSING_ALGORITHMS_H_ #include "TraverseSegments.h" #include "ExpEvaluator.h" /** Optimization macro to help vectorize computing the LS source contants */ #ifdef THREED #define _NUM_COEFFS 6 #endif /** Forward declaration of CPUSolver class */ class CPUSolver; class CPULSSolver; /** * @class MaxOpticalLength TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to calculate the maximum optical path length across * all segments in the Geometry. * @details A MaxOpticalLength allocates SegmentationKernels to temporarily * store segment data. The segments are then traversed afterwards and * the maximum optical path length is calculated. */ class MaxOpticalLength: public TraverseSegments { private: FP_PRECISION _min_tau; FP_PRECISION _max_tau; public: MaxOpticalLength(TrackGenerator* track_generator); void execute(); void onTrack(Track* track, segment* segments); }; /** * @class SegmentCounter TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to count the number of segments on each Track and the * maximum number of segments per Track. * @details A SegmentCounter allocates CounterKernels to count segments along * each Track given a maximum optical path length imported from the * provided TrackGenerator and the maximum number of segments per * Track in the TrackGenerator is updated. */ class SegmentCounter: public TraverseSegments { private: int _max_num_segments; long _total_num_segments; bool _count_total_segments; bool _total_segments_counted; public: SegmentCounter(TrackGenerator* track_generator); void execute(); void onTrack(Track* track, segment* segments); void countTotalNumSegments(); long getTotalNumSegments(); }; /** * @class SegmentSplitter TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to split explicit segments along Tracks. * @details A SegmentSplitter imports a maximum optical path length from the * provided TrackGenerator and then ensures all segments have an * optical path length less than the maximum optical path length by * splitting segments stored in the Tracks. */ class SegmentSplitter: public TraverseSegments { public: SegmentSplitter(TrackGenerator* track_generator); void execute(); void onTrack(Track* track, segment* segments); }; /** * @class VolumeCalculator TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to calculate FSR volumes. * @details A VolumeCalculator imports a buffer to store FSR volumes from the * provided TrackGenerator and the allocates VolumeKernels to * calculate and update the volumes in each FSR, implicitly writing * the calculated volumes back to the TrackGenerator. */ class VolumeCalculator: public TraverseSegments { public: VolumeCalculator(TrackGenerator* track_generator); void execute(); void onTrack(Track* track, segment* segments); }; /** * @class CentroidGenerator TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to calculate the centroids of each FSR. * @details A CentroidGenerator imports FSR Volumes and associated locks form * the provided TrackGenerator, then centroids are calculated and * stored in the provided buffer by first allocating * SegmentationKernels to temporarily store segments and then looping * over all segments and adding their contribution to each FSR * centroid. */ class CentroidGenerator: public TraverseSegments { private: Point** _centroids; FP_PRECISION* _FSR_volumes; omp_lock_t* _FSR_locks; Quadrature* _quadrature; Point** _starting_points; public: CentroidGenerator(TrackGenerator* track_generator); virtual ~CentroidGenerator(); void setCentroids(Point** centroids); void execute(); void onTrack(Track* track, segment* segments); }; /** * @class LinearExpansionGenerator TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to calculate the linear expansion coeffs of each FSR. * @details A LinearExpansionGenerator loops through all tracks and computes : * a linear source term that is constant through all iterations, matrix * coefficients in each FSR that help compute the linear source. */ //TODO Improve class LinearExpansionGenerator: public TraverseSegments { private: double* _lin_exp_coeffs; FP_PRECISION* _FSR_volumes; omp_lock_t* _FSR_locks; double* _src_constants; Quadrature* _quadrature; CPULSSolver* _solver; int _num_groups; #ifndef THREED int _NUM_COEFFS; #endif int _num_flat; Point** _starting_points; double** _thread_source_constants; ExpEvaluator* _exp_evaluator; Progress* _progress; public: LinearExpansionGenerator(CPULSSolver* solver); virtual ~LinearExpansionGenerator(); void execute(); void onTrack(Track* track, segment* segments); }; /** * @class TransportSweep TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to apply the MOC transport equations to all segments. * @details TransportSweep imports data from the provided TrackGenerator and * using a provided CPUSolver, it applies the MOC equations to each * segment, tallying the contributions to each FSR. At the end of each * Track, boundary fluxes are exchanged based on boundary conditions. */ class TransportSweep: public TraverseSegments { private: CPUSolver* _cpu_solver; CPULSSolver* _ls_solver; Geometry* _geometry; int _num_groups; FP_PRECISION** _thread_fsr_fluxes; FP_PRECISION** _thread_scratch_pads; public: TransportSweep(CPUSolver* cpu_solver); virtual ~TransportSweep(); void execute(); void onTrack(Track* track, segment* segments); }; /** * @class DumpSegments TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to write tracking data to a file. * @details DumpSegments imports Track data from the provided TrackGenerator * and writes the tracking data to the provided file. */ class DumpSegments: public TraverseSegments { private: FILE* _out; public: DumpSegments(TrackGenerator* track_generator); void setOutputFile(FILE* out); void execute(); void onTrack(Track* track, segment* segments); }; /** * @class ReadSegments TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to read tracking data from a file. * @details ReadSegments imports Track data from the provided file and writes * the tracking data to the Tracks in the provided TrackGenerator. */ class ReadSegments: public TraverseSegments { private: FILE* _in; public: ReadSegments(TrackGenerator* track_generator); void setInputFile(FILE* input); void execute(); void onTrack(Track* track, segment* segments); }; /** * @class TransportSweepOTF TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to ray trace and apply the MOC transport equations * simultaneously On-The-Fly. * @details TransportSweepOTF uses a track generator and a CPUSolver to solve * the ray-trace and solve the MOC equations at the same time. * NOT FULLY IMPLEMENTED //TODO */ class TransportSweepOTF: public TraverseSegments { private: CPUSolver* _cpu_solver; public: TransportSweepOTF(TrackGenerator* track_generator); void setCPUSolver(CPUSolver* cpu_solver); void onTrack(Track* track, segment* segments); void execute(); }; /** * @class RecenterSegments TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to recenter Segments once their related FSR centroid is * known. * @details RecenterSegments imports Track data from the provided TrackGenerator * and loops through segments to re-center them once their FSR centroid * has been computed. This is important to use the linear source with * explicit ray tracing. */ class RecenterSegments: public TraverseSegments { private: Geometry* _geometry; public: RecenterSegments(TrackGenerator* track_generator); void onTrack(Track* track, segment* segments); void execute(); }; /** * @class PrintSegments TrackTraversingAlgorithms.h * "src/TrackTraversingAlgorithms.h" * @brief A class used to write tracking data to a file. * @details PrintSegments imports Track data from the provided TrackGenerator * and writes the tracking data to the provided file. */ class PrintSegments: public TraverseSegments { private: FILE* _out; public: PrintSegments(TrackGenerator* track_generator); void setOutputFile(FILE* out); void execute(); void onTrack(Track* track, segment* segments); }; #endif
AI-Pranto/OpenMOC
src/constants.h
<reponame>AI-Pranto/OpenMOC /** * @file constants.h * @brief Math constants and comparision tolerances. * @date April 9, 2015. * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef CONSTANTS_H_ #define CONSTANTS_H_ /** Threshold to determine if a float equals to 0.0 */ #define FLT_EPSILON 1.0E-12 /** Threshold to determine if a flux is equal to 0.0 */ #define FLUX_EPSILON FP_PRECISION(1.0E-25) /** Threshold to determine if a float is equal to infinity */ #define FLT_INFINITY 1.0E300 /* The single line width permissible for timer / memory logger reports */ #define REPORT_WIDTH 53 /** The minimum auto ID used for Surfaces, Cells, Materials and Universes */ #define DEFAULT_INIT_ID 1000000 /** The value of 4pi: \f$ 4\pi \f$ */ #define FOUR_PI 12.566370614359172 /** The values of 1 divided by 4pi: \f$ \frac{1}{4\pi} \f$ */ #define ONE_OVER_FOUR_PI 0.07957747154594767 /** A negligible cross-section value to over-ride user-defined * cross-sections very near zero (e.g., within (-1E-10, 1E-10)) */ #define ZERO_SIGMA_T 1E-6 /** Threshold to determine how close the sum of \f$ \Sigma_a \f$ and * \f$ \Sigma_s \f$ must match \f$ \Sigma_t \f$ for each energy group */ #define SIGMA_T_THRESH 1E-10 /** Distance a Point is moved to cross over a Surface into a new Cell */ #define TINY_MOVE 1E-8 /** Threshold to determine if a Point is on the boundary of a Lattice cell */ #define ON_LATTICE_CELL_THRESH 1E-12 /** Error threshold to determine if a point is to be considered on a Surface */ #define ON_SURFACE_THRESH 1E-12 /** Tolerance for difference of the sum of polar weights with respect to 1.0 */ #define POLAR_WEIGHT_SUM_TOL 1E-5 /** The default maximum optical path length */ #define MAX_OPTICAL_LENGTH FP_PRECISION(100.) /** A small amount to increment the tau, the max optical path length, to ensure * that tracks with the max optical path length are not split. */ #define TAU_NUDGE 1E-12 /** The minimum acceptable precision for exponential evaluations from * the ExpEvaluator's linear interpolation table. This default precision * was selected based on analysis by Yamamoto's 2004 paper on the topic. */ #define EXP_PRECISION FP_PRECISION(1E-5) /** The minimum number of interpolation points to be used in an exponential * lookup table */ #define MIN_EXP_INTERP_POINTS 100 /** The minimum calculated determinant to allow for the calculation of a matrix * inverse. */ #define MIN_DET 1E-10 /** The maximum number of iterations allowed for a power method eigenvalue * solve in linalg.cpp */ #define MIN_LINALG_POWER_ITERATIONS 25 #define MAX_LINALG_POWER_ITERATIONS 25000 #define MIN_LINALG_TOLERANCE LINALG_TOL /** The maximum number of iterations allowed for a linear solve in linalg.cpp */ #define MIN_LINEAR_SOLVE_ITERATIONS 25 #define MAX_LINEAR_SOLVE_ITERATIONS 10000 #ifdef MPIx //TODO Make tracks per buffer dependent on number of processes, and groups #define TRACKS_PER_BUFFER 2000 #define CMFD_BUFFER_SIZE 10000 #endif #define LOCAL_COORDS_LEN 16 #define MAX_VERSION_NUM 50 /** The faces, edges, and vertices that collectively make up the surfaces of a * rectangular prism. The edges denoted as "e" and vertices as "v" on the * illustration below: * * e * v +--------------------+ v * /| /| * / | / | * / | / | * e/ e| /e |e * / | / | * / | e / | * / v +-------------/------+ v * v +--------------------+ v / * | / | / * | / | / * e| e/ |e e/ * | / | / * | / | / * |/ |/ * v +--------------------+ v * e * */ #define NUM_FACES 6 #define NUM_EDGES 12 #define NUM_VERTICES 8 #define NUM_SURFACES 26 #define SURFACE_X_MIN 0 #define SURFACE_Y_MIN 1 #define SURFACE_Z_MIN 2 #define SURFACE_X_MAX 3 #define SURFACE_Y_MAX 4 #define SURFACE_Z_MAX 5 #define SURFACE_X_MIN_Y_MIN 6 #define SURFACE_X_MAX_Y_MIN 7 #define SURFACE_X_MIN_Y_MAX 8 #define SURFACE_X_MAX_Y_MAX 9 #define SURFACE_X_MIN_Z_MIN 10 #define SURFACE_X_MAX_Z_MIN 11 #define SURFACE_X_MIN_Z_MAX 12 #define SURFACE_X_MAX_Z_MAX 13 #define SURFACE_Y_MIN_Z_MIN 14 #define SURFACE_Y_MAX_Z_MIN 15 #define SURFACE_Y_MIN_Z_MAX 16 #define SURFACE_Y_MAX_Z_MAX 17 #define SURFACE_X_MIN_Y_MIN_Z_MIN 18 #define SURFACE_X_MIN_Y_MIN_Z_MAX 19 #define SURFACE_X_MIN_Y_MAX_Z_MIN 20 #define SURFACE_X_MIN_Y_MAX_Z_MAX 21 #define SURFACE_X_MAX_Y_MIN_Z_MIN 22 #define SURFACE_X_MAX_Y_MIN_Z_MAX 23 #define SURFACE_X_MAX_Y_MAX_Z_MIN 24 #define SURFACE_X_MAX_Y_MAX_Z_MAX 25 /** The number of values used in representing a Track when the Tracks are * retrieved from the TrackGenerator. */ #define NUM_VALUES_PER_RETRIEVED_TRACK 6 /** The number of values used in representing a Segment when the Segments are * retrieved from the TrackGenerator. */ #define NUM_VALUES_PER_RETRIEVED_SEGMENT 7 /** Least common multiple tolerance */ #define LCM_TOLERANCE 1.e-8 #ifdef NVCC /** The maximum number of polar angles to reserve constant memory on GPU */ #define MAX_POLAR_ANGLES_GPU 10 /** The maximum number of azimuthal angles to reserve constant memory on GPU */ #define MAX_AZIM_ANGLES_GPU 256 #endif #endif /* CONSTANTS_H_ */
AI-Pranto/OpenMOC
src/Vector.h
<reponame>AI-Pranto/OpenMOC /** * @file Vector.h * @brief A vector object * @date May 5, 2015 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef SRC_VECTOR_H_ #define SRC_VECTOR_H_ #ifdef __cplusplus #include <math.h> #include <stdlib.h> #include <stdio.h> #include <map> #include <vector> #include <string> #include <iostream> #include <sstream> #include <iomanip> #include "log.h" #include "pairwise_sum.h" #endif class Vector { private: /** A list of lists representing the vector */ CMFD_PRECISION* _array; int _num_rows; int _num_x; int _num_y; int _num_z; int _num_groups; /** OpenMP mutual exclusion locks for atomic cell updates */ omp_lock_t* _cell_locks; void setNumX(int num_x); void setNumY(int num_y); void setNumZ(int num_z); void setNumGroups(int num_groups); public: Vector(omp_lock_t* cell_locks, int num_x = 1, int num_y = 1, int num_z = 1, int num_groups = 1); virtual ~Vector(); /* Worker functions */ void incrementValue(int cell, int group, CMFD_PRECISION val); void incrementValues(int cell, int group_start, int group_end, CMFD_PRECISION* vals); void clear(); void scaleByValue(CMFD_PRECISION val); void printString(); void copyTo(Vector* vector); /* Getter functions */ CMFD_PRECISION* getArray(); int getNumX(); int getNumY(); int getNumZ(); int getNumGroups(); int getNumRows(); double getSum(); long getNumNegativeValues(); omp_lock_t* getCellLocks(); /* Setter functions */ void setValue(int cell, int group, CMFD_PRECISION val); void setValues(int cell, int group_start, int group_end, CMFD_PRECISION* vals); void setAll(CMFD_PRECISION val); /** * @brief Get a value at location described by a given cell and group index. * @param cell The cell location index. * @param group The group location index. */ inline CMFD_PRECISION getValue(int cell, int group) { return _array[cell*_num_groups + group]; } }; #endif // SRC_VECTOR_H_
AI-Pranto/OpenMOC
src/ExpEvaluator.h
/** * @file ExpEvaluator.h * @brief The ExpEvaluator class. * @date April 9, 2015. * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef EXPEVALUATOR_H_ #define EXPEVALUATOR_H_ #ifdef __cplusplus #define _USE_MATH_DEFINES #include "log.h" #include "Quadrature.h" #include <malloc.h> #include <math.h> #include "exponentials.h" #endif /** * @class ExpEvaluator ExpEvaluator.h "src/ExpEvaluator.h" * @brief This is a class for evaluating exponentials. * @details The ExpEvaluator includes different algorithms to evaluate * exponentials with varying degrees of accuracy and speed. This is a * helper class for the Solver and its subclasses and it is not * intended to be initialized as a standalone object. */ class ExpEvaluator { private: /** A boolean indicating whether or not to use linear interpolation */ bool _interpolate; /** A boolean indicating whether or not linear source is being used */ bool _linear_source; /** The spacing for the exponential linear interpolation table */ FP_PRECISION _exp_table_spacing; /** The inverse spacing for the exponential linear interpolation table */ FP_PRECISION _inverse_exp_table_spacing; /** The sine of the base polar angle */ FP_PRECISION _sin_theta_no_offset; /** The inverse of the sine of the base polar angle */ FP_PRECISION _inverse_sin_theta_no_offset; /** The number of entries in the exponential linear interpolation table */ int _table_size; /** The exponential linear interpolation table */ FP_PRECISION* _exp_table; /** The PolarQuad object of interest */ Quadrature* _quadrature; /** The maximum optical length a track is allowed to have */ FP_PRECISION _max_optical_length; /** The maximum acceptable approximation error for exponentials */ FP_PRECISION _exp_precision; /** The azimuthal angle index used by this exponential evaluator */ int _azim_index; /** The base polar angle index used by this exponential evaluator */ int _polar_index; /** The number of exponential terms per optical length in the table */ int _num_exp_terms; /** The number of polar angles handled in the exponential table */ int _num_polar_terms; public: ExpEvaluator(); virtual ~ExpEvaluator(); void setQuadrature(Quadrature* quadrature); void setMaxOpticalLength(FP_PRECISION max_optical_length); void setExpPrecision(FP_PRECISION exp_precision); void useInterpolation(); void useIntrinsic(); void useLinearSource(); FP_PRECISION getMaxOpticalLength(); FP_PRECISION getExpPrecision(); bool isUsingInterpolation(); FP_PRECISION getTableSpacing(); int getTableSize(); FP_PRECISION* getExpTable(); int getExponentialIndex(FP_PRECISION tau); FP_PRECISION getDifference(int index, FP_PRECISION tau); FP_PRECISION convertDistance3Dto2D(FP_PRECISION length); FP_PRECISION getInverseSinTheta(); void initialize(int azim_index, int polar_index, bool solve_3D); FP_PRECISION computeExponential(FP_PRECISION tau, int polar_offset); FP_PRECISION computeExponentialF1(int index, int polar_offset, FP_PRECISION dt, FP_PRECISION dt2); FP_PRECISION computeExponentialF2(int index, int polar_offset, FP_PRECISION dt, FP_PRECISION dt2); FP_PRECISION computeExponentialH(int index, int polar_offset, FP_PRECISION dt, FP_PRECISION dt2); void retrieveExponentialComponents(FP_PRECISION tau, int polar_offset, FP_PRECISION* exp_F1, FP_PRECISION* exp_F2, FP_PRECISION* exp_H); FP_PRECISION computeExponentialG2(FP_PRECISION tau); ExpEvaluator* deepCopy(); }; /** * @brief Get the index on the exponential interpolation grid of the value right * beneath tau. * @param tau optical distance * @return the index on the exponential interpolation grid */ inline int ExpEvaluator::getExponentialIndex(FP_PRECISION tau) { return int(tau * _inverse_exp_table_spacing); } /** * @brief Compute the difference between an optical path and an indexed value in * the exponential interpolation grid. * @param index index on the exponential interpolation grid * @param tau optical distance * @return the difference between tau and the value on the grid */ inline FP_PRECISION ExpEvaluator::getDifference(int index, FP_PRECISION tau) { return tau - index * _exp_table_spacing; } /** * @brief Convert a 3D distance to a 2D based on the evaluator's polar angle. * @param length the 3D distance * @return the 2D distance */ inline FP_PRECISION ExpEvaluator::convertDistance3Dto2D(FP_PRECISION length) { return length * _sin_theta_no_offset; } /** * @brief Get the inverse of sin theta from the ExpEvaluator * @return inverse sin theta for the first angle */ inline FP_PRECISION ExpEvaluator::getInverseSinTheta() { return _inverse_sin_theta_no_offset; } /** * @brief Computes the F1 exponential term. * @param tau the optical distance (2D) * @param polar_offset an offset to the index in the look-up table * @return the F1 exponential term */ inline FP_PRECISION ExpEvaluator::computeExponential(FP_PRECISION tau, int polar_offset) { #ifndef THREED FP_PRECISION inv_sin_theta = _quadrature->getInvSinThetaInline(_azim_index, _polar_index + polar_offset); #else FP_PRECISION inv_sin_theta = _inverse_sin_theta_no_offset; #endif FP_PRECISION exp_F1; expF1_fractional(tau * inv_sin_theta, &exp_F1); return inv_sin_theta * exp_F1; } /** * @brief Computes the F1 exponential term. * @details This method computes F1 exponential from Ferrer [1] given * an index into the exponential look-up table, the distance (in units * of optical length) from the corresponding table value and the * requested tau, and that distance squared. This method uses either a * linear interpolation table (default) or the exponential intrinsic * exp(...) function. //DEPRECATED * * [1] <NAME> and <NAME> III, "A Linear Source Approximation * Scheme for the Method of Characteristics", Nuclear Science and * Engineering, Volume 182, February 2016. * * @param index the index into the exponential look-up table * @param polar_offset an offset to the index in the look-up table * @param dt the distance to the corresponding look-up table bin * @param dt2 the distance to the corresponding look-up table bin squared * @return the evaluated F1 exponential term */ inline FP_PRECISION ExpEvaluator::computeExponentialF1(int index, int polar_offset, FP_PRECISION dt, FP_PRECISION dt2) { /* Calculate full index */ int full_index = (index * _num_polar_terms + polar_offset) * _num_exp_terms; if (_interpolate) { return _exp_table[full_index] + _exp_table[full_index + 1] * dt + _exp_table[full_index + 2] * dt2; } else { int polar_index = _polar_index + polar_offset; FP_PRECISION tau = index * _exp_table_spacing + dt; FP_PRECISION inv_sin_theta = 1.0 / _quadrature->getSinTheta(_azim_index, polar_index); return (1.0 - exp(- tau * inv_sin_theta)) / tau; } } /** * @brief Computes the F2 exponential term. * @details This method computes F2 exponential from Ferrer [1] given * an index into the exponential look-up table, the distance (in units * of optical length) from the corresponding table value and the * requested tau, and that distance squared. This method uses either a * linear interpolation table (default) or the exponential intrinsic * exp(...) function. //DEPRECATED * * [1] <NAME> and <NAME> III, "A Linear Source Approximation * Scheme for the Method of Characteristics", Nuclear Science and * Engineering, Volume 182, February 2016. * * @param index the index into the exponential look-up table * @param polar_offset an offset to the index in the look-up table * @param dt the distance to the corresponding look-up table bin * @param dt2 the distance to the corresponding look-up table bin squared * @return the evaluated F2 exponential term */ inline FP_PRECISION ExpEvaluator::computeExponentialF2(int index, int polar_offset, FP_PRECISION dt, FP_PRECISION dt2) { /* Calculate full index */ int full_index = (index * _num_polar_terms + polar_offset) * _num_exp_terms; if (_interpolate) return _exp_table[full_index + 3] + _exp_table[full_index + 4] * dt + _exp_table[full_index + 5] * dt2; else { int polar_index = _polar_index + polar_offset; FP_PRECISION tau = index * _exp_table_spacing + dt; FP_PRECISION inv_sin_theta = 1.0 / _quadrature->getSinTheta(_azim_index, polar_index); FP_PRECISION tau_m = tau * inv_sin_theta; FP_PRECISION F1 = (1.0 - exp(- tau_m)) / tau; return 2.0 / tau * (inv_sin_theta - F1) - inv_sin_theta * F1; } } /** * @brief Computes the H exponential term. * @details This method computes H exponential from Ferrer [1] given * an index into the exponential look-up table, the distance (in units * of optical length) from the corresponding table value and the * requested tau, and that distance squared. This method uses either a * linear interpolation table (default) or the exponential intrinsic * exp(...) function. //DEPRECATED * * [1] <NAME> and <NAME> III, "A Linear Source Approximation * Scheme for the Method of Characteristics", Nuclear Science and * Engineering, Volume 182, February 2016. * * @param index the index into the exponential look-up table * @param polar_offset an offset to the index in the look-up table * @param dt the distance to the corresponding look-up table bin * @param dt2 the distance to the corresponding look-up table bin squared * @return the evaluated H exponential term */ inline FP_PRECISION ExpEvaluator::computeExponentialH(int index, int polar_offset, FP_PRECISION dt, FP_PRECISION dt2) { /* Calculate full index */ int full_index = (index * _num_polar_terms + polar_offset) * _num_exp_terms; if (_interpolate) return _exp_table[full_index + 6] + _exp_table[full_index + 7] * dt + _exp_table[full_index + 8] * dt2; else { int polar_index = _polar_index + polar_offset; FP_PRECISION tau = index * _exp_table_spacing + dt; FP_PRECISION inv_sin_theta = 1.0 / _quadrature->getSinTheta(_azim_index, polar_index); FP_PRECISION tau_m = tau * inv_sin_theta; FP_PRECISION F1 = (1.0 - exp(- tau_m)) / tau; FP_PRECISION G1 = 1.0 / tau + 0.5 * inv_sin_theta - (1.0 + 1.0 / tau_m) * F1; return 0.5 * inv_sin_theta - G1; } } /** * @brief Computes the G2 exponential term for a optical length and polar angle. * @details This method computes the G2 exponential term from Ferrer [1] * for some optical path length and polar angle. This method uses a * rational fraction approximation to compute the exponential term. * * [1] <NAME> and <NAME> III, "A Linear Source Approximation * Scheme for the Method of Characteristics", Nuclear Science and * Engineering, Volume 182, February 2016. * * @param tau the optical path length (e.g., sigma_t times length) * @return the evaluated exponential */ inline FP_PRECISION ExpEvaluator::computeExponentialG2(FP_PRECISION tau) { FP_PRECISION exp_G2; expG2_fractional(tau, &exp_G2); return exp_G2; } /** * @brief Computes the F1, F2, H exponential term. * @details This method computes F1, F2, H exponential from Ferrer [1] given the * requested tau. This method uses either a linear interpolation table * (default) or the exponential intrinsicexp(...) function. * * [1] <NAME> and <NAME> III, "A Linear Source Approximation * Scheme for the Method of Characteristics", Nuclear Science and * Engineering, Volume 182, February 2016. * * @param tau the requested tau * @param polar_offset an offset to the index in the look-up table * @param exp_F1 pointer to the F1 exponential term to be computed * @param exp_F2 pointer to the F2 exponential term to be computed * @param exp_H pointer to the H exponential term to be computed */ inline void ExpEvaluator::retrieveExponentialComponents(FP_PRECISION tau, int polar_offset, #ifdef SWIG //FIXME Find out how to use restrict with SWIG FP_PRECISION* exp_F1, FP_PRECISION* exp_F2, FP_PRECISION* exp_H) { #else FP_PRECISION* __restrict__ exp_F1, FP_PRECISION* __restrict__ exp_F2, FP_PRECISION* __restrict__ exp_H) { #endif #ifndef THREED FP_PRECISION inv_sin_theta = _quadrature->getInvSinThetaInline(_azim_index, _polar_index + polar_offset); #else FP_PRECISION inv_sin_theta = _inverse_sin_theta_no_offset; #endif /* Limit range of tau to avoid numerical errors */ tau = std::max(FP_PRECISION(1e-8), tau * inv_sin_theta); /* Compute exponentials from a common exponential */ FP_PRECISION exp_G; expG_fractional(tau, &exp_G); *exp_F1 = 1.f - tau*exp_G; *exp_F1 *= inv_sin_theta; exp_G *= inv_sin_theta; *exp_F2 = 2.f*exp_G - *exp_F1; *exp_H = *exp_F1 - exp_G; /* Quadratic exponential interpolation tables */ // __builtin_assume_aligned(_exp_table, VEC_ALIGNMENT); // // tau /= inv_sin_theta; // int exp_index = getExponentialIndex(tau); // FP_PRECISION dt = getDifference(exp_index, tau); // FP_PRECISION dt2 = dt * dt; // int full_index = (exp_index * _num_polar_terms + polar_offset) // * _num_exp_terms; // *exp_F1 = _exp_table[full_index] + _exp_table[full_index + 1] * dt + // _exp_table[full_index + 2] * dt2; // *exp_F2 = _exp_table[full_index + 3] + _exp_table[full_index + 4] * dt + // _exp_table[full_index + 5] * dt2; // *exp_H = _exp_table[full_index + 6] + _exp_table[full_index + 7] * dt + // _exp_table[full_index + 8] * dt2; } #endif /* EXPEVALUATOR_H_ */
AI-Pranto/OpenMOC
src/Progress.h
<gh_stars>10-100 /** * @file Progress.h * @brief An object to track progress * @date January 11, 2016 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef PROGRESS_H_ #define PROGRESS_H_ #ifdef __cplusplus #include <math.h> #include <map> #include <vector> #include <string> #include <iostream> #include <sstream> #include <stdlib.h> #include <stdio.h> #include <string> #include <iomanip> #include <omp.h> #include "log.h" #endif #ifdef MPIx #include <mpi.h> #endif class Geometry; class Progress { private: std::string _name; long _counter; long _num_iterations; int _curr_interval; std::vector<long> _intervals; Geometry* _geometry; bool _mpi_comm; public: Progress(long num_iterations, std::string name, double interval=0.1, Geometry* geometry=NULL, bool mpi_comm=false); virtual ~Progress(); /* Worker functions */ void incrementCounter(); void reset(); }; #endif /* PROGRESS_H_ */
AI-Pranto/OpenMOC
src/linalg.h
/** * @file linalg.h * @details This file contains a library of functions for performing linear * algebra operations. * @date July 3, 2015 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ /* File: linalg.h */ #ifndef LINALG_H_ #define LINALG_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "log.h" #include "Matrix.h" #include "Vector.h" #include "constants.h" #include <math.h> #include <vector> #include <omp.h> #endif /** * @brief Verbose iteration information for the CMFD eigenvalue solver */ struct ConvergenceData { /* The Max. prolongation factor of the CMFD */ double pf; /* The initial residual of the CMFD eigenvalue problem */ double cmfd_res_1; /* The final residual of the CMFD eigenvalue problem */ double cmfd_res_end; /* The linear solver residual of the first CMFD eigenvalue iteration */ double linear_res_1; /* The linear solver residual of the final CMFD eigenvalue iteration */ double linear_res_end; /* The number of the CMFD eigenvalue iterations */ int cmfd_iters; /* The number of linear iterations for the first CMFD eigenvalue iteration */ int linear_iters_1; /* The number of linear iterations for the final CMFD eigenvalue iteration */ int linear_iters_end; /* Constructor initializes convergence statistics to -1 */ ConvergenceData() { pf = -1; cmfd_res_1 = -1; cmfd_res_end = -1; linear_res_1 = -1; linear_res_end = -1; cmfd_iters = -1; linear_iters_1 = -1; linear_iters_end = -1; } }; /** * @brief Structure for communication of fluxes between neighbor domains */ struct DomainCommunicator { int _num_domains_x; int _num_domains_y; int _num_domains_z; int _domain_idx_x; int _domain_idx_y; int _domain_idx_z; int _local_num_x; int _local_num_y; int _local_num_z; /* Sum of the starting CMFD global indexes of a domain, for the color*/ int _offset; /* Number of connecting neighbors for each surface cell */ int** num_connections; /* Indexes of connecting neighbors for each surface cell */ int*** indexes; /* Surface numbers of connecting neighbors for each surface cell */ int*** domains; /* Coupling coeffs between connecting neighbors and itself for each surface cell */ CMFD_PRECISION*** coupling_coeffs; /* Fluxes of connecting neighbors for each surface cell*/ CMFD_PRECISION*** fluxes; /* Buffer for sending/receiving fluxes to/from connecting neighbors */ CMFD_PRECISION** buffer; /* Map to the index of the boundary elements */ std::map<int, int> mapLocalToSurface; int num_groups; bool stop; #ifdef MPIx MPI_Comm _MPI_cart; #endif }; /** * @brief Get coupling fluxes and other information from neighbors. * @details The information are transfered by reference. */ #ifdef MPIx void getCouplingTerms(DomainCommunicator* comm, int color, int*& coupling_sizes, int**& coupling_indexes, CMFD_PRECISION**& coupling_coeffs, CMFD_PRECISION**& coupling_fluxes, CMFD_PRECISION* curr_fluxes, int& offset); #endif double eigenvalueSolve(Matrix* A, Matrix* M, Vector* X, double k_eff, double tol, double SOR_factor=1.5, ConvergenceData* convergence_data = NULL, DomainCommunicator* comm = NULL); bool linearSolve(Matrix* A, Matrix* M, Vector* X, Vector* B, double tol, double SOR_factor=1.5, ConvergenceData* convergence_data = NULL, DomainCommunicator* comm = NULL); bool ddLinearSolve(Matrix* A, Matrix* M, Vector* X, Vector* B, double tol, double SOR_factor, ConvergenceData* convergence_data, DomainCommunicator* comm); void matrixMultiplication(Matrix* A, Vector* X, Vector* B); double computeRMSE(Vector* x, Vector* y, bool integrated, DomainCommunicator* comm = NULL); /** * @brief Transpose a 2D matrix. * @param matrix array to transpose * @param dim1 first dimension length * @param dim2 second dimension length */ template<typename T> inline void matrix_transpose(T* matrix, int dim1, int dim2) { std::vector<T> temp(dim1 * dim2); for (int i=0; i < dim1; i++) { for (int j=0; j < dim2; j++) temp[i * dim1 + j] = matrix[j * dim1 + i]; } std::copy(temp.begin(), temp.end(), matrix); } #endif /* LINALG_H_ */
AI-Pranto/OpenMOC
src/exponentials.h
<filename>src/exponentials.h /** * @file exponentials.h * @brief Math approximations for computing exponentials. * @date January 16, 2019 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef EXPONENTIALS_H_ #define EXPONENTIALS_H_ /** * @brief Computes the F1 exponential term. * @details This method computes (1-exp(-x))/x using a 7th order polynomial * approximation. It is accurate to 1e-5 over [0, 5]. It was generated * by <NAME> using Remez's algorithm. * @param x the value at which to evaluate the function, usually tau * @param expF1 a pointer to the exponential */ inline void expF1_poly(FP_PRECISION x, FP_PRECISION* expF1) { const FP_PRECISION p0 = 1.; const FP_PRECISION p1 = -4.998618823537523 * 1E-1; const FP_PRECISION p2 = 1.660264339632089 * 1E-1; const FP_PRECISION p3 = -4.0607961247327 * 1E-2; const FP_PRECISION p4 = 7.459558151235148 * 1E-3; const FP_PRECISION p5 = -9.773063624328772 * 1E-4; const FP_PRECISION p6 = 8.004982165323072 * 1E-5; const FP_PRECISION p7 = -3.016010858852142 * 1E-6; *expF1 = p7*x + p6; *expF1 = *expF1*x + p5; *expF1 = *expF1*x + p4; *expF1 = *expF1*x + p3; *expF1 = *expF1*x + p2; *expF1 = *expF1*x + p1; *expF1 = *expF1*x + p0; } /** * @brief Computes the F2 exponential term. * @details This method computes (x-2+exp(-x)*(2+x))/x**2 using a 8th order * polynomial approximation. It is accurate to 1e-5 over [0, 5]. It was * generated by <NAME> using Remez's algorithm. * @param x the value at which to evaluate the function, usually tau * @param expF2 a pointer to the exponential */ inline void expF2_poly(FP_PRECISION x, FP_PRECISION* expF2) { const FP_PRECISION p1 = 1.666656766985825 * 1E-1; const FP_PRECISION p2 = -8.331262914972137 * 1E-2; const FP_PRECISION p3 = 2.492325839109710 * 1E-2; const FP_PRECISION p4 = -5.440953156443790 * 1E-3; const FP_PRECISION p5 = 9.034802244154581 * 1E-4; const FP_PRECISION p6 = -1.091608727341864 * 1E-4; const FP_PRECISION p7 = 8.411465095972204 * 1E-6; const FP_PRECISION p8 = -3.029020287833148 * 1E-7; *expF2 = p8*x + p7; *expF2 = *expF2*x + p6; *expF2 = *expF2*x + p5; *expF2 = *expF2*x + p4; *expF2 = *expF2*x + p3; *expF2 = *expF2*x + p2; *expF2 = *expF2*x + p1; *expF2 = *expF2*x; } /** * @brief Computes the H exponential term. * @details This method computes (1-exp(-x)*(1+x))/x**2 using a 8th order * polynomial approximation. It is accurate to 1e-5 over [0, 5]. It was * generated by <NAME> using Remez's algorithm. * @param x the value at which to evaluate the function, usually tau * @param expH a pointer to the exponential */ inline void expH_poly(FP_PRECISION x, FP_PRECISION* expH) { const FP_PRECISION p0 = 0.5; const FP_PRECISION p1 = -3.33307480097059 * 1E-1; const FP_PRECISION p2 = 1.248597190564637 * 1E-1; const FP_PRECISION p3 = -3.305711771115656 * 1E-2; const FP_PRECISION p4 = 6.667701492411682 * 1E-3; const FP_PRECISION p5 = -1.028726890908856 * 1E-3; const FP_PRECISION p6 = 1.145870114989106 * 1E-4; const FP_PRECISION p7 = -8.079532805720403 * 1E-6; const FP_PRECISION p8 = 2.657707693467421 * 1E-7; *expH = p8*x + p7; *expH = *expH*x + p6; *expH = *expH*x + p5; *expH = *expH*x + p4; *expH = *expH*x + p3; *expH = *expH*x + p2; *expH = *expH*x + p1; *expH = *expH*x + p0; } /** * @brief Computes an exponential G term, used to reconstruct F1, F2 and H. * @details This method computes 1/x-(1-exp(-x))/x**2 using a 5/6th order * rational approximation. It is accurate to 2e-7 over [0, 1e5]. * However, accuracy when reconstructing F1, F2 and H is lower. * It was generated by <NAME> using Remez's algorithm. * @param x the value at which to evaluate the function, usually tau * @param expG a pointer to the exponential */ inline void expG_fractional(FP_PRECISION x, FP_PRECISION* expG) { /* Coefficients for numerator */ const FP_PRECISION p0 = 0.5; const FP_PRECISION p1 = 1.76558112351595 * 1E-1; const FP_PRECISION p2 = 4.041584305811143 * 1E-2; const FP_PRECISION p3 = 6.178333902037397 * 1E-3; const FP_PRECISION p4 = 6.429894635552992 * 1E-4; const FP_PRECISION p5 = 6.064409107557148 * 1E-5; /* Coefficients for denominator */ const FP_PRECISION d0 = 1.0; const FP_PRECISION d1 = 6.864462055546078 * 1E-1; const FP_PRECISION d2 = 2.263358514260129 * 1E-1; const FP_PRECISION d3 = 4.721469893686252 * 1E-2; const FP_PRECISION d4 = 6.883236664917246 * 1E-3; const FP_PRECISION d5 = 7.036272419147752 * 1E-4; const FP_PRECISION d6 = 6.064409107557148 * 1E-5; FP_PRECISION num, den; den = d6*x + d5; den = den*x + d4; den = den*x + d3; den = den*x + d2; den = den*x + d1; den = den*x + d0; den = 1.f/den; num = p5*x + p4; num = num*x + p3; num = num*x + p2; num = num*x + p1; num = num*x + p0; *expG = num*den; } /** * @brief Computes the F1 exponential term. * @details This method computes (1-exp(-x))/x using a 5/6th order * rational approximation. It is accurate to 2e-6 over [0, 1e5]. * It was generated by <NAME> using Remez's algorithm. * @param x the value at which to evaluate the function, usually tau * @param expF1 a pointer to the exponential */ inline void expF1_fractional(FP_PRECISION x, FP_PRECISION* expF1) { /* Coefficients for numerator */ const FP_PRECISION p0 = 1.0; const FP_PRECISION p1 = 2.4172687328033081 * 1E-1; const FP_PRECISION p2 = 6.2804790965268531 * 1E-2; const FP_PRECISION p3 = 1.0567595009016521 * 1E-2; const FP_PRECISION p4 = 1.0059468082903561 * 1E-3; const FP_PRECISION p5 = 1.9309063097411041 * 1E-4; /* Coefficients for denominator */ const FP_PRECISION d0 = 1.0; const FP_PRECISION d1 = 7.4169266112320541 * 1E-1; const FP_PRECISION d2 = 2.6722515319494311 * 1E-1; const FP_PRECISION d3 = 6.1643725066901411 * 1E-2; const FP_PRECISION d4 = 1.0590759992367811 * 1E-2; const FP_PRECISION d5 = 1.0057980007137651 * 1E-3; const FP_PRECISION d6 = 1.9309063097411041 * 1E-4; FP_PRECISION num, den; den = d6*x + d5; den = den*x + d4; den = den*x + d3; den = den*x + d2; den = den*x + d1; den = den*x + d0; den = 1.f / den; num = p5*x + p4; num = num*x + p3; num = num*x + p2; num = num*x + p1; num = num*x + p0; *expF1 = num*den; } /** * @brief Computes the F2 exponential term. * @details This method computes (x-2+exp(-x)*(2+x))/x**2 using a 5/6th order * rational approximation. It is accurate to 2e-6 over [0, 1e5]. * It was generated by <NAME> using Remez's algorithm. * @param x the value at which to evaluate the function, usually tau * @param expF2 a pointer to the exponential */ inline void expF2_fractional(FP_PRECISION x, FP_PRECISION* expF2) { /* Coefficients for numerator */ const FP_PRECISION p1 = 1.666661470036759 * 1E-1; const FP_PRECISION p2 = 3.59041632356318 * 1E-2; const FP_PRECISION p3 = 7.675127136944033 * 1E-3; const FP_PRECISION p4 = 6.408491755085618 * 1E-4; const FP_PRECISION p5 = 1.367575707015872 * 1E-4; /* Coefficients for denominator */ const FP_PRECISION d0 = 1.0; const FP_PRECISION d1 = 7.153333128932897 * 1E-1; const FP_PRECISION d2 = 2.541555663123697 * 1E-1; const FP_PRECISION d3 = 5.613392571426973 * 1E-2; const FP_PRECISION d4 = 9.476002327852898 * 1E-3; const FP_PRECISION d5 = 9.145637477815584 * 1E-4; const FP_PRECISION d6 = 1.367575707015872 * 1E-4; FP_PRECISION num, den; num = p5*x + p4; num = num*x + p3; num = num*x + p2; num = num*x + p1; num = num*x; den = d6*x + d5; den = den*x + d4; den = den*x + d3; den = den*x + d2; den = den*x + d1; den = den*x + d0; *expF2 = num/den; } /** * @brief Computes the H exponential term. * @details This method computes (1-exp(-x)*(1+x))/x**2 using a 5/7th order * rational approximation. It is accurate to 2e-6 over [0, 1e5]. * It was generated by <NAME> using Remez's algorithm. * @param x the value at which to evaluate the function, usually tau * @param expH a pointer to the exponential */ inline void expH_fractional(FP_PRECISION x, FP_PRECISION* expH) { /* Coefficients for numerator */ const FP_PRECISION p0 = 0.5; const FP_PRECISION p1 = 5.599412483229184 * 1E-2; const FP_PRECISION p2 = 1.294939509305754 * 1E-2; const FP_PRECISION p3 = 2.341166644220405 * 1E-3; const FP_PRECISION p4 = 3.686858969421769 * 1E-5; const FP_PRECISION p5 = 4.220477028150503 * 1E-5; /* Coefficients for denominator */ const FP_PRECISION d0 = 1.0; const FP_PRECISION d1 = 7.787274561075199 * 1E-1; const FP_PRECISION d2 = 2.945145030273455 * 1E-1; const FP_PRECISION d3 = 7.440380752801196 * 1E-2; const FP_PRECISION d4 = 1.220791761275212 * 1E-2; const FP_PRECISION d5 = 2.354181374425252 * 1E-3; const FP_PRECISION d6 = 3.679462493221416 * 1E-5; const FP_PRECISION d7 = 4.220477028150503 * 1E-5; FP_PRECISION num, den; num = p5*x + p4; num = num*x + p3; num = num*x + p2; num = num*x + p1; num = num*x + p0; den = d7*x + d6; den = den*x + d5; den = den*x + d4; den = den*x + d3; den = den*x + d2; den = den*x + d1; den = den*x + d0; *expH = num/den; } /** * @brief Computes the G2 exponential term. * @details This method computes 2/3 - (1 + 2/x) * (1/x + 0.5 - (1 + 1/x) * (1-exp(-x)) / x) using a 5/5th order * rational approximation. It is accurate to 1e-6 over [0, 1e6]. * It was generated by <NAME> using Remez's algorithm. * @param x the value at which to evaluate the function, usually tau * @param expG2 a pointer to the exponential */ inline void expG2_fractional(FP_PRECISION x, FP_PRECISION* expG2) { /* Coefficients for numerator */ const FP_PRECISION a1 = -8.335775885589858 * 1E-2; const FP_PRECISION a2 = -3.603942303847604 * 1E-3; const FP_PRECISION a3 = 3.7673183263550827 * 1E-3; const FP_PRECISION a4 = 1.124183494990467 * 1E-5; const FP_PRECISION a5 = 1.6837426505799449 * 1E-4; /* Coefficients for denominator */ const FP_PRECISION b1 = 7.454048371823628 * 1E-1; const FP_PRECISION b2 = 2.3794300531408347 * 1E-1; const FP_PRECISION b3= 5.367250964303789 * 1E-2; const FP_PRECISION b4 = 6.125197988351906 * 1E-3; const FP_PRECISION b5 = 1.0102514456857377 * 1E-3; FP_PRECISION num, den; num = a5 * x + a4; num = num * x + a3; num = num * x + a2; num = num * x + a1; num *= x; den = b5 * x + b4; den = den * x + b3; den = den * x + b2; den = den * x + b1; den = den * x + 1.f; *expG2 = num / den; } /** * @brief Evaluates the function 1 - exp(x) for x negative. Vectorises well. * Accurate to 6.18 digits (single precision) for entire domain (including * near zero, unlike intrinsic) * * Valid for x ~= [-1.5e6, 0] * @param x value at which to evaluate 1 - exp(x) * @param expv value of function */ inline void cram7(FP_PRECISION x, FP_PRECISION* expv) { /* Generated in Mathematica, accurate to 6.18 digits (single precision), tau [-1.5e6,0] */ const FP_PRECISION c1n = -1.00000014302666667201396424463; const FP_PRECISION c2n = 2.34841040052684510704433796447 * 1E-1; const FP_PRECISION c3n = -6.24785939603762121316592924635 * 1E-2; const FP_PRECISION c4n = 1.00434102711342948752684759736 * 1E-2; const FP_PRECISION c5n = -1.35724435934263932676353754751 * 1E-3; const FP_PRECISION c6n = 9.51474224366003625378414851577 * 1E-5; const FP_PRECISION c7n = -1.60076055315534285575266516209 * 1E-5; const FP_PRECISION c0d = 1.; const FP_PRECISION c1d = -7.34847118148952339633322706422 * 1E-1; const FP_PRECISION c2d = 2.63193362386411901729092564316 * 1E-1; const FP_PRECISION c3d = -6.09467155163113059870970359654 * 1E-2; const FP_PRECISION c4d = 1.00863490579686697359577926719 * 1E-2; const FP_PRECISION c5d = -1.35667018708833025497446407598 * 1E-3; const FP_PRECISION c6d = 9.51502816434275317085698085885 * 1E-5; const FP_PRECISION c7d = -1.60076032420105715765981718742 * 1E-5; FP_PRECISION num, den; den = c7d; den = den * x + c6d; den = den * x + c5d; den = den * x + c4d; den = den * x + c3d; den = den * x + c2d; den = den * x + c1d; den = den * x + c0d; num = c7n; num = num * x + c6n; num = num * x + c5n; num = num * x + c4n; num = num * x + c3n; num = num * x + c2n; num = num * x + c1n; num = num * x; *expv = num / den; } #endif // EXPONENTIALS_H_
AI-Pranto/OpenMOC
src/Universe.h
/** * @file Universe.h * @brief The Universe class. * @date January 9, 2012 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef UNIVERSE_H_ #define UNIVERSE_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "constants.h" #include "LocalCoords.h" #include "boundary_type.h" #include <limits> #include <map> #include <vector> #endif /* Forward declarations to resolve circular dependencies */ class LocalCoords; class Cell; class Surface; class Material; int universe_id(); void reset_universe_id(); void maximize_universe_id(int universe_id); /** * @enum universeType * @brief The type of universe. */ enum universeType{ /** A simple non-repeating Universe */ SIMPLE, /** A collection of Universes in a rectangular Lattice */ LATTICE }; /** * @class Universe Universe.h "src/Universe.h" * @brief A Universe represents an unbounded space in 3D. * @details A Universe contains cell which are bounded subspaces in 3D * which together form the Universe. Universes allow * for complex, repeating (i.e. lattices) geometries to be simply * represented with as few data structures as possible. */ class Universe { protected: /** A static counter for the number of Universes */ static int _n; /** A monotonically increasing unique ID for each Universe created */ int _uid; /** A user-defined id for each Universe created */ int _id; /** A user-defined name for the Surface */ char* _name; /** The type of Universe (ie, SIMPLE or LATTICE) */ universeType _type; /** A collection of Cell IDs and Cell pointers in this Universe */ std::map<int, Cell*> _cells; /** A boolean representing whether or not this Universe contains a Material * with a non-zero fission cross-section and is fissionable */ bool _fissionable; /** The extrema of the Universe */ double _min_x; double _max_x; double _min_y; double _max_y; double _min_z; double _max_z; /** A flag for determining if boundaries are up to date */ bool _boundaries_inspected; /** The boundaryTypes of the universe */ boundaryType _min_x_bound; boundaryType _max_x_bound; boundaryType _min_y_bound; boundaryType _max_y_bound; boundaryType _min_z_bound; boundaryType _max_z_bound; public: Universe(const int id=-1, const char* name=""); virtual ~Universe(); int getUid() const; int getId() const; char* getName() const; universeType getType(); int getNumCells() const; double getMinX(); double getMaxX(); double getMinY(); double getMaxY(); double getMinZ(); double getMaxZ(); boundaryType getMinXBoundaryType(); boundaryType getMaxXBoundaryType(); boundaryType getMinYBoundaryType(); boundaryType getMaxYBoundaryType(); boundaryType getMinZBoundaryType(); boundaryType getMaxZBoundaryType(); Cell* getCell(int cell_id); std::map<int, Cell*> getCells() const; std::map<int, Cell*> getAllCells(); std::map<int, Material*> getAllMaterials(); std::map<int, Universe*> getAllUniverses(); bool isFissionable(); void resetBoundaries(); void calculateBoundaries(); void setName(const char* name); void setType(universeType type); void addCell(Cell* cell); void removeCell(Cell* cell); bool containsPoint(Point* point); Cell* findCell(LocalCoords* coords); void setFissionability(bool fissionable); void subdivideCells(double max_radius=INFINITY); void buildNeighbors(); virtual std::string toString(); void printString(); Universe* clone(); }; /** * @class Lattice Universe.h "src/Universe.h" * @brief Represents a repeating 3D Lattice of Universes. */ class Lattice: public Universe { private: /** The number of Lattice cells along the x-axis */ int _num_x; /** The number of Lattice cells along the y-axis */ int _num_y; /** The number of Lattice cells along the z-axis */ int _num_z; /** True if the lattice is non-uniform */ bool _non_uniform; /** The width of each Lattice cell (cm) along the x-axis (uniform lattices only) */ double _width_x; /** x-direction dimensions of non-uniform lattice meshes */ std::vector<double> _widths_x; std::vector<double> _accumulate_x; /** The width of each Lattice cell (cm) along the y-axis (uniform lattices only) */ double _width_y; /** y-direction dimensions of non-uniform lattice meshes */ std::vector<double> _widths_y; std::vector<double> _accumulate_y; /** The width of each Lattice cell (cm) along the z-axis (uniform lattices only) */ double _width_z; /** z-direction dimensions of non-uniform lattice meshes */ std::vector<double> _widths_z; std::vector<double> _accumulate_z; /** The coordinates of the offset for the Universe */ Point _offset; /** A container of Universes */ std::vector< std::vector< std::vector< std::pair<int, Universe*> > > > _universes; public: Lattice(const int id=-1, const char* name=""); virtual ~Lattice(); void setOffset(double x, double y, double z=0.0); Point* getOffset(); int getNumX() const; int getNumY() const; int getNumZ() const; double getWidthX() const; double getWidthY() const; double getWidthZ() const; bool getNonUniform() const; const std::vector<double>& getWidthsX() const; const std::vector<double>& getWidthsY() const; const std::vector<double>& getWidthsZ() const; const std::vector<double>& getAccumulateX() const; const std::vector<double>& getAccumulateY() const; const std::vector<double>& getAccumulateZ() const; double getMinX(); double getMaxX(); double getMinY(); double getMaxY(); double getMinZ(); double getMaxZ(); Universe* getUniverse(int lat_x, int lat_y, int lat_z=0) const; std::vector< std::vector< std::vector< std::pair<int, Universe*> > > >* getUniverses(); std::map<int, Universe*> getUniqueUniverses(); std::map<int, double> getUniqueRadius(std::map<int, Universe*> unique_universes); std::map<int, Cell*> getAllCells(); std::map<int, Universe*> getAllUniverses(); void setNumX(int num_x); void setNumY(int num_y); void setNumZ(int num_z); void setWidth(double width_x, double width_y, double width_z=std::numeric_limits<double>::infinity()); void setNonUniform(bool non_uniform); void setWidthsX(std::vector<double> widthsx); void setWidthsY(std::vector<double> widthsy); void setWidthsZ(std::vector<double> widthsz); void setAccumulateX(std::vector<double> accumulatex); void setAccumulateY(std::vector<double> accumulatey); void setAccumulateZ(std::vector<double> accumulatez); void setUniverses(int num_z, int num_y, int num_x, Universe** universes); void updateUniverse(int lat_x, int lat_y, int lat_z, Universe* universe); void removeUniverse(Universe* universe); void subdivideCells(double max_radius=INFINITY); void buildNeighbors(); bool containsPoint(Point* point); Cell* findCell(LocalCoords* coords); double minSurfaceDist(Point* point, double azim, double polar=M_PI/2.0); int getLatX(Point* point); int getLatY(Point* point); int getLatZ(Point* point); int getLatticeCell(Point* point); int getLatticeSurface(int cell, Point* point); int getLatticeSurfaceOTF(int cell, double z, int surface_2D); std::string toString(); void printString(); /* Set XYZ widths of non-uniform meshes */ void setWidths(std::vector<double> widths_x, std::vector<double> widths_y, std::vector<double> widths_z); void computeSizes(); /* For debug use */ void printLatticeSizes(); }; /** * @brief A helper struct for the Universe::findCell() method. * @details This is used to insert a Universe's Cells to the back of a vector * of neighbor Cells in Universe::findCell() routine. This works in * symbiosis with the pair_second method template defined below. */ template<typename tPair> struct second_t { typename tPair::second_type operator()(const tPair& p) const { return p.second; } }; /** * @brief A helper routine for the Universe::findCell() method. * @details This is used to insert a Universe's Cells to the back of a vector * of neighbor Cells in Universe::findCell() routine. This works in * symbiosis with the second_t struct template defined above. * @param map a std::map iterator * @return the second element in the iterator (e.g., map value) */ template<typename tMap> second_t<typename tMap::value_type> pair_second(const tMap& map) { return second_t<typename tMap::value_type>(); } #endif /* UNIVERSE_H_ */
AI-Pranto/OpenMOC
src/accel/cuda/GPUQuery.h
<gh_stars>10-100 /** * @file GPUQuery.h * @brief Routines to check machine for an NVIDIA GPU and print GPU * and CUDA hardware characteristics to the screen. * @author May 30, 2013 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef GPUQUERY_H_ #define GPUQUERY_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "../../log.h" #endif bool machine_contains_gpu(); void attach_gpu(int id=0); void print_basic_gpu_info(); void print_detailed_gpu_info(); int get_num_threads_per_warp(); /* Cuda error handling macro */ #define getLastCudaError() getLastCudaError_inline(__FILE__, __LINE__) inline void getLastCudaError_inline(const char* file, const int line) { cudaError_t err = cudaGetLastError(); if (err != cudaSuccess) { log_printf(ERROR, "%s:%i getLastCudaError() CUDA error:\n" "Error code %i: %s.\n", file, line, static_cast<int>(err), cudaGetErrorString(err)); } } #endif /* GPUQUERY_H_ */
AI-Pranto/OpenMOC
src/Quadrature.h
/** * @file Quadrature.h * @brief The Quadrature abstract class and subclasses. * @details The Quadrature subclasses are defined with tabulated or functional * quadrature sets given in the "Lattice Physics Computations", * Handbook of Nuclear Engineering, <NAME>, <NAME>, 2010. * @date April 8, 2016 * @author <NAME>, MIT, Course 22 (<EMAIL>) * @author <NAME>, MIT, Course 22 (<EMAIL>) * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef QUADRATURE_H_ #define QUADRATURE_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "constants.h" #include "log.h" #include <sstream> #endif #include <vector> #include <iostream> #include <cmath> #include <algorithm> /** * @enum QuadratureType * @brief The types of quadrature sets supported by OpenMOC. */ enum QuadratureType { TABUCHI_YAMAMOTO, LEONARD, GAUSS_LEGENDRE, EQUAL_WEIGHT, EQUAL_ANGLE }; /** Shorthand for vectors of floats */ typedef std::vector<double> DoubleVec; typedef std::vector<FP_PRECISION> FloatVec; typedef DoubleVec::const_iterator DVCI; /** Template function for writing vectors to a stream */ template <typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) { if (vec.size() == 0) { os << "EMPTY"; } else { using CI = typename std::vector<T>::const_iterator; os << "["; for (CI cit = vec.begin(); cit != vec.end(); ++cit) { if (cit != vec.begin()) { os << ", "; } os << *cit; } os << "]"; } return os; } /** * @class Quadrature Quadrature.h "src/Quadrature.h" * @brief The arbitrary quadrature parent class. */ class Quadrature { protected: /** The quadrature type being used */ QuadratureType _quad_type; /** The number of azimuthal angles in (0, 2*PI) */ size_t _num_azim; /** The number of polar angles in (0, PI) */ size_t _num_polar; /** An array of the sines of quadrature polar angles */ std::vector<DoubleVec> _sin_thetas; /** An array of the inverse sines of quadrature polar angles */ std::vector<FloatVec> _inv_sin_thetas; /** An array of the quadrature polar angles */ std::vector<DoubleVec> _thetas; /** An array of the quadrature azimuthal angles */ DoubleVec _phis; /** The actual track azimuthal spacing (cm) by azimuthal angle */ DoubleVec _azim_spacings; /** An array of the quadrature azimuthal weights */ DoubleVec _azim_weights; /** The actual track polar spacing (cm) by (azim, polar) */ std::vector<DoubleVec> _polar_spacings; /** An array of the quadrature polar weights */ std::vector<DoubleVec> _polar_weights; /** An array of the total weights for each azimuthal/polar angle pair */ std::vector<FloatVec> _total_weights; /* Templates for setting the same values to complimentary and supplementary * angles */ template <typename T> void setPolarValues(std::vector< std::vector<T> >& vec, size_t azim_index, size_t polar_index, T value) { size_t c_azim_index = _num_azim/2 - azim_index - 1; size_t s_polar_index = _num_polar - polar_index - 1; vec.at(azim_index).at(polar_index) = value; vec.at(c_azim_index).at(polar_index) = value; vec.at(azim_index).at(s_polar_index) = value; vec.at(c_azim_index).at(s_polar_index) = value; } template <typename T> void setAzimuthalValues(std::vector<T>& vec, size_t azim_index, T value) { vec.at(azim_index) = value; vec.at(_num_azim/2 - azim_index - 1) = value; } template <typename T> static void resize2D(std::vector< std::vector<T> >& vec, size_t dim1, size_t dim2) { vec.resize(dim1); for (size_t i = 0; i < dim1; ++i) { vec.at(i).resize(dim2); } } public: Quadrature(); size_t getNumPolarAngles() const; size_t getNumAzimAngles() const; double getSinTheta(size_t azim, size_t polar) const; double getSinThetaInline(size_t azim, size_t polar) const; FP_PRECISION getInvSinThetaInline(size_t azim, size_t polar) const; double getTheta(size_t azim, size_t polar) const; double getPhi(size_t azim) const; double getAzimWeight(size_t azim) const; double getPolarWeight(size_t azim, size_t polar) const; double getWeight(size_t azim, size_t polar) const; FP_PRECISION getWeightInline(size_t azim, size_t polar) const; const std::vector<DoubleVec>& getSinThetas() const; const std::vector<DoubleVec>& getThetas() const; const DoubleVec& getPhis() const; const DoubleVec& getAzimWeights() const; const std::vector<DoubleVec>& getPolarWeights() const; QuadratureType getQuadratureType() const; const DoubleVec& getAzimSpacings() const; double getAzimSpacing(size_t azim) const; const std::vector<DoubleVec>& getPolarSpacings() const; double getPolarSpacing(size_t azim, size_t polar) const; virtual void setNumAzimAngles(size_t num_azim); virtual void setNumPolarAngles(size_t num_polar); void setThetas(const DoubleVec& thetas); void setPolarWeights(const DoubleVec& weights); void setTheta(double theta, size_t azim, size_t polar); void setPhi(double phi, size_t azim); void setAzimSpacing(double spacing, size_t azim); void setPolarSpacing(double spacing, size_t azim, size_t polar); void setAzimWeight(double weight, size_t azim); void setPolarWeight(double weight, size_t azim, size_t polar); virtual void initialize(); virtual void precomputeWeights(bool solve_3D); std::string toString() const; friend std::ostream& operator<<(std::ostream& os, const Quadrature& quad); }; /** * @class TYPolarQuad Quadrature.h "src/Quadrature.h" * @brief Tabuchi-Yamamoto's polar quadrature. */ class TYPolarQuad: public Quadrature { private: public: TYPolarQuad(); void setNumPolarAngles(size_t num_polar); void initialize(); void precomputeWeights(bool solve_3D); }; /** * @class LeonardPolarQuad Quadrature.h "src/Quadrature.h" * @brief Leonard's polar quadrature. */ class LeonardPolarQuad: public Quadrature { private: public: LeonardPolarQuad(); void setNumPolarAngles(size_t num_polar); void initialize(); void precomputeWeights(bool solve_3D); }; /** * @class GLPolarQuad Quadrature.h "src/Quadrature.h" * @brief Gauss-Legendre's polar quadrature. */ class GLPolarQuad: public Quadrature { private: /** the roots to the Legendre polynomial of degree _num_polar */ std::vector <double> _roots; /** the roots which have been adjusted to allow for periodic tracks */ std::vector <double> _adjusted_roots; /** Whether to updated weights based on adjusted polar angles */ bool _correct_weights; public: GLPolarQuad(); void setNumPolarAngles(size_t num_polar); void useCorrectedWeights(bool use_corrected_weights); void initialize(); void precomputeWeights(bool solve_3D); DoubleVec getCorrectedWeights(size_t azim) const; static double legendrePolynomial(size_t n, double x); static double logDerivLegendre(size_t n, double x); static double secondLogDerivLegendre(size_t n, double x); static double getSingleWeight(double root, size_t n); static DoubleVec getLegendreRoots(size_t n); static DoubleVec getGLWeights(const DoubleVec& roots, size_t n); }; /** * @class EqualWeightPolarQuad Quadrature.h "src/Quadrature.h" * @brief Equal weight polar quadrature. */ class EqualWeightPolarQuad: public Quadrature { private: public: EqualWeightPolarQuad(); void setNumPolarAngles(size_t num_polar); void initialize(); void precomputeWeights(bool solve_3D); }; /** * @class EqualAnglePolarQuad Quadrature.h "src/Quadrature.h" * @brief Equal angle polar quadrature. */ class EqualAnglePolarQuad: public Quadrature { private: public: EqualAnglePolarQuad(); void setNumPolarAngles(size_t num_polar); void initialize(); void precomputeWeights(bool solve_3D); }; /** * @brief Returns the \f$ sin(\theta)\f$ value for a particular polar angle. * @param azim index of the azimthal angle of interest * @param polar index of the polar angle of interest * @return the value of \f$ \sin(\theta) \f$ for this azimuthal and polar angle * @details azim must be between 0 and _num_azim / 2 */ inline double Quadrature::getSinThetaInline(size_t azim, size_t polar) const { if (azim >= _num_azim/2) azim = _num_azim - azim - 1; return _sin_thetas[azim][polar]; } /** * @brief Returns the \f$ 1/sin(\theta)\f$ value for a particular polar angle. * @param azim index of the azimthal angle of interest * @param polar index of the polar angle of interest * @return the value of \f$ 1 / \sin(\theta) \f$ for this azimuthal and polar angle * @details azim must be between 0 and _num_azim / 2 */ inline FP_PRECISION Quadrature::getInvSinThetaInline(size_t azim, size_t polar) const { if (azim >= _num_azim/2) azim = _num_azim - azim - 1; return _inv_sin_thetas[azim][polar]; } /** * @brief Returns the total weight for Tracks with the given azimuthal and * polar indexes without error checking and inlined * @details Angular weights are multiplied by Track spacings * @param azim index of the azimuthal angle of interest * @param polar index of the polar angle of interest * @return the total weight of each Track with the given indexes */ inline FP_PRECISION Quadrature::getWeightInline(size_t azim, size_t polar) const { return _total_weights[azim][polar]; } #endif /* QUADRATURE_H_ */
AI-Pranto/OpenMOC
src/CPUSolver.h
/** * @file CPUSolver.h * @brief The CPUSolver class. * @date May 28, 2013 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef CPUSOLVER_H_ #define CPUSOLVER_H_ #ifdef __cplusplus #define _USE_MATH_DEFINES #include "Solver.h" #include "TrackTraversingAlgorithms.h" #include <math.h> #include <omp.h> #include <stdlib.h> #include <unordered_map> #endif #undef track_flux /** Optimization macro to facilitate SIMD vectorization */ #ifdef NGROUPS #define _NUM_GROUPS (NGROUPS) #else #define _NUM_GROUPS (_num_groups) #endif /** Indexing macro for the angular fluxes for each polar angle and energy * group for either the forward or reverse direction for a given Track */ #define track_flux(pe) (track_flux[(pe)]) /** Indexing macro for the angular fluxes for each polar angle and energy * group for the outgoing reflective track from a given Track */ #define track_out_flux(pe) (track_out_flux[(pe)]) /** Indexing macro for the leakage for each polar angle and energy group * for either the forward or reverse direction for a given Track */ #define track_leakage(pe) (track_leakage[(pe)]) /* Structure containing the info to send about a track (used in printCycle) */ struct sendInfo { long track_id; int domain; bool fwd; }; /** * @class CPUSolver CPUSolver.h "src/CPUSolver.h" * @brief This a subclass of the Solver class for multi-core CPUs using * OpenMP multi-threading. */ class CPUSolver : public Solver { protected: /** The number of shared memory OpenMP threads */ int _num_threads; /** OpenMP mutual exclusion locks for atomic FSR scalar flux updates */ omp_lock_t* _FSR_locks; #ifdef MPIx /* Message size when communicating track angular fluxes at interfaces */ int _track_message_size; /* Buffer to send track angular fluxes and associated information */ std::vector<std::vector<float> > _send_buffers; /* Index into send_buffers for pre-filling (ONLYVACUUMBC mode) */ std::vector<int> _send_buffers_index; /* Buffer to receive track angular fluxes and associated information */ std::vector<std::vector<float> > _receive_buffers; /* Vector of vectors containing boundary track ids and direction */ std::vector<std::vector<long> > _boundary_tracks; /* Vector to know how big of a send buffer to send to another domain */ std::vector<int> _send_size; /* Vector to save the size of the receive buffers */ std::vector<int> _receive_size; /* Vector of vectors containing the connecting track id and direction */ std::vector<std::vector<long> > _track_connections; /* Vector of vectors containing the connecting domains */ std::vector<std::vector<int> > _domain_connections; /* Rank of domains neighboring local domain */ std::vector<int> _neighbor_domains; /* Index of neighboring domains in _neighbor_domains */ std::unordered_map<int, int> _neighbor_connections; /* Array to check whether MPI communications are finished */ MPI_Request* _MPI_requests; /* Arrays of booleans to know whether a send/receive call was made */ bool* _MPI_sends; bool* _MPI_receives; #endif #ifdef ONLYVACUUMBC /* Vector of the vacuum boundary track ids and direction */ std::vector<long> _tracks_from_vacuum; /* Vector of vectors containing if a track flux has been sent by pre-fill */ std::vector<std::vector<bool> > _track_flux_sent; #endif virtual void initializeFluxArrays(); virtual void initializeSourceArrays(); virtual void initializeFSRs(); void zeroTrackFluxes(); void copyBoundaryFluxes(); void tallyStartingCurrents(); #ifdef MPIx void setupMPIBuffers(); void deleteMPIBuffers(); void packBuffers(std::vector<long> &packing_indexes); void transferAllInterfaceFluxes(); #endif #ifdef ONLYVACUUMBC void resetBoundaryFluxes(); #endif virtual void flattenFSRFluxes(FP_PRECISION value); void flattenFSRFluxesChiSpectrum(); void storeFSRFluxes(); virtual double normalizeFluxes(); void computeFSRFissionSources(); void computeFSRScatterSources(); virtual void computeFSRSources(int iteration); void transportSweep(); virtual void computeStabilizingFlux(); virtual void stabilizeFlux(); virtual void addSourceToScalarFlux(); void computeKeff(); double computeResidual(residualType res_type); public: CPUSolver(TrackGenerator* track_generator=NULL); virtual ~CPUSolver(); int getNumThreads(); void setNumThreads(int num_threads); void setFluxes(FP_PRECISION* in_fluxes, int num_fluxes); void setFixedSourceByFSR(long fsr_id, int group, FP_PRECISION source); void resetFixedSources(); void computeFSRFissionRates(double* fission_rates, long num_FSRs, bool nu = false); void printInputParamsSummary(); void tallyScalarFlux(segment* curr_segment, int azim_index, FP_PRECISION* fsr_flux, float* track_flux); void accumulateScalarFluxContribution(long fsr_id, FP_PRECISION weight, FP_PRECISION* fsr_flux); void tallyCurrent(segment* curr_segment, int azim_index, int polar_index, float* track_flux, bool fwd); void transferBoundaryFlux(Track* track, int azim_index, int polar_index, bool direction, float* track_flux); void getFluxes(FP_PRECISION* out_fluxes, int num_fluxes); void initializeFixedSources(); void printFSRFluxes(std::vector<double> dim1, std::vector<double> dim2, double offset, const char* plane); void printFluxesTemp(); void printNegativeSources(int iteration, int num_x, int num_y, int num_z); #ifdef MPIx void printCycle(long track_start, int domain_start, int length); void printLoadBalancingReport(); void boundaryFluxChecker(); #endif }; #endif /* CPUSOLVER_H_ */
AI-Pranto/OpenMOC
profile/models/load-geometry/helper-code/group-structures.h
#include <vector> #include <iostream> #include "../../../../src/log.h" std::vector<std::vector<int> > get_group_structure(int num_groups, int num_cmfd_groups); inline std::vector<std::vector<int> > get_group_structure(int num_groups, int num_cmfd_groups) { std::vector<std::vector<int> > cmfd_group_structure; cmfd_group_structure.resize(num_cmfd_groups); if (num_groups == num_cmfd_groups) { for (int g=0; g < num_groups; g++) cmfd_group_structure.at(g).push_back(g+1); } else if (num_cmfd_groups == 1) { for (int g=0; g < num_groups; g++) cmfd_group_structure.at(0).push_back(g+1); } else if (num_groups == 70) { if (num_cmfd_groups == 2) { for (int g=0; g<46; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=46; g<70; g++) cmfd_group_structure.at(1).push_back(g+1); } else if (num_cmfd_groups == 4) { for (int g=0; g<5; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=5; g<15; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=15; g<46; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=46; g<70; g++) cmfd_group_structure.at(3).push_back(g+1); } else if (num_cmfd_groups == 8) { for (int g=0; g<5; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=5; g<15; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=15; g<27; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=27; g<46; g++) cmfd_group_structure.at(3).push_back(g+1); for (int g=46; g<52; g++) cmfd_group_structure.at(4).push_back(g+1); for (int g=52; g<56; g++) cmfd_group_structure.at(5).push_back(g+1); for (int g=56; g<60; g++) cmfd_group_structure.at(6).push_back(g+1); for (int g=60; g<70; g++) cmfd_group_structure.at(7).push_back(g+1); } else if (num_cmfd_groups == 11) { for (int g=0; g<5; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=5; g<15; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=15; g<24; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=24; g<25; g++) cmfd_group_structure.at(3).push_back(g+1); for (int g=25; g<26; g++) cmfd_group_structure.at(4).push_back(g+1); for (int g=26; g<27; g++) cmfd_group_structure.at(5).push_back(g+1); for (int g=27; g<46; g++) cmfd_group_structure.at(6).push_back(g+1); for (int g=46; g<52; g++) cmfd_group_structure.at(7).push_back(g+1); for (int g=52; g<56; g++) cmfd_group_structure.at(8).push_back(g+1); for (int g=56; g<60; g++) cmfd_group_structure.at(9).push_back(g+1); for (int g=60; g<70; g++) cmfd_group_structure.at(10).push_back(g+1); } else if (num_cmfd_groups == 12) { for (int g=0; g<5; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=5; g<15; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=15; g<27; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=27; g<46; g++) cmfd_group_structure.at(3).push_back(g+1); for (int g=46; g<49; g++) cmfd_group_structure.at(4).push_back(g+1); for (int g=49; g<52; g++) cmfd_group_structure.at(5).push_back(g+1); for (int g=52; g<54; g++) cmfd_group_structure.at(6).push_back(g+1); for (int g=54; g<56; g++) cmfd_group_structure.at(7).push_back(g+1); for (int g=56; g<58; g++) cmfd_group_structure.at(8).push_back(g+1); for (int g=58; g<60; g++) cmfd_group_structure.at(9).push_back(g+1); for (int g=60; g<65; g++) cmfd_group_structure.at(10).push_back(g+1); for (int g=65; g<70; g++) cmfd_group_structure.at(11).push_back(g+1); } else if (num_cmfd_groups == 14) { for (int g=0; g<2; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=2; g<6; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=6; g<9; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=9; g<12; g++) cmfd_group_structure.at(3).push_back(g+1); for (int g=12; g<16; g++) cmfd_group_structure.at(4).push_back(g+1); for (int g=16; g<19; g++) cmfd_group_structure.at(5).push_back(g+1); for (int g=19; g<21; g++) cmfd_group_structure.at(6).push_back(g+1); for (int g=21; g<24; g++) cmfd_group_structure.at(7).push_back(g+1); for (int g=24; g<27; g++) cmfd_group_structure.at(8).push_back(g+1); for (int g=27; g<33; g++) cmfd_group_structure.at(9).push_back(g+1); for (int g=33; g<53; g++) cmfd_group_structure.at(10).push_back(g+1); for (int g=53; g<61; g++) cmfd_group_structure.at(11).push_back(g+1); for (int g=61; g<68; g++) cmfd_group_structure.at(12).push_back(g+1); for (int g=68; g<70; g++) cmfd_group_structure.at(13).push_back(g+1); } else if (num_cmfd_groups == 16) { for (int g=0; g<5; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=5; g<15; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=15; g<27; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=27; g<34; g++) cmfd_group_structure.at(3).push_back(g+1); for (int g=34; g<35; g++) cmfd_group_structure.at(4).push_back(g+1); for (int g=35; g<37; g++) cmfd_group_structure.at(5).push_back(g+1); for (int g=37; g<40; g++) cmfd_group_structure.at(6).push_back(g+1); for (int g=40; g<42; g++) cmfd_group_structure.at(7).push_back(g+1); for (int g=42; g<45; g++) cmfd_group_structure.at(8).push_back(g+1); for (int g=45; g<47; g++) cmfd_group_structure.at(9).push_back(g+1); for (int g=47; g<50; g++) cmfd_group_structure.at(10).push_back(g+1); for (int g=50; g<53; g++) cmfd_group_structure.at(11).push_back(g+1); for (int g=53; g<57; g++) cmfd_group_structure.at(12).push_back(g+1); for (int g=57; g<61; g++) cmfd_group_structure.at(13).push_back(g+1); for (int g=61; g<65; g++) cmfd_group_structure.at(14).push_back(g+1); for (int g=65; g<70; g++) cmfd_group_structure.at(15).push_back(g+1); } else if (num_cmfd_groups == 25) { for (int g=0; g<6; g++) cmfd_group_structure.at(g).push_back(g+1); for (int g=6; g<9; g++) cmfd_group_structure.at(6).push_back(g+1); for (int g=9; g<14; g++) cmfd_group_structure.at(7).push_back(g+1); for (int g=14; g<15; g++) cmfd_group_structure.at(8).push_back(g+1); for (int g=15; g<21; g++) cmfd_group_structure.at(9).push_back(g+1); for (int g=21; g<25; g++) cmfd_group_structure.at(10).push_back(g+1); for (int g=25; g<26; g++) cmfd_group_structure.at(11).push_back(g+1); for (int g=26; g<27; g++) cmfd_group_structure.at(12).push_back(g+1); for (int g=27; g<31; g++) cmfd_group_structure.at(13).push_back(g+1); for (int g=31; g<34; g++) cmfd_group_structure.at(14).push_back(g+1); for (int g=34; g<36; g++) cmfd_group_structure.at(15).push_back(g+1); for (int g=36; g<39; g++) cmfd_group_structure.at(16).push_back(g+1); for (int g=39; g<41; g++) cmfd_group_structure.at(17).push_back(g+1); for (int g=41; g<46; g++) cmfd_group_structure.at(18).push_back(g+1); for (int g=46; g<49; g++) cmfd_group_structure.at(19).push_back(g+1); for (int g=49; g<52; g++) cmfd_group_structure.at(20).push_back(g+1); for (int g=52; g<56; g++) cmfd_group_structure.at(21).push_back(g+1); for (int g=56; g<60; g++) cmfd_group_structure.at(22).push_back(g+1); for (int g=60; g<64; g++) cmfd_group_structure.at(23).push_back(g+1); for (int g=64; g<70; g++) cmfd_group_structure.at(24).push_back(g+1); } } else if (num_groups == 40) { if (num_cmfd_groups == 2) { for (int g=0; g<28; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=28; g<40; g++) cmfd_group_structure.at(1).push_back(g+1); } else if (num_cmfd_groups == 4) { for (int g=0; g<5; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=5; g<9; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=9; g<28; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=28; g<40; g++) cmfd_group_structure.at(3).push_back(g+1); } } else if (num_groups == 25) { if (num_cmfd_groups == 2) { for (int g=0; g<19; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=19; g<25; g++) cmfd_group_structure.at(1).push_back(g+1); } else if (num_cmfd_groups == 4) { for (int g=0; g<5; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=5; g<9; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=9; g<19; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=19; g<25; g++) cmfd_group_structure.at(3).push_back(g+1); } else if (num_cmfd_groups == 8) { for (int g=0; g<5; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=5; g<9; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=9; g<13; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=13; g<19; g++) cmfd_group_structure.at(3).push_back(g+1); for (int g=19; g<21; g++) cmfd_group_structure.at(4).push_back(g+1); for (int g=21; g<22; g++) cmfd_group_structure.at(5).push_back(g+1); for (int g=22; g<23; g++) cmfd_group_structure.at(6).push_back(g+1); for (int g=23; g<25; g++) cmfd_group_structure.at(7).push_back(g+1); } // CASMO-16 and -25 have different group boundaries for thermal energies else if (num_cmfd_groups == 16) { for (int g=0; g<5; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=5; g<9; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=9; g<12; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=12; g<13; g++) cmfd_group_structure.at(3).push_back(g+1); for (int g=13; g<14; g++) cmfd_group_structure.at(4).push_back(g+1); for (int g=14; g<15; g++) cmfd_group_structure.at(5).push_back(g+1); for (int g=15; g<16; g++) cmfd_group_structure.at(6).push_back(g+1); for (int g=16; g<17; g++) cmfd_group_structure.at(7).push_back(g+1); for (int g=17; g<18; g++) cmfd_group_structure.at(8).push_back(g+1); for (int g=18; g<19; g++) cmfd_group_structure.at(9).push_back(g+1); for (int g=19; g<20; g++) cmfd_group_structure.at(10).push_back(g+1); for (int g=20; g<21; g++) cmfd_group_structure.at(11).push_back(g+1); for (int g=21; g<22; g++) cmfd_group_structure.at(12).push_back(g+1); for (int g=22; g<23; g++) cmfd_group_structure.at(13).push_back(g+1); for (int g=23; g<24; g++) cmfd_group_structure.at(14).push_back(g+1); for (int g=24; g<25; g++) cmfd_group_structure.at(15).push_back(g+1); } } else if (num_groups == 16) { if (num_cmfd_groups == 2) { for (int g=0; g<10; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=10; g<16; g++) cmfd_group_structure.at(1).push_back(g+1); } else if (num_cmfd_groups == 4) { for (int g=0; g<3; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=3; g<4; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=4; g<5; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=12; g<16; g++) cmfd_group_structure.at(3).push_back(g+1); } else if (num_cmfd_groups == 8) { for (int g=0; g<1; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=1; g<2; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=2; g<3; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=3; g<10; g++) cmfd_group_structure.at(3).push_back(g+1); for (int g=10; g<12; g++) cmfd_group_structure.at(4).push_back(g+1); for (int g=12; g<13; g++) cmfd_group_structure.at(5).push_back(g+1); for (int g=13; g<14; g++) cmfd_group_structure.at(6).push_back(g+1); for (int g=14; g<16; g++) cmfd_group_structure.at(7).push_back(g+1); } } else if (num_groups == 8) { if (num_cmfd_groups == 2) { for (int g=0; g<3; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=3; g<8; g++) cmfd_group_structure.at(1).push_back(g+1); } else if (num_cmfd_groups == 4) { for (int g=0; g<2; g++) cmfd_group_structure.at(0).push_back(g+1); for (int g=2; g<3; g++) cmfd_group_structure.at(1).push_back(g+1); for (int g=3; g<5; g++) cmfd_group_structure.at(2).push_back(g+1); for (int g=5; g<8; g++) cmfd_group_structure.at(3).push_back(g+1); } } else if (num_groups < num_cmfd_groups) log_printf(ERROR, "Number of CMFD groups must be lower than the number of" "MOC groups."); if (cmfd_group_structure.at(0).size() == 0) { log_printf(WARNING_ONCE, "CMFD group structure requested is unknown, " "creating a condensed structure with a constant number of " "MOC groups in each CMFD group"); int group = 0; int last_index = 0; for (int cg=0; cg<num_cmfd_groups; cg++) { /* Keep track of last index */ int next_bound = std::min(int((cg+1) * float(num_groups + 1) / num_cmfd_groups - last_index), num_groups - group); last_index += next_bound; for (int i=0; i<next_bound; i++) cmfd_group_structure.at(cg).push_back(++group); } } return cmfd_group_structure; }
AI-Pranto/OpenMOC
src/ParallelHashMap.h
/** * @file ParallelHashMap.h * @brief A thread-safe hash map supporting insertion and lookup operations. * @details The parallel hash map is built on top of a fixed-sized hash map * object and features OpenMP concurrency structures. The underlying * fixed-sized hash map handles collisions with chaining. * @date June 6, 2015 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef __PARALLEL_HASH_MAP__ #define __PARALLEL_HASH_MAP__ #include<iostream> #include<stdexcept> #include<functional> #include<omp.h> #include "log.h" /** * @class FixedHashMap ParallelHashMap.h "src/ParallelHashMap.h" * @brief A fixed-size hash map supporting insertion and lookup operations. * @details The FixedHashMap class supports insertion and lookup operations * but not deletion as deletion is not needed in the OpenMOC application. * This hash table uses chaining for collisions and does not incorporate * concurrency objects except for tracking the number of entries in the * table for which an atomic increment is used. This hash table is not * thread safe but is used as a building block for the ParallelHashMap * class. This table guarantees O(1) insertions and lookups on average. */ template <class K, class V> class FixedHashMap { struct node { node(K k_in, V v_in) : next(NULL), key(k_in), value(v_in) {} K key; V value; node *next; }; private: size_t _M; /* table size */ size_t _N; /* number of elements present in table */ node ** _buckets; /* buckets of values stored in nodes */ public: FixedHashMap(size_t M = 64); virtual ~FixedHashMap(); bool contains(K& key); V& at(K& key); void insert(K key, V value); long insert_and_get_count(K key, V value); size_t size(); size_t bucket_count(); K* keys(); V* values(); void clear(); void print_buckets(); }; /** * @class ParallelHashMap ParallelHashMap.h "src/ParallelHashMap.h" * @brief A thread-safe hash map supporting insertion and lookup operations. * @details The ParallelHashMap class is built on top of the FixedHashMap * class, supporting insertion and lookup operations but not deletion as * deletion is not needed in the OpenMOC application. This hash table uses * chaining for collisions, as defined in FixedHashMap. It offers lock * free lookups in O(1) time on average and fine-grained locking for * insertions in O(1) time on average as well. Resizing is conducted * periodically during inserts, although the starting table size can be * chosen to limit the number of resizing operations. */ template <class K, class V> class ParallelHashMap { /* padded pointer to hash table to avoid false sharing */ struct paddedPointer { volatile long pad_L1; volatile long pad_L2; volatile long pad_L3; volatile long pad_L4; volatile long pad_L5; volatile long pad_L6; volatile long pad_L7; FixedHashMap<K,V> volatile* value; volatile long pad_R1; volatile long pad_R2; volatile long pad_R3; volatile long pad_R4; volatile long pad_R5; volatile long pad_R6; volatile long pad_R7; volatile long pad_R8; }; private: FixedHashMap<K,V> *_table; paddedPointer *_announce; size_t _num_threads; size_t _N; omp_lock_t * _locks; size_t _num_locks; bool _fixed_size; void resize(); public: ParallelHashMap(size_t M = 64, size_t L = 64); virtual ~ParallelHashMap(); bool contains(K& key); V at(K& key); void update(K& key, V value); void insert(K key, V value); long insert_and_get_count(K key, V value); size_t size(); size_t bucket_count(); size_t num_locks(); K* keys(); V* values(); void clear(); void setFixedSize(); void print_buckets(); void realloc(size_t M); }; /** * @brief Constructor initializes fixed-size table of buckets filled with empty * linked lists. * @details The constructor initializes a fixed-size hash map with the size * as an input parameter. If no size is given the default size (64) * is used. Buckets are filled with empty linked lists presented as * NULL pointers. * @param M size of fixed hash map */ template <class K, class V> FixedHashMap<K,V>::FixedHashMap(size_t M) { /* ensure M is a power of 2 */ if ((M & (M-1)) != 0) { /* if not, round up to nearest power of 2 */ M--; for (size_t i = 1; i < 8 * sizeof(size_t); i*=2) M |= M >> i; M++; } /* allocate table */ _M = M; _N = 0; _buckets = new node*[_M](); } /** * @brief Destructor deletes all nodes in the linked lists associated with each * bucket in the fixed-size table and their pointers. */ template <class K, class V> FixedHashMap<K,V>::~FixedHashMap() { /* for each bucket, scan through linked list and delete all nodes */ for (size_t i=0; i<_M; i++) { node *iter_node = _buckets[i]; while (iter_node != NULL) { node *next_node = iter_node->next; delete iter_node; iter_node = next_node; } } /* delete all buckets (now pointers to empty linked lists) */ delete [] _buckets; } /** * @brief Determine whether the fixed-size table contains a given key. * @details The linked list in the bucket associated with the key is searched * to determine whether the key is present. * @param key key to be searched * @return boolean value referring to whether the key is contained in the map */ template <class K, class V> bool FixedHashMap<K,V>::contains(K& key) { /* get hash into table assuming M is a power of 2, using fast modulus */ size_t key_hash = std::hash<K>()(key) & (_M-1); /* search corresponding bucket for key */ node *iter_node = _buckets[key_hash]; while (iter_node != NULL) { if (iter_node->key == key) return true; else iter_node = iter_node->next; } return false; } /** * @brief Determine the value associated with a given key in the fixed-size * table. * @details The linked list in the bucket associated with the key is searched * and once the key is found, the corresponding value is returned. * An exception is thrown if the key is not present in the map. * @param key key whose corresponding value is desired * @return value associated with the given key */ template <class K, class V> V& FixedHashMap<K,V>::at(K& key) { /* get hash into table assuming M is a power of 2, using fast modulus */ size_t key_hash = std::hash<K>()(key) & (_M-1); /* search bucket for key and return the corresponding value if found */ node *iter_node = _buckets[key_hash]; while (iter_node != NULL) { if (iter_node->key == key) return iter_node->value; else iter_node = iter_node->next; } /* after the bucket has been completely searched without finding the key, print an error message */ log_printf(ERROR, "Key not present in map"); } /** * @brief Inserts a key/value pair into the fixed-size table. * @details The specified key value pair is inserted into the fixed-size table. * If the key already exists in the table, the pair is not inserted * and the function returns. * @param key key of the key/value pair to be inserted * @param value value of the key/value pair to be inserted */ template <class K, class V> void FixedHashMap<K,V>::insert(K key, V value) { /* get hash into table using fast modulus */ size_t key_hash = std::hash<K>()(key) & (_M-1); /* check to see if key already exists in map */ if (contains(key)) return; /* create new node */ node *new_node = new node(key, value); /* find where to place element in linked list */ node **iter_node = &_buckets[key_hash]; while (*iter_node != NULL) iter_node = &(*iter_node)->next; /* place element in linked list */ *iter_node = new_node; /* increment counter */ #pragma omp atomic _N++; } /** * @brief Inserts a key/value pair into the fixed-size table and returns the * order number with which it was inserted. * @details The specified key value pair is inserted into the fixed-size table. * If the key already exists in the table, the pair is not inserted * and the function returns -1. * @param key key of the key/value pair to be inserted * @param value value of the key/value pair to be inserted * @return order number in which key/value pair was inserted, -1 is returned if * key was already present in map. */ template <class K, class V> long FixedHashMap<K,V>::insert_and_get_count(K key, V value) { /* get hash into table using fast modulus */ size_t key_hash = std::hash<K>()(key) & (_M-1); /* check to see if key already exists in map */ if (contains(key)) return -1; /* create new node */ node *new_node = new node(key, value); /* find where to place element in linked list */ node **iter_node = &_buckets[key_hash]; while (*iter_node != NULL) iter_node = &(*iter_node)->next; /* place element in linked list */ *iter_node = new_node; /* increment counter and return number */ size_t N; #pragma omp atomic capture N = _N++; return (long) N; } /** * @brief Returns the number of key/value pairs in the fixed-size table. * @return number of key/value pairs in the map */ template <class K, class V> size_t FixedHashMap<K,V>::size() { return _N; } /** * @brief Returns the number of buckets in the fixed-size table. * @return number of buckets in the map */ template <class K, class V> size_t FixedHashMap<K,V>::bucket_count() { return _M; } /** * @brief Returns an array of the keys in the fixed-size table. * @details All buckets are scanned in order to form a list of all keys * present in the table and then the list is returned. WARNING: The user * is responsible for freeing the allocated memory once the array is no * longer needed. * @return an array of keys in the map whose length is the number of key/value * pairs in the table. */ template <class K, class V> K* FixedHashMap<K,V>::keys() { /* allocate array of keys */ K *key_list = new K[_N]; /* fill array with keys */ size_t ind = 0; for (size_t i=0; i<_M; i++) { node *iter_node = _buckets[i]; while (iter_node != NULL) { key_list[ind] = iter_node->key; iter_node = iter_node->next; ind++; } } return key_list; } /** * @brief Returns an array of the values in the fixed-size table. * @details All buckets are scanned in order to form a list of all values * present in the table and then the list is returned. WARNING: The user * is responsible for freeing the allocated memory once the array is no * longer needed. * @return an array of values in the map whose length is the number of * key/value pairs in the table. */ template <class K, class V> V* FixedHashMap<K,V>::values() { /* allocate array of values */ V *values = new V[_N]; /* fill array with values */ size_t ind = 0; for (size_t i=0; i<_M; i++) { node *iter_node = _buckets[i]; while (iter_node != NULL) { values[ind] = iter_node->value; iter_node = iter_node->next; ind++; } } return values; } /** * @brief Clears all key/value pairs form the hash table. */ template <class K, class V> void FixedHashMap<K,V>::clear() { /* for each bucket, scan through linked list and delete all nodes */ for (size_t i=0; i<_M; i++) { node *iter_node = _buckets[i]; while (iter_node != NULL) { node *next_node = iter_node->next; delete iter_node; iter_node = next_node; } } /* reset each bucket to null */ for (size_t i=0; i<_M; i++) _buckets[i] = NULL; /* reset the number of entries to zero */ _N = 0; } /** * @brief Prints the contents of each bucket to the screen. * @details All buckets are scanned and the contents of the buckets are * printed, which are pointers to linked lists. If the pointer is NULL * suggesting that the linked list is empty, NULL is printed to the * screen. */ template <class K, class V> void FixedHashMap<K,V>::print_buckets() { log_printf(NORMAL, "Printing all buckets in the hash map..."); for (size_t i=0; i<_M; i++) { if (_buckets[i] == NULL) log_printf(NORMAL, "Bucket %d -> NULL", i); else log_printf(NORMAL, "Bucket %d -> %p", i, _buckets[i]); } } /** * @brief Constructor generates initial underlying table as a fixed-sized * hash map and initializes concurrency structures. */ template <class K, class V> ParallelHashMap<K,V>::ParallelHashMap(size_t M, size_t L) { /* allocate table */ _table = new FixedHashMap<K,V>(M); _fixed_size = false; /* get number of threads and create concurrency structures */ _num_threads = 1; _num_threads = omp_get_max_threads(); _num_locks = L; _locks = new omp_lock_t[_num_locks]; for (size_t i=0; i<_num_locks; i++) omp_init_lock(&_locks[i]); _announce = new paddedPointer[_num_threads]; for (size_t t=0; t<_num_threads; t++) _announce[t].value = NULL; } /** * @brief Destructor frees memory associated with fixed-sized hash map and * concurrency structures. */ template <class K, class V> ParallelHashMap<K,V>::~ParallelHashMap() { delete _table; delete [] _locks; delete [] _announce; } /** * @brief Determine whether the parallel hash map contains a given key. * @details First the thread accessing the table announces its presence and * which table it is reading. Then the linked list in the bucket * associated with the key is searched without setting any locks * to determine whether the key is present. When the thread has * finished accessing the table, the announcement is reset to NULL. * The announcement ensures that the data in the map is not freed * during a resize until all threads have finished accessing the map. * @param key key to be searched * @return boolean value referring to whether the key is contained in the map */ template <class K, class V> bool ParallelHashMap<K,V>::contains(K& key) { /* get thread ID */ size_t tid = 0; tid = omp_get_thread_num(); /* get pointer to table, announce it will be searched, and ensure consistency */ FixedHashMap<K,V> *table_ptr; do { table_ptr = _table; _announce[tid].value = table_ptr; #pragma omp flush } while (table_ptr != _table); /* see if current table contains the thread */ bool present = table_ptr->contains(key); /* reset table announcement to not searching */ _announce[tid].value = NULL; return present; } /** * @brief Determine the value associated with a given key. * @details This function follows the same algorithm as "contains" except that * the value associated with the searched key is returned. * First the thread accessing the table acquires the lock corresponding * with the associated bucket based on the key. Then the linked list * in the bucket is searched for the key. An exception is thrown if the * key is not found. When the thread has finished accessing the table, * it releases the lock. * @param key key to be searched * @return value associated with the key */ template <class K, class V> V ParallelHashMap<K,V>::at(K& key) { /* If the size is fixed, simply return the value from the fixed hash map */ if (_fixed_size) return _table->at(key); /* get thread ID */ size_t tid = 0; tid = omp_get_thread_num(); /* get pointer to table, announce it will be searched */ FixedHashMap<K,V> *table_ptr; do { table_ptr = _table; _announce[tid].value = table_ptr; #pragma omp flush } while (table_ptr != _table); /* get value associated with the key in the underlying table */ V value = table_ptr->at(key); /* reset table announcement to not searching */ _announce[tid].value = NULL; return value; } /** * @brief Insert a given key/value pair into the parallel hash map. * @details First the underlying table is checked to determine if a resize * should be conducted. Then, the table is checked to see if it * already contains the key. If so, the key/value pair is not inserted * and the function returns. Otherwise, the lock of the associated * bucket is acquired and the key/value pair is added to the bucket. * @param key key of the key/value pair to be inserted * @param value value of the key/value pair to be inserted */ template <class K, class V> void ParallelHashMap<K,V>::insert(K key, V value) { /* check if resize needed */ if (2*_table->size() > _table->bucket_count()) resize(); /* check to see if key is already contained in the table */ if (contains(key)) return; /* get lock hash */ size_t lock_hash = (std::hash<K>()(key) & (_table->bucket_count() - 1)) % _num_locks; /* acquire lock */ omp_set_lock(&_locks[lock_hash]); /* insert value */ _table->insert(key, value); /* release lock */ omp_unset_lock(&_locks[lock_hash]); } /** * @brief Updates the value associated with a key in the parallel hash map. * @details The thread first acquires the lock for the bucket associated with * the key is acquired, then the linked list in the bucket is searched * for the key. If the key is not found, an exception is returned. When * the key is found, the value is updated and the lock is released. * @param key the key of the key/value pair to be updated * @param value the new value for the key/value pair */ template <class K, class V> void ParallelHashMap<K,V>::update(K& key, V value) { /* get lock hash */ size_t lock_hash = (std::hash<K>()(key) & (_table->bucket_count() - 1)) % _num_locks; /* acquire lock */ omp_set_lock(&_locks[lock_hash]); /* insert value */ _table->at(key) = value; /* release lock */ omp_unset_lock(&_locks[lock_hash]); } /** * @brief Insert a given key/value pair into the parallel hash map and return the order number. * @details First the underlying table is checked to determine if a resize * should be conducted. Then, the table is checked to see if it * already contains the key. If so, the key/value pair is not inserted * and the function returns. Otherwise, the lock of the associated * bucket is acquired and the key/value pair is added to the bucket. * @param key key of the key/value pair to be inserted * @param value value of the key/value pair to be inserted * @return order number in which the key/value pair was inserted, -1 if it * already exists */ template <class K, class V> long ParallelHashMap<K,V>::insert_and_get_count(K key, V value) { /* check if resize needed */ if (2*_table->size() > _table->bucket_count()) resize(); /* check to see if key is already contained in the table */ if (contains(key)) return -1; /* get lock hash */ size_t lock_hash = (std::hash<K>()(key) & (_table->bucket_count() - 1)) % _num_locks; /* acquire lock */ omp_set_lock(&_locks[lock_hash]); /* insert value */ long N =_table->insert_and_get_count(key, value); /* release lock */ omp_unset_lock(&_locks[lock_hash]); return N; } /** * @brief Resizes the underlying table to twice its current capacity. * @details In a thread-safe manner, this procedure resizes the underlying * FixedHashMap table to twice its current capacity using locks and the * announce array. First, all locks are set in order to block inserts and * prevent deadlock. A new table is allocated of twice the size and all * key/value pairs from the old table, then the pointer is switched to the * new table and locks are released. Finally the memory needs to be freed. * To prevent threads currently reading the table from encountering * segmentation faults, the resizing threads waits for the announce array * to be free of references to the old table before freeing the memory. */ template <class K, class V> void ParallelHashMap<K,V>::resize() { /* do not resize if fixed size */ if (_fixed_size) return; /* acquire all locks in order */ for (size_t i=0; i<_num_locks; i++) omp_set_lock(&_locks[i]); /* recheck if resize needed */ if (2*_table->size() < _table->bucket_count()) { /* release locks */ for (size_t i=0; i<_num_locks; i++) omp_unset_lock(&_locks[i]); return; } /* allocate new hash map of double the size */ FixedHashMap<K,V> *new_map = new FixedHashMap<K,V>(2*_table->bucket_count()); /* get keys, values, and number of elements */ K *key_list = _table->keys(); V *value_list = _table->values(); /* insert key/value pairs into new hash map */ for (size_t i=0; i<_table->size(); i++) new_map->insert(key_list[i], value_list[i]); /* save pointer of old table */ FixedHashMap<K,V> *old_table = _table; /* reassign pointer */ _table = new_map; #pragma omp flush /* release all locks */ for (size_t i=0; i<_num_locks; i++) omp_unset_lock(&_locks[i]); /* delete key and value list */ delete [] key_list; delete [] value_list; /* wait for all threads to stop reading from the old table */ for (size_t i=0; i<_num_threads; i++) { while (_announce[i].value == old_table) { #pragma omp flush continue; } } /* free memory associated with old table */ delete old_table; } /** * @brief Returns the number of key/value pairs in the underlying table. * @return number of key/value pairs in the map */ template <class K, class V> size_t ParallelHashMap<K,V>::size() { return _table->size(); } /** * @brief Returns the number of buckets in the underlying table. * @return number of buckets in the map */ template <class K, class V> size_t ParallelHashMap<K,V>::bucket_count() { return _table->bucket_count(); } /** * @brief Returns the number of locks in the parallel hash map. * @return number of locks in the map */ template <class K, class V> size_t ParallelHashMap<K,V>::num_locks() { return _num_locks; } /** * @brief Returns an array of the keys in the underlying table. * @details All buckets are scanned in order to form a list of all keys * present in the table and then the list is returned. Threads * announce their presence to ensure table memory is not freed * during access. WARNING: The user is responsible for freeing the * allocated memory once the array is no longer needed. * @return an array of keys in the map whose length is the number of key/value * pairs in the table. */ template <class K, class V> K* ParallelHashMap<K,V>::keys() { /* get thread ID */ size_t tid = 0; tid = omp_get_thread_num(); /* get pointer to table, announce it will be searched */ FixedHashMap<K,V> *table_ptr; do { table_ptr = _table; _announce[tid].value = table_ptr; #pragma omp flush } while (table_ptr != _table); /* get key list */ K* key_list = table_ptr->keys(); /* reset table announcement to not searching */ _announce[tid].value = NULL; return key_list; } /** * @brief Returns an array of the values in the underlying table. * @details All buckets are scanned in order to form a list of all values * present in the table and then the list is returned. Threads * announce their presence to ensure table memory is not freed * during access. WARNING: The user is responsible for freeing the * allocated memory once the array is no longer needed. * @return an array of values in the map whose length is the number of key/value * pairs in the table. */ template <class K, class V> V* ParallelHashMap<K,V>::values() { /* get thread ID */ size_t tid = 0; tid = omp_get_thread_num(); /* get pointer to table, announce it will be searched */ FixedHashMap<K,V> *table_ptr; do { table_ptr = _table; _announce[tid].value = table_ptr; #pragma omp flush } while (table_ptr != _table); /* get value list */ V* value_list = table_ptr->values(); /* reset table announcement to not searching */ _announce[tid].value = NULL; return value_list; } /** * @brief Prevents the parallel hash map from further resizing. */ template <class K, class V> void ParallelHashMap<K,V>::setFixedSize() { _fixed_size = true; } /** * @brief Clears all key/value pairs form the hash table. */ template <class K, class V> void ParallelHashMap<K,V>::clear() { /* acquire all locks in order */ for (size_t i=0; i<_num_locks; i++) omp_set_lock(&_locks[i]); /* clear underlying fixed table */ _table->clear(); /* release all locks in order */ for (size_t i=0; i<_num_locks; i++) omp_unset_lock(&_locks[i]); } /** * @brief Prints the contents of each bucket to the screen. * @details All buckets are scanned and the contents of the buckets are * printed, which are pointers to linked lists. If the pointer is NULL * suggesting that the linked list is empty, NULL is printed to the * screen. Threads announce their presence to ensure table memory is * not freed during access. */ template <class K, class V> void ParallelHashMap<K,V>::print_buckets() { /* get thread ID */ size_t tid = 0; tid = omp_get_thread_num(); /* get pointer to table, announce it will be searched */ FixedHashMap<K,V> *table_ptr; do { table_ptr = _table; _announce[tid].value = table_ptr; #pragma omp flush } while (table_ptr != _table); /* print buckets */ table_ptr->print_buckets(); /* reset table announcement to not searching */ _announce[tid].value = NULL; } /** * @brief Reallocates the underlying table to the desired size. * @param M The requested new size */ template <class K, class V> void ParallelHashMap<K,V>::realloc(size_t M) { /* delete old table */ delete _table; /* allocate new table */ _table = new FixedHashMap<K,V>(M); } #endif
AI-Pranto/OpenMOC
src/CPULSSolver.h
/** * @file CPULSSolver.h * @brief The CPULSSolver class. * @date February 19, 2016 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef CPULSSOLVER_H_ #define CPULSSOLVER_H_ #ifdef __cplusplus #define _USE_MATH_DEFINES #include "CPUSolver.h" #include <math.h> #include <omp.h> #include <stdlib.h> #endif /** Indexing macro for the scalar flux in each FSR and energy group */ #define _scalar_flux_xyz(r,e,x) (_scalar_flux_xyz[(r)*_num_groups*3 + (x)*_num_groups + (e)]) /** Indexing macro for the total source divided by the total cross-section * (\f$ \frac{Q}{\Sigma_t} \f$) in each FSR and energy group */ #define _reduced_sources_xyz(r,e,x) (_reduced_sources_xyz[(r)*_num_groups*3 + (x)*_num_groups + (e)]) /** Indexing macro for the stabilizing scalar flux moments in each FSR and * energy group */ #define _stabilizing_flux_xyz(r,e,x) (_stabilizing_flux_xyz[(r)*_num_groups*3 + (e)*3 + (x)]) /** Indexing scheme for fixed source moments for each FSR and energy group */ #define _fixed_sources_xyz(r,e,i) (_fixed_sources_xyz[(r)*_num_groups + (e)][i]) /** * @class CPULSSolver CPULSSolver.h "src/CPULSSolver.h" * @brief This a subclass of the CPUSolver class for using the linear source * approximation. */ class CPULSSolver : public CPUSolver { protected: /** The FSR linear expansion matrix values for each FSR */ double* _FSR_lin_exp_matrix; /** The FSR source constants for each FSR and energy group */ FP_PRECISION* _FSR_source_constants; /** An array of the scalar flux x, y, and z terms */ FP_PRECISION* _scalar_flux_xyz; /** An array of the reduced source x, y, and z terms */ FP_PRECISION* _reduced_sources_xyz; /** The stabilizing flux for each energy group in each FSR */ FP_PRECISION* _stabilizing_flux_xyz; /** Optional user-specified fixed linear source in each FSR & energy group */ std::vector<std::vector<double> > _fixed_sources_xyz; /** A map of fixed sources moments keyed by the pair (FSR ID, energy group) */ std::map< std::pair<int, int>, std::vector<double> > _fix_src_xyz_FSR_map; /** A map of fixed sources moments keyed by the pair (Cell*, energy group) */ std::map< std::pair<Cell*, int>, std::vector<double> > _fix_src_xyz_cell_map; /** Whether to stabilize the flux moments */ bool _stabilize_moments; /** Whether fixed linear source moments have been provided */ bool _fixed_source_moments_on; public: CPULSSolver(TrackGenerator* track_generator=NULL); virtual ~CPULSSolver(); /* Initialization routines */ void initializeFluxArrays(); void initializeSourceArrays(); void initializeCmfd(); void initializeExpEvaluators(); void initializeFSRs(); /* Routines to handle fixed source moments */ void initializeFixedSources(); void setFixedSourceMomentsByCell(Cell* cell, int group, double source_x, double source_y, double source_z); void setFixedSourceMomentByFSR(long fsr_id, int group, double source_x, double source_y, double source_z); void resetFixedSources(); /* Worker routines */ void flattenFSRFluxes(FP_PRECISION value); double normalizeFluxes(); void computeFSRSources(int iteration); void tallyLSScalarFlux(segment* curr_segment, int azim_index, int polar_index, FP_PRECISION* fsr_flux, FP_PRECISION* fsr_flux_x, FP_PRECISION* fsr_flux_y, FP_PRECISION* fsr_flux_z, float* track_flux, FP_PRECISION direction[3]); void accumulateLinearFluxContribution(long fsr_id, FP_PRECISION weight, FP_PRECISION* fsr_flux); void addSourceToScalarFlux(); /* Transport stabilization routines */ void computeStabilizingFlux(); void stabilizeFlux(); void checkLimitXS(int iteration); /* Routines to handle constant part of linear source */ void initializeLinearSourceConstants(); double* getLinearExpansionCoeffsBuffer(); FP_PRECISION* getSourceConstantsBuffer(); /* Getter routine */ FP_PRECISION getFluxByCoords(LocalCoords* coords, int group); }; #endif /* CPULSSOLVER_H_ */
AI-Pranto/OpenMOC
src/TraverseSegments.h
/** * @file TraverseSegments.h * @brief A TraverseSegments object * @date February 15, 2016 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef TRAVERSE_SEGMENTS_H_ #define TRAVERSE_SEGMENTS_H_ #ifdef SWIG #include "Python.h" #endif #include "Track.h" #include "Track3D.h" #include "Geometry.h" #include "TrackGenerator3D.h" /** * @class TraverseSegments TraverseSegments.h "src/TraverseSegments.h" * @brief An TraverseSegments object defines how to loop over Tracks given * various different segmentation schemes and how to apply algorithms * to the Tracks and associated segments. * @details A TraverseSegments object sketches how to loop over Tracks for * various different segmentation schemes such as 2D explicit, 3D * explicit, and on-the-fly ray tracing. A TraverseSegments object * is an abstract class meant to be extended by classes defined in * TrackTraversingAlgorithms.h. This parent class's main purpose is to * abstract the looping procedure and apply a function onTrack(...) to * each Track and apply the supplied MOCKernel to each segment. If * NULL is provided for the MOCKernel, only the functionality defined * in onTrack(...) is applied to each Track. */ class TraverseSegments { private: /* Functions defining how to loop over Tracks */ void loopOverTracks2D(MOCKernel* kernel); void loopOverTracksExplicit(MOCKernel* kernel); void loopOverTracksByTrackOTF(MOCKernel* kernel); void loopOverTracksByStackOTF(MOCKernel* kernel); /* Functions defining how to traverse segments */ void traceSegmentsExplicit(Track* track, MOCKernel* kernel); void traceSegmentsOTF(Track* flattened_track, Point* start, double theta, MOCKernel* kernel); void traceStackOTF(Track* flattened_track, int polar_index, MOCKernel* kernel); void traceStackTwoWay(Track* flattened_track, int polar_index, TransportKernel* kernel); int findMeshIndex(double* values, int size, double val, int sign); protected: /** Pointer to the associated TrackGenerator */ TrackGenerator* _track_generator; TrackGenerator3D* _track_generator_3D; /** A pointer to the associated global z-mesh (if applicable) */ double* _global_z_mesh; /** The size of the global z-mesh */ int _mesh_size; /** The type of segmentation used for segment formation */ segmentationType _segment_formation; TraverseSegments(TrackGenerator* track_generator); virtual ~TraverseSegments(); /* Functions defining how to loop over and operate on Tracks */ void loopOverTracks(MOCKernel* kernel); virtual void onTrack(Track* track, segment* segments) = 0; //FIXME Rework function calls to make this private void loopOverTracksByStackTwoWay(TransportKernel* kernel); /* Returns a kernel of the requested type */ template <class KernelType> MOCKernel* getKernel() { /* Check for segmentation kernel in explicit methods */ if ((typeid(KernelType) != typeid(SegmentationKernel)) || ((_segment_formation != EXPLICIT_2D) && (_segment_formation != EXPLICIT_3D))) { /* Allocate kernel */ MOCKernel* kernel = new KernelType(_track_generator); return kernel; } else return NULL; } public: virtual void execute() = 0; }; #endif
AI-Pranto/OpenMOC
src/accel/cuda/dev_exponential.h
/** * Compute exponentials on the GPU using some of <NAME>'s finest work. */ #pragma once /* Coefficients for numerator */ __device__ const FP_PRECISION p0 = 1.0; __device__ const FP_PRECISION p1 = 2.4172687328033081 * 1E-1; __device__ const FP_PRECISION p2 = 6.2804790965268531 * 1E-2; __device__ const FP_PRECISION p3 = 1.0567595009016521 * 1E-2; __device__ const FP_PRECISION p4 = 1.0059468082903561 * 1E-3; __device__ const FP_PRECISION p5 = 1.9309063097411041 * 1E-4; /* Coefficients for denominator */ __device__ const FP_PRECISION d0 = 1.0; __device__ const FP_PRECISION d1 = 7.4169266112320541 * 1E-1; __device__ const FP_PRECISION d2 = 2.6722515319494311 * 1E-1; __device__ const FP_PRECISION d3 = 6.1643725066901411 * 1E-2; __device__ const FP_PRECISION d4 = 1.0590759992367811 * 1E-2; __device__ const FP_PRECISION d5 = 1.0057980007137651 * 1E-3; __device__ const FP_PRECISION d6 = 1.9309063097411041 * 1E-4; /** * @brief Computes the exponential term for a optical length and polar angle. * @details This method computes \f$ 1 - exp(-x) \f$ * for some optical path length and polar angle. Uses the rational approximation of Josey from exponentials.h, but using device constants. * @param tau the optical path length (e.g., sigma_t times length) * @param polar the polar angle index * @return the evaluated exponential */ __forceinline__ __device__ FP_PRECISION dev_exponential(FP_PRECISION x) { FP_PRECISION exponential; FP_PRECISION num, den; den = d6*x + d5; den = den*x + d4; den = den*x + d3; den = den*x + d2; den = den*x + d1; den = den*x + d0; den = d0 / den; num = p5*x + p4; num = num*x + p3; num = num*x + p2; num = num*x + p1; num = num*x + p0; // TODO Redo fractional approximation for 1-exp(-x) rather than (1-exp(-x))/x exponential = num * den * x; return exponential; }
AI-Pranto/OpenMOC
src/Region.h
<reponame>AI-Pranto/OpenMOC /** * @file Region.h * @brief The Region class. * @date March 10, 2017 * @author <NAME>, MIT, Course 22 (<EMAIL>) */ #ifndef REGION_H_ #define REGION_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "Surface.h" #include "boundary_type.h" #include <limits> #endif /* Forward declarations to resolve circular dependencies */ class Intersection; class Union; class Complement; class Halfspace; /** * @enum regionType * @brief The types of regions supported by OpenMOC. */ enum regionType { /** The intersection of one or more regions */ INTERSECTION, /** The union of one or more regions */ UNION, /** The complement of a region */ COMPLEMENT, /** The side of a surface */ HALFSPACE }; /** * @class Region Region.h "src/Region.h" * @brief A region of space that can be assigned to a Cell. */ class Region { protected: /** The type of Region (ie, UNION, INTERSECTION, etc) */ regionType _region_type; /** A collection of the nodes within the Region */ std::vector<Region*> _nodes; /** The parent region, a region which has this region among its nodes */ Region* _parent_region; public: Region(); virtual ~Region(); /* Functions for constructing the Region / other Regions */ virtual void addNode(Region* node, bool clone=true); void removeHalfspace(Surface* surface, int halfspace); regionType getRegionType(); void setParentRegion(Region* node); Region* getParentRegion(); /* Getter functions */ virtual std::vector<Region*> getNodes(); virtual std::vector<Region*> getAllNodes(); virtual std::map<int, Halfspace*> getAllSurfaces(); /* Worker functions */ virtual double getMinX(); virtual double getMaxX(); virtual double getMinY(); virtual double getMaxY(); virtual double getMinZ(); virtual double getMaxZ(); virtual boundaryType getMinXBoundaryType(); virtual boundaryType getMaxXBoundaryType(); virtual boundaryType getMinYBoundaryType(); virtual boundaryType getMaxYBoundaryType(); virtual boundaryType getMinZBoundaryType(); virtual boundaryType getMaxZBoundaryType(); virtual bool containsPoint(Point* point) =0; virtual double minSurfaceDist(LocalCoords* coords); virtual double minSurfaceDist(Point* point, double azim, double polar=M_PI_2); virtual Region* clone(); }; /** * @class Intersection Region.h "src/Region.h" * @brief An intersection of two or more Regions. */ class Intersection : public Region { public: Intersection(); bool containsPoint(Point* point); }; /** * @class Union Region.h "src/Region.h" * @brief A union of two or more Regions. */ class Union : public Region { public: Union(); bool containsPoint(Point* point); }; /** * @class Complement Region.h "src/Region.h" * @brief A complement of a Region. */ class Complement : public Region { public: Complement(); void addNode(Region* node, bool clone=true); bool containsPoint(Point* point); }; /** * @class Halfspace Region.h "src/Region.h" * @brief A positive or negative halfspace Region. */ class Halfspace : public Region { public: /** A pointer to the Surface object */ Surface* _surface; /** The halfspace associated with this surface */ int _halfspace; Halfspace(int halfspace, Surface* surface); Halfspace* clone(); Surface* getSurface(); int getHalfspace(); void reverseHalfspace(); std::map<int, Halfspace*> getAllSurfaces(); double getMinX(); double getMaxX(); double getMinY(); double getMaxY(); double getMinZ(); double getMaxZ(); boundaryType getMinXBoundaryType(); boundaryType getMaxXBoundaryType(); boundaryType getMinYBoundaryType(); boundaryType getMaxYBoundaryType(); boundaryType getMinZBoundaryType(); boundaryType getMaxZBoundaryType(); bool containsPoint(Point* point); double minSurfaceDist(LocalCoords* coords); double minSurfaceDist(Point* point, double azim, double polar=M_PI_2); }; /** * @class RectangularPrism Region.h "src/Region.h" * @brief An infinite rectangular prism aligned with the z-axis. */ class RectangularPrism : public Intersection { public: RectangularPrism(double width_x, double width_y, double origin_x=0., double origin_y=0., double width_z=3E300, double origin_z=0.); void setBoundaryType(boundaryType boundary_type); }; #endif /* REGION_H_ */
AI-Pranto/OpenMOC
src/Track3D.h
/** * @file Track3D.h * @brief The 3D Track class. * @date May 9, 2015 * @author <NAME>, MIT Course, 22 (<EMAIL>) */ #ifndef TRACK3D_H_ #define TRACK3D_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "Point.h" #include "Material.h" #include "Track.h" #include "Track.h" #include "LocalCoords.h" #include <vector> #endif /** Forward declaration of ExtrudedFSR struct */ struct ExtrudedFSR; /** * @class Track3D Track3D.h "src/Track3D.h" * @brief A 3D Track represents a characteristic line across the geometry. * @details A 3D Track has particular starting and ending points on the * boundaries of the geometry and an azimuthal and polar angle. */ class Track3D : public Track { protected: /** The polar angle for the Track */ double _theta; /* Indices that are used to locate the track in the various track arrays */ int _polar_index; int _z_index; int _lz_index; int _cycle_index; int _cycle_track_index; int _train_index; /** Boolean to indicate whether track is in the same direction as the * reflective track cycle. */ bool _cycle_fwd; public: Track3D(); virtual ~Track3D(); /* Setter methods */ void setValues(const double start_x, const double start_y, const double start_z, const double end_x, const double end_y, const double end_z, const double phi, const double theta); void setTheta(const double theta); void setCoords(double x0, double y0, double z0, double x1, double y1, double z1); void setPolarIndex(int index); void setZIndex(int index); void setLZIndex(int index); void setCycleIndex(int index); void setCycleTrackIndex(int index); void setTrainIndex(int index); void setCycleFwd(bool fwd); /* Getter methods */ double getTheta() const; int getPolarIndex(); int getZIndex(); int getLZIndex(); int getCycleIndex(); int getCycleTrackIndex(); int getTrainIndex(); bool getCycleFwd(); /* Worker methods */ std::string toString(); }; #endif /* TRACK3D_H_ */
AI-Pranto/OpenMOC
src/Track.h
/** * @file Track.h * @brief The generic Track class. * @date May 16, 2015 * @author <NAME>, MIT Course, 22 (<EMAIL>) */ #ifndef TRACK_H_ #define TRACK_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "Point.h" #include "Material.h" #include "boundary_type.h" #include <vector> #include <algorithm> #endif /** * @struct segment * @brief A segment represents a line segment within a single flat source * region along a track. */ struct segment { /** The length of the segment (cm) */ double _length; /** A pointer to the material in which this segment resides */ Material* _material; /** The ID for flat source region in which this segment resides */ int _region_id; /** The ID of the track */ int _track_idx; /** The ID for the mesh surface crossed by the Track end point */ int _cmfd_surface_fwd; /** The ID for the mesh surface crossed by the Track start point */ int _cmfd_surface_bwd; /** The starting point of the segment relative to the FSR centroid */ FP_PRECISION _starting_position[3]; /** Constructor initializes CMFD surfaces and segment Z-coordinate */ segment() { _track_idx = 0; _material = NULL; _cmfd_surface_fwd = -1; _cmfd_surface_bwd = -1; _starting_position[2] = 0.; } }; /** * @class Track Track.h "src/Track.h" * @brief A Track represents a characteristic line across the geometry. * @details A Track has particular starting and ending points on the * boundaries of the geometry and an azimuthal and polar angle. */ class Track { protected: /** A monotonically increasing unique ID for each Track created */ int _uid; /** The Track's start point */ Point _start; /** The Track's end point */ Point _end; /** The azimuthal angle for the Track */ double _phi; /** A dynamically sized vector of segments making up this Track */ std::vector<segment> _segments; /** Number of segments recorded during volume calculation */ int _num_segments; /** An enum to indicate whether the outgoing angular flux along this * Track's "forward" direction should be zeroed out for vacuum boundary * conditions or sent to a periodic or reflective track. */ boundaryType _bc_fwd; /** An enum to indicate whether the outgoing angular flux along this * Track's "reverse" direction should be zeroed out for vacuum boundary * conditions or sent to a periodic or reflective track. */ boundaryType _bc_bwd; /* Indices that are used to locate the track in the various track arrays */ int _azim_index; int _xy_index; int _link_index; /** Pointers to next, reflective, and periodic Tracks in the forward and * reverse directions */ long _track_next_fwd; long _track_next_bwd; long _track_prdc_fwd; long _track_prdc_bwd; long _track_refl_fwd; long _track_refl_bwd; /** Booleans to indicate wheter the reflective Tracks in the forward and * and backward direction enter into Tracks pointed in the forward * direction. */ bool _next_fwd_fwd; bool _next_bwd_fwd; /** Boolean indicating whether the track is pointing fwd (True) or bwd * (False) in the cycle of tracks */ //FIXME bool _direction_in_cycle; /** Surfaces at the beginning and end of the Track */ int _surface_in; int _surface_out; /** Domains further along and before the current domain on this Track */ int _domain_fwd; int _domain_bwd; public: Track(); virtual ~Track(); /* Setter methods */ virtual void setValues(const double start_x, const double start_y, const double end_x, const double end_y, const double phi); virtual void setCoords(double x0, double y0, double x1, double y1); void setUid(int uid); void setPhi(const double phi); void setBCFwd(const boundaryType bc_fwd); void setBCBwd(const boundaryType bc_bwd); void setTrackNextFwd(long track_id); void setTrackNextBwd(long track_id); void setTrackPrdcFwd(long track_id); void setTrackPrdcBwd(long track_id); void setTrackReflFwd(long track_id); void setTrackReflBwd(long track_id); void setNextFwdFwd(bool fwd); void setNextBwdFwd(bool fwd); void setXYIndex(int index); void setAzimIndex(int index); void setSurfaceIn(int surface_in); void setSurfaceOut(int surface_out); void setDomainFwd(int neighbor); void setDomainBwd(int neighbor); void setLinkIndex(int index); /* Getter methods */ int getUid(); Point* getEnd(); Point* getStart(); double getPhi() const; double getLength(); long getTrackNextFwd(); long getTrackNextBwd(); long getTrackPrdcFwd(); long getTrackPrdcBwd(); long getTrackReflFwd(); long getTrackReflBwd(); bool getNextFwdFwd(); bool getNextBwdFwd(); int getXYIndex(); int getAzimIndex(); int getLinkIndex(); boundaryType getBCFwd() const; boundaryType getBCBwd() const; segment* getSegment(int s); segment* getSegments(); int getNumSegments(); int getDomainFwd(); int getDomainBwd(); int getSurfaceIn(); int getSurfaceOut(); /* Worker methods */ void addSegment(segment* segment); void removeSegment(int index); void insertSegment(int index, segment* segment); void clearSegments(); void setNumSegments(int num_segments); virtual std::string toString(); }; /** * @brief Return the Track's unique ID. * @return the Track's unique ID */ inline int Track::getUid() { return _uid; } /** * @brief Returns a pointer to a segment with a given index. * @details Returns a pointer to the segment or ends program if Track does * not have the requested segment. * @param segment index into the Track's segments container * @return a pointer to the requested segment */ inline segment* Track::getSegment(int segment) { /* If Track doesn't contain this segment, exits program */ if (segment >= (int)_segments.size()) log_printf(ERROR, "Attempted to retrieve segment s = %d but Track only " "has %d segments", segment, _segments.size()); return &_segments[segment]; } /** * @brief Returns a vector of pointers to the Track's segments. * @return vector of segment pointers */ inline segment* Track::getSegments() { return &_segments[0]; } /** * @brief Return the number of segments along this Track. * @return the number of segments */ inline int Track::getNumSegments() { if (_num_segments == 0) return _segments.size(); else return _num_segments; } /** * @brief Sets the number of segments in a track. * @details This function sets the number of segments in a track. It's purpose * is to be used for 3D tracks with on-the-fly ray tracing where * segments are not explicitly created, but there is a need to know * how many segments exist. */ inline void Track::setNumSegments(int num_segments) { _num_segments = num_segments; } /** * @brief Returns a pointer to the Track's end Point. * @return A pointer to the Track's end Point */ inline Point* Track::getEnd() { return &_end; } /** * @brief Returns a pointer to the Track's start Point. * @return A pointer to the Track's start Point */ inline Point* Track::getStart() { return &_start; } /** * @brief Return the Track's azimuthal angle (with respect to the x-axis). * @return The azimuthal angle \f$ \phi \in [0, \pi] \f$ */ inline double Track::getPhi() const { return _phi; } /** * @brief Returns the boundary condition for the flux along the Track's * "forward" direction. * @return vacuum (0), reflective (1), or periodic (2) boundary conditions */ inline boundaryType Track::getBCFwd() const { return _bc_fwd; } /** * @brief Returns the boundary condition for the flux along the Track's * "reverse" direction. * @return vacuum (0), reflective (1), or periodic (2) boundary conditions */ inline boundaryType Track::getBCBwd() const { return _bc_bwd; } #endif /* TRACK_H_ */
cordella/MOS6581_t
MOS6581_p.h
<reponame>cordella/MOS6581_t #ifndef MOS6581_P_H #define MOS6581_P_H #include <Arduino.h> #include "MOS6581_t.h" class MOS6581_p: public MOS6581_t { /* Parallel implementation of SID control; microcontroller pins connect in parallel to SID address * and data pins, possibly in combination with other chips on a bus. */ private: /* The parallel address-select pins that control which of the SID's registers to write to or read from. * Pin order: A0, A1, A2, A3, A4 */ byte ADDR[ADDR_PIN_COUNT]; /* The parallel data pins used to write to or read from the selected register. * Pin order: D0, D1, D2, D3, D4, D5, D6, D7 */ byte DATA[DATA_PIN_COUNT]; public: MOS6581_p(const byte address_pins[ADDR_PIN_COUNT], const byte data_pins[DATA_PIN_COUNT], byte _cs_pin, byte r_w_pin); /* Writes the address pins to the address provided. * The MSB is A4, the LSB is A0. */ void select_register(registers_t address); /* Writes the data pins with the data provided. * The MSB is D7, the LSB is D0. */ void write_data_pins(byte value); /* Reads the data pins of the current register. * The MSB is D7, the LSB is D0. */ byte read_data_pins(); }; #endif
cordella/MOS6581_t
MOS6581_t.h
<gh_stars>1-10 #ifndef MOS6581_T_H #define MOS6581_T_H #include <Arduino.h> class MOS6581_t { /* Base class for the SID, holds all information common to both parallel and serial implementations. */ protected: byte last_address, last_write, last_read; byte O2; public: /* Parallel pin counts. */ static const byte ADDR_PIN_COUNT = 5; static const byte DATA_PIN_COUNT = 8; enum registers_t {v1_freq_lo, v1_freq_hi, v1_pw_lo, v1_pw_hi, v1_control, v1_ad, v1_sr, v2_freq_lo, v2_freq_hi, v2_pw_lo, v2_pw_hi, v2_control, v2_ad, v2_sr, v3_freq_lo, v3_freq_hi, v3_pw_lo, v3_pw_hi, v3_control, v3_ad, v3_sr, filter_fc_lo, filter_fc_hi, filter_res_filt, filter_mode_vol, misc_potx, misc_poty, misc_osc3_random, misc_env3, }; /* The chip select pin, which must be low in order to interface with the SID's registers. */ const byte _CS; /* Operation select pin. Read is HIGH, Write is LOW. */ const byte R_W; MOS6581_t(byte _cs_pin, byte r_w_pin); /* Accessor method for the stored address. */ byte get_last_address() const; /* Accessor method for the stored last write. */ byte get_last_write() const; /* Accessor method for the stored last read. */ byte get_last_read() const; /* Writes the address pins with the bits of `address`. * Implemented by subclasses. */ virtual void select_register(registers_t address); /* Writes the data pins with the bits of `value`. * Implemented by subclasses. */ virtual void write_data_pins(byte value); /* Returns the values read on the data pins as an unsigned eight bit field. * Implemented by subclasses. */ virtual byte read_data_pins(); /* Implementation of the PEEK command from BASIC. * Returns the contents of the register at `address`. */ byte PEEK(registers_t address); /* Implementation of the POKE command from BASIC. * Writes the register at `address` with the data `value`. */ void POKE(registers_t address, byte value); /* Generates a 1 MHz clock signal for the SID using AVR's hardware timers. * Returns 0 if successful or `o2_pin` if not. * Valid values of `o2_pin`: 3, 9, 10, 11 * * (These pins are only valid for the ATmega168/328. On these versions of Arduino, * pins 9 and 10 use Timer1, 3 and 11 use Timer2. Pin 11 is also used by the ICSP header. * Keep these in mind if using other libraries or an external programmer.) */ byte start_clock(byte o2_pin); // byte start_clock(byte o2_pin, byte timer); }; #endif
cordella/MOS6581_t
MOS6581_s.h
#ifndef MOS6581_S_H #define MOS6581_S_H #include <Arduino.h> #include "MOS6581_t.h" #endif
pranavyeola/Hacktoberfest2020
c codes/elevator.c
<reponame>pranavyeola/Hacktoberfest2020<gh_stars>1-10 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> struct node { int data; struct node *next; struct node *prev; }; //this link always point to first Link struct node *head = NULL; //this link always point to last Link struct node *last = NULL; struct node *current = NULL; //is list empty bool isEmpty() { return head == NULL; } int length() { int length = 0; // struct node *current; for(current = head; current != NULL; current = current->next){ length++; } return length; } //display the list in from first to last void displayForward() { //start from the beginning struct node *ptr = head; //navigate till the end of the list printf("\n "); while(ptr != NULL) { printf("%d",ptr->data); ptr = ptr->next; } } //insert link at the last location void insertLast(int data) { //create a link struct node *link = (struct node*) malloc(sizeof(struct node)); //link->key = key; link->data = data; if(isEmpty()) { head=link;//make it the last link last = link; } else { //make link a new last link last->next = link; //mark old last node as prev of new link link->prev = last; } //point last to new last node last = link; } int elevator(int floor) { int i; //struct node*current; if(current->data==floor) printf("you are already at floor %d",floor); else if((current->data)<=floor) { current=current->next; for(i=current->data;i<=floor;i++) { if(i==floor) { printf("\n\tYou reached at Floor %d",i); return 1;//indicating that elevator is going up; } else printf("\n\tGoing up to floor %d",i); current=current->next; } } else if((current->data)>floor) { current=current->prev; for(i=(current->data);i>=floor;i--) { if(i==floor) { printf("\n\t You reached at Floor %d",i); return 0;//indicating that elevator is going up; } else printf("\n\tGoing down to floor %d",i); if((current->data) > (head->data)) current=(current->prev); } } } void ascsort(int floor[],int inputs) { int i,j,swap; for (i = 0 ; i < inputs-1; i++) { for (j = 0 ;j<inputs-i-1; j++) { if (floor[j] > floor[j+1]) /* For decreasing order use < */ { swap = floor[j]; floor[j] = floor[j+1]; floor[j+1] = swap; } } } } void descsort(int floor[],int inputs) { int i,j,swap; for (i = 0 ; i < inputs-1; i++) { for (j = 0 ;j<inputs-i-1; j++) { if (floor[j] < floor[j+1]) { swap = floor[j]; floor[j] = floor[j+1]; floor[j+1] = swap; } } } } void main() { int n,k,l,floor[8],inputs,dir,i,j,swap,flag=0,arr[8],brr[8];//people capacity char ch; printf("\n\t Enter how many floors"); scanf("%d",&n); for(i=0;i<=n;i++) insertLast(i); displayForward(); printf("\n\tAt start elevator is at ground Floor"); do{ while(1) { printf("\n\tEnter how many inputs(max capacity is 8)"); scanf("%d",&inputs); if(inputs<=8 && inputs>0) break; } for(i=0;i<inputs;i++) { while(1) { printf("Enter input %d",i+1); scanf("%d",&floor[i]); if(floor[i]<=n && floor[i]>=0) break; } } if(flag==0) { ascsort(floor,inputs); current=head; for(i=0;i<inputs;i++) dir=elevator(floor[i]); flag=1; } else if(flag==1) { int j=0,l=0; if(dir==1) { for(i=0;i<inputs;i++) { if(floor[i]>current->data) { arr[j]=floor[i]; j++; } else { brr[l]=floor[i]; l++; } } ascsort(arr,j); descsort(brr,l); for(i=0;i<j;i++) { dir=elevator(arr[i]); } for(i=0;i<l;i++) { dir=elevator(brr[i]); } } else if(dir==0) { j=0,l=0; for(i=0;i<inputs;i++) { if(floor[i]<current->data) { arr[j]=floor[i]; j++; } else { brr[l]=floor[i]; l++; } } descsort(arr,j); ascsort(brr,l); for(i=0;i<j;i++) { dir=elevator(arr[i]); } for(i=0;i<l;i++) { dir=elevator(brr[i]); } } } printf("\n\t Do you want to continue..press(y/n)"); ch=getchar(); ch=getchar(); }while(ch=='y'); }
zrora/DistributedNAS
BUSE/busexmp.c
<gh_stars>0 /* * busexmp - example memory-based block device using BUSE * Copyright (C) 2013 <NAME> * * This program 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <argp.h> #include <err.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "buse.h" /* BUSE callbacks */ static void *data; static int xmp_read(void *buf, u_int32_t len, u_int64_t offset, void *userdata) { if (*(int *)userdata) { fprintf(stderr, "R - %lu, %u\n", offset, len); } memcpy(buf, (char *)data + offset, len); return 0; } static int xmp_write(const void *buf, u_int32_t len, u_int64_t offset, void *userdata) { if (*(int *)userdata) { fprintf(stderr, "W - %lu, %u\n", offset, len); } memcpy((char *)data + offset, buf, len); return 0; } static void xmp_disc(void *userdata) { if (*(int *)userdata) { fprintf(stderr, "Received a disconnect request.\n"); } } static int xmp_flush(void *userdata) { if (*(int *)userdata) { fprintf(stderr, "Received a flush request.\n"); } return 0; } static int xmp_trim(u_int64_t from, u_int32_t len, void *userdata) { if (*(int *)userdata) { fprintf(stderr, "T - %lu, %u\n", from, len); } return 0; } /* argument parsing using argp */ static struct argp_option options[] = { {"verbose", 'v', 0, 0, "Produce verbose output", 0}, {0}, }; struct arguments { unsigned long long size; char * device; int verbose; }; static unsigned long long strtoull_with_prefix(const char * str, char * * end) { unsigned long long v = strtoull(str, end, 0); switch (**end) { case 'K': v *= 1024; *end += 1; break; case 'M': v *= 1024 * 1024; *end += 1; break; case 'G': v *= 1024 * 1024 * 1024; *end += 1; break; } return v; } /* Parse a single option. */ static error_t parse_opt(int key, char *arg, struct argp_state *state) { struct arguments *arguments = state->input; char * endptr; switch (key) { case 'v': arguments->verbose = 1; break; case ARGP_KEY_ARG: switch (state->arg_num) { case 0: arguments->size = strtoull_with_prefix(arg, &endptr); if (*endptr != '\0') { /* failed to parse integer */ errx(EXIT_FAILURE, "SIZE must be an integer"); } break; case 1: arguments->device = arg; break; default: /* Too many arguments. */ return ARGP_ERR_UNKNOWN; } break; case ARGP_KEY_END: if (state->arg_num < 2) { warnx("not enough arguments"); argp_usage(state); } break; default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = { .options = options, .parser = parse_opt, .args_doc = "SIZE DEVICE", .doc = "BUSE virtual block device that stores its content in memory.\n" "`SIZE` accepts suffixes K, M, G. `DEVICE` is path to block device, for example \"/dev/nbd0\".", }; int main(int argc, char *argv[]) { struct arguments arguments = { .verbose = 0, }; argp_parse(&argp, argc, argv, 0, 0, &arguments); struct buse_operations aop = { .read = xmp_read, .write = xmp_write, .disc = xmp_disc, .flush = xmp_flush, .trim = xmp_trim, .size = arguments.size, }; data = malloc(aop.size); if (data == NULL) err(EXIT_FAILURE, "failed to alloc space for data"); return buse_main(arguments.device, &aop, (void *)&arguments.verbose); }
zrora/DistributedNAS
BUSE/loopback.c
<filename>BUSE/loopback.c<gh_stars>1-10 /* * loopback - example loopback device using BUSE * Copyright (C) 2013 <NAME> * * This program 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #define _GNU_SOURCE #define _LARGEFILE64_SOURCE #include <assert.h> #include <fcntl.h> #include <stdio.h> #include <sys/mount.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "buse.h" static int fd; static void usage(void) { fprintf(stderr, "Usage: loopback <phyical device> <virtual device>\n"); } static int loopback_read(void *buf, u_int32_t len, u_int64_t offset, void *userdata) { int bytes_read; (void)(userdata); lseek64(fd, offset, SEEK_SET); while (len > 0) { bytes_read = read(fd, buf, len); assert(bytes_read > 0); len -= bytes_read; buf = (char *) buf + bytes_read; } return 0; } static int loopback_write(const void *buf, u_int32_t len, u_int64_t offset, void *userdata) { int bytes_written; (void)(userdata); lseek64(fd, offset, SEEK_SET); while (len > 0) { bytes_written = write(fd, buf, len); assert(bytes_written > 0); len -= bytes_written; buf = (char *) buf + bytes_written; } return 0; } static struct buse_operations bop = { .read = loopback_read, .write = loopback_write }; int main(int argc, char *argv[]) { struct stat buf; int err; int64_t size; if (argc != 3) { usage(); return -1; } fd = open(argv[1], O_RDWR|O_LARGEFILE); assert(fd != -1); /* Let's verify that this file is actually a block device. We could support * regular files, too, but we don't need to right now. */ fstat(fd, &buf); assert(S_ISBLK(buf.st_mode)); /* Figure out the size of the underlying block device. */ err = ioctl(fd, BLKGETSIZE64, &size); assert(err != -1); (void)err; fprintf(stderr, "The size of this device is %ld bytes.\n", size); bop.size = size; buse_main(argv[2], &bop, NULL); return 0; }
zrora/DistributedNAS
DesignPatterns/Singletone/handleton/myclass.h
<reponame>zrora/DistributedNAS<filename>DesignPatterns/Singletone/handleton/myclass.h #ifndef __SINGLETON_V1_H__ #define __SINGLETON_V1_H__ #include <boost/noncopyable.hpp> #include "handleton.h" namespace ilrd { class MyClass: boost::noncopyable { public: void Print(); private: friend class Handleton<MyClass>; MyClass(); ~MyClass(); }; }//namespace ilrd #endif
zrora/DistributedNAS
DesignPatterns/Singletone/singletonesharedlibrary/handleton.h
#ifndef __HANDLETON_H__ #define __HANDLETON_H__ #include <iostream> #include <unistd.h> #include <stdlib.h> /* Usage: void f(Something &s){...} void letsusesomething() { Handleton<Something> s; s->method(); f(s); } void useitagain() { Handleton<Something> s; s->someothermethod(); } */ #ifdef WIN32 #define NO_STATIC_PRAGMA _Pragma("comment(lib,\"xxx.lib\")") #elif defined(WIN64) #define NO_STATIC_PRAGMA _Pragma("comment(lib,\"xxx.lib\")") #else #define NO_STATIC_PRAGMA _Pragma("message(\"please ensure that \"__FILE__\ \" is compiled into a shared object and not a static library\")") #endif namespace ilrd{ #define Atomic_Or(T,X) __sync_fetch_and_or(T, X) #define IMPLEMENT_SINGLETON(T) \ NO_STATIC_PRAGMA \ template<> \ T *&Handleton<T>::GetInstance() \ { \ static volatile bool sv_isReady=0; \ static volatile int sv_shouldInit=0; \ static T *theObject = 0; \ if(!sv_isReady) \ { \ if(!Atomic_Or(&sv_shouldInit, true)) \ { \ theObject = new T(); \ ::atexit(&Handleton<T>::DestroyInstance); \ Atomic_Or(&sv_isReady,true); \ } \ while(!sv_isReady) \ { \ ::sleep(0); \ } \ } \ return theObject; \ } template <class T> class Handleton { public: Handleton() { GetInstance(); } operator T &() { return *GetInstance(); } operator const T &() const { return *GetInstance(); } T *operator->(){ return GetInstance(); } const T *operator->() const { return GetInstance(); } private: T *&GetInstance(); static void DestroyInstance() { Handleton<T> h; T *ptr = h.GetInstance(); h.GetInstance() = reinterpret_cast<T*>(0xdeadbeef); __sync_synchronize(); delete ptr; } }; }//namespace ilrd #endif
zrora/DistributedNAS
BUSE/buse.h
<reponame>zrora/DistributedNAS<filename>BUSE/buse.h #ifndef BUSE_H_INCLUDED #define BUSE_H_INCLUDED #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> struct buse_operations { int (*read)(void *buf, u_int32_t len, u_int64_t offset, void *userdata); int (*write)(const void *buf, u_int32_t len, u_int64_t offset, void *userdata); void (*disc)(void *userdata); int (*flush)(void *userdata); int (*trim)(u_int64_t from, u_int32_t len, void *userdata); // either set size, OR set both blksize and size_blocks u_int64_t size; u_int32_t blksize; u_int64_t size_blocks; }; int buse_main(const char* dev_file, const struct buse_operations *bop, void *userdata); #ifdef __cplusplus } #endif #endif /* BUSE_H_INCLUDED */
glennsl/reason-sdl2
src/reglfw_image.h
extern "C" { struct ReglfwImageInfo { int width; int height; // Actual data - should be width*height*4 bytes due to RGBA layout unsigned char* data; }; CAMLprim value caml_createImage(value vPixels); CAMLprim value caml_destroyImage(value vImage); CAMLprim value caml_getImagePixels(value vImage); CAMLprim value caml_setImagePixels(value vImage, value vPixels); CAMLprim value caml_saveImage(value vImage, value path); }
glennsl/reason-sdl2
src/glad.c
/* OpenGL ES loader generated by glad 0.1.27 on Tue Sep 11 02:18:13 2018. Language/Generator: C/C++ Specification: gl APIs: gles2=2.0 Profile: core Extensions: Loader: True Local files: False Omit khrplatform: False Reproducible: False Commandline: --profile="core" --api="gles2=2.0" --generator="c" --spec="gl" --extensions="" Online: http://glad.dav1d.de/#profile=core&language=c&specification=gl&loader=on&api=gles2%3D2.0 */ #include <glad/glad.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct gladGLversionStruct GLVersion = {0, 0}; #if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) #define _GLAD_IS_SOME_NEW_VERSION 1 #endif static int max_loaded_major; static int max_loaded_minor; static const char *exts = NULL; static int num_exts_i = 0; static char **exts_i = NULL; static int get_exts(void) { #ifdef _GLAD_IS_SOME_NEW_VERSION if (max_loaded_major < 3) { #endif exts = (const char *)glGetString(GL_EXTENSIONS); #ifdef _GLAD_IS_SOME_NEW_VERSION } else { unsigned int index; num_exts_i = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); if (num_exts_i > 0) { exts_i = (char **)realloc((void *)exts_i, (size_t)num_exts_i * (sizeof *exts_i)); } if (exts_i == NULL) { return 0; } for (index = 0; index < (unsigned)num_exts_i; index++) { const char *gl_str_tmp = (const char *)glGetStringi(GL_EXTENSIONS, index); size_t len = strlen(gl_str_tmp); char *local_str = (char *)malloc((len + 1) * sizeof(char)); if (local_str != NULL) { memcpy(local_str, gl_str_tmp, (len + 1) * sizeof(char)); } exts_i[index] = local_str; } } #endif return 1; } static void free_exts(void) { if (exts_i != NULL) { int index; for (index = 0; index < num_exts_i; index++) { free((char *)exts_i[index]); } free((void *)exts_i); exts_i = NULL; } } static int has_ext(const char *ext) { #ifdef _GLAD_IS_SOME_NEW_VERSION if (max_loaded_major < 3) { #endif const char *extensions; const char *loc; const char *terminator; extensions = exts; if (extensions == NULL || ext == NULL) { return 0; } while (1) { loc = strstr(extensions, ext); if (loc == NULL) { return 0; } terminator = loc + strlen(ext); if ((loc == extensions || *(loc - 1) == ' ') && (*terminator == ' ' || *terminator == '\0')) { return 1; } extensions = terminator; } #ifdef _GLAD_IS_SOME_NEW_VERSION } else { int index; if (exts_i == NULL) return 0; for (index = 0; index < num_exts_i; index++) { const char *e = exts_i[index]; if (exts_i[index] != NULL && strcmp(e, ext) == 0) { return 1; } } } #endif return 0; } int GLAD_GL_ES_VERSION_2_0 = 0; PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL; PFNGLATTACHSHADERPROC glad_glAttachShader = NULL; PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL; PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL; PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL; PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL; PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; PFNGLBLENDCOLORPROC glad_glBlendColor = NULL; PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL; PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL; PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL; PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL; PFNGLBUFFERDATAPROC glad_glBufferData = NULL; PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL; PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL; PFNGLCLEARPROC glad_glClear = NULL; PFNGLCLEARCOLORPROC glad_glClearColor = NULL; PFNGLCLEARDEPTHFPROC glad_glClearDepthf = NULL; PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL; PFNGLCOLORMASKPROC glad_glColorMask = NULL; PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL; PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL; PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL; PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL; PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; PFNGLCREATESHADERPROC glad_glCreateShader = NULL; PFNGLCULLFACEPROC glad_glCullFace = NULL; PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL; PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL; PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL; PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL; PFNGLDELETESHADERPROC glad_glDeleteShader = NULL; PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL; PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL; PFNGLDEPTHMASKPROC glad_glDepthMask = NULL; PFNGLDEPTHRANGEFPROC glad_glDepthRangef = NULL; PFNGLDETACHSHADERPROC glad_glDetachShader = NULL; PFNGLDISABLEPROC glad_glDisable = NULL; PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL; PFNGLENABLEPROC glad_glEnable = NULL; PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL; PFNGLFINISHPROC glad_glFinish = NULL; PFNGLFLUSHPROC glad_glFlush = NULL; PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL; PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL; PFNGLFRONTFACEPROC glad_glFrontFace = NULL; PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL; PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL; PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL; PFNGLGENTEXTURESPROC glad_glGenTextures = NULL; PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL; PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL; PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL; PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL; PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL; PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL; PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL; PFNGLGETERRORPROC glad_glGetError = NULL; PFNGLGETFLOATVPROC glad_glGetFloatv = NULL; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv = NULL; PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL; PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL; PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL; PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv = NULL; PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL; PFNGLGETSHADERPRECISIONFORMATPROC glad_glGetShaderPrecisionFormat = NULL; PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL; PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL; PFNGLGETSTRINGPROC glad_glGetString = NULL; PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL; PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL; PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL; PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL; PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL; PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL; PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL; PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL; PFNGLHINTPROC glad_glHint = NULL; PFNGLISBUFFERPROC glad_glIsBuffer = NULL; PFNGLISENABLEDPROC glad_glIsEnabled = NULL; PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer = NULL; PFNGLISPROGRAMPROC glad_glIsProgram = NULL; PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer = NULL; PFNGLISSHADERPROC glad_glIsShader = NULL; PFNGLISTEXTUREPROC glad_glIsTexture = NULL; PFNGLLINEWIDTHPROC glad_glLineWidth = NULL; PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL; PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL; PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL; PFNGLREADPIXELSPROC glad_glReadPixels = NULL; PFNGLRELEASESHADERCOMPILERPROC glad_glReleaseShaderCompiler = NULL; PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL; PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL; PFNGLSCISSORPROC glad_glScissor = NULL; PFNGLSHADERBINARYPROC glad_glShaderBinary = NULL; PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL; PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL; PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL; PFNGLSTENCILMASKPROC glad_glStencilMask = NULL; PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL; PFNGLSTENCILOPPROC glad_glStencilOp = NULL; PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL; PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL; PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL; PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL; PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL; PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL; PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL; PFNGLUNIFORM1FPROC glad_glUniform1f = NULL; PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL; PFNGLUNIFORM1IPROC glad_glUniform1i = NULL; PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL; PFNGLUNIFORM2FPROC glad_glUniform2f = NULL; PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL; PFNGLUNIFORM2IPROC glad_glUniform2i = NULL; PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL; PFNGLUNIFORM3FPROC glad_glUniform3f = NULL; PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL; PFNGLUNIFORM3IPROC glad_glUniform3i = NULL; PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL; PFNGLUNIFORM4FPROC glad_glUniform4f = NULL; PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL; PFNGLUNIFORM4IPROC glad_glUniform4i = NULL; PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL; PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL; PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL; PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL; PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL; PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL; PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL; PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL; PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL; PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL; PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL; PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL; PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL; PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL; PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL; PFNGLVIEWPORTPROC glad_glViewport = NULL; static void load_GL_ES_VERSION_2_0(GLADloadproc load) { if (!GLAD_GL_ES_VERSION_2_0) return; glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); glad_glClear = (PFNGLCLEARPROC)load("glClear"); glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); glad_glClearDepthf = (PFNGLCLEARDEPTHFPROC)load("glClearDepthf"); glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); glad_glDepthRangef = (PFNGLDEPTHRANGEFPROC)load("glDepthRangef"); glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load( "glGetFramebufferAttachmentParameteriv"); glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); glad_glGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)load("glGetShaderPrecisionFormat"); glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); glad_glHint = (PFNGLHINTPROC)load("glHint"); glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); glad_glReleaseShaderCompiler = (PFNGLRELEASESHADERCOMPILERPROC)load("glReleaseShaderCompiler"); glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); glad_glShaderBinary = (PFNGLSHADERBINARYPROC)load("glShaderBinary"); glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); } static int find_extensionsGLES2(void) { if (!get_exts()) return 0; (void)&has_ext; free_exts(); return 1; } static void find_coreGLES2(void) { /* Thank you @elmindreda * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 * https://github.com/glfw/glfw/blob/master/src/context.c#L36 */ int i, major, minor; const char *version; const char *prefixes[] = {"OpenGL ES-CM ", "OpenGL ES-CL ", "OpenGL ES ", NULL}; version = (const char *)glGetString(GL_VERSION); if (!version) return; for (i = 0; prefixes[i]; i++) { const size_t length = strlen(prefixes[i]); if (strncmp(version, prefixes[i], length) == 0) { version += length; break; } } /* PR #18 */ #ifdef _MSC_VER sscanf_s(version, "%d.%d", &major, &minor); #else sscanf(version, "%d.%d", &major, &minor); #endif GLVersion.major = major; GLVersion.minor = minor; max_loaded_major = major; max_loaded_minor = minor; GLAD_GL_ES_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; if (GLVersion.major > 2 || (GLVersion.major >= 2 && GLVersion.minor >= 0)) { max_loaded_major = 2; max_loaded_minor = 0; } } int gladLoadGLES2Loader(GLADloadproc load) { GLVersion.major = 0; GLVersion.minor = 0; glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); if (glGetString == NULL) return 0; if (glGetString(GL_VERSION) == NULL) return 0; find_coreGLES2(); load_GL_ES_VERSION_2_0(load); if (!find_extensionsGLES2()) return 0; return GLVersion.major != 0 || GLVersion.minor != 0; }
cparnot/INAppStoreWindow
INAppStoreWindow/INAppStoreWindow.h
// // INAppStoreWindow.h // // Copyright (c) 2011-2014 <NAME>. All rights reserved. // Copyright (c) 2014 Petroules Corporation. All rights reserved. // // Licensed under the BSD 2-clause License. See LICENSE file distributed in the source // code of this project. // #import <Cocoa/Cocoa.h> /** Height of a small bottom bar of a window. Currently, this is 22 points. */ APPKIT_EXTERN const NSInteger kINAppStoreWindowSmallBottomBarHeight; /** Height of a large bottom bar of a window. Currently, this is 32 points. */ APPKIT_EXTERN const NSInteger kINAppStoreWindowLargeBottomBarHeight; @class INWindowButton; /** * Draws default style OS X window backgrounds and separators. */ @interface INWindowBackgroundView : NSView @end /** Draws a default style OS X title bar. */ @interface INTitlebarView : INWindowBackgroundView @end /** Draws a default style OS X bottom bar. */ @interface INBottomBarView : INWindowBackgroundView @end /** Creates a window similar to the Mac App Store window, with centered traffic lights and an enlarged title bar. This does not handle creating the toolbar. */ @interface INAppStoreWindow : NSWindow /** Prototype for a block used to implement custom drawing code for a window's title bar or bottom bar. @param drawsAsMainWindow Whether the window should be drawn in main state. @param drawingRect Drawing area of the window's title bar. @param edge NSMinYEdge to draw a bottom bar, NSMaxYEdge to draw a title bar. @param clippingPath Path to clip drawing according to window's rounded corners. */ typedef void (^INAppStoreWindowBackgroundDrawingBlock)(BOOL drawsAsMainWindow, CGRect drawingRect, CGRectEdge edge, CGPathRef clippingPath); /** The height of the title bar. By default, this is set to the standard title bar height. */ @property (nonatomic) CGFloat titleBarHeight; /** Container view for custom views added to the title bar. Add subviews to this view that you want to show in the title bar (e.g. buttons, a toolbar, etc.). This view can also be set if you want to use a different style title bar from the default one (textured, etc.). */ @property (nonatomic, strong) NSView *titleBarView; /** The height of the bottom bar. By default, this is set to 0. */ @property (nonatomic) CGFloat bottomBarHeight; /** Container view for custom views added to the bottom bar. Add subviews to this view that you want to show in the bottom bar (e.g. labels, sliders, etc.). This view can also be set if you want to use a different style bottom bar from the default one (textured, etc.). */ @property (nonatomic, strong) NSView *bottomBarView; /** Whether the fullscreen button is vertically centered. */ @property (nonatomic) BOOL centerFullScreenButton; /** Whether the traffic light buttons are vertically centered. */ @property (nonatomic) BOOL centerTrafficLightButtons; /** Whether the traffic light buttons are displayed in vertical orientation. */ @property (nonatomic) BOOL verticalTrafficLightButtons; /** Whether the title is centered vertically. */ @property (nonatomic) BOOL verticallyCenterTitle; /** Whether to hide the title bar in fullscreen mode. */ @property (nonatomic) BOOL hideTitleBarInFullScreen; /** Whether to display the baseline separator between the window's title bar and content area. */ @property (nonatomic) BOOL showsBaselineSeparator; /** Whether to display the bottom separator between the window's bottom bar and content area. */ @property (nonatomic) BOOL showsBottomBarSeparator; /** Distance between the traffic light buttons and the left edge of the window. */ @property (nonatomic) CGFloat trafficLightButtonsLeftMargin; /** * Distance between the traffic light buttons and the top edge of the window. */ @property (nonatomic) CGFloat trafficLightButtonsTopMargin; /** Distance between the fullscreen button and the right edge of the window. */ @property (nonatomic) CGFloat fullScreenButtonRightMargin; /** Distance between the fullscreen button and the top edge of the window. */ @property (nonatomic) CGFloat fullScreenButtonTopMargin; /** Spacing between the traffic light buttons. */ @property (nonatomic) CGFloat trafficLightSeparation; /** Number of points in any direction above which the window will be allowed to reposition. A Higher value indicates coarser movements but much reduced CPU overhead. Defaults to 1. */ @property (nonatomic) CGFloat mouseDragDetectionThreshold; /** Whether to show the window's title text. If \c YES, the title will be shown even if \a titleBarDrawingBlock is set. To draw the title manually, set this property to \c NO and draw the title using \a titleBarDrawingBlock. */ @property (nonatomic) BOOL showsTitle; /** Whether to show the window's title text in fullscreen mode. */ @property (nonatomic) BOOL showsTitleInFullscreen; /** Whether the window displays the document proxy icon (for document-based applications). */ @property (nonatomic) BOOL showsDocumentProxyIcon; /** The button to use as the window's close button. If this property is nil, the default button will be used. */ @property (nonatomic, strong) INWindowButton *closeButton; /** The button to use as the window's minimize button. If this property is nil, the default button will be used. */ @property (nonatomic, strong) INWindowButton *minimizeButton; /** The button to use as the window's zoom button. If this property is nil, the default button will be used. */ @property (nonatomic, strong) INWindowButton *zoomButton; /** The button to use as the window's fullscreen button. If this property is nil, the default button will be used. */ @property (nonatomic, strong) INWindowButton *fullScreenButton; /** The divider line between the window title and document versions button. */ @property (nonatomic, readonly) NSTextField *titleDivider; /** The font used to draw the window's title text. */ @property (nonatomic, strong) NSFont *titleFont; /** Gradient used to draw the window's title bar, when the window is main. If this property is \c nil, the system gradient will be used. */ @property (nonatomic, strong) NSGradient *titleBarGradient; /** Gradient used to draw the window's bottom bar, when the window is main. If this property is \c nil, the system gradient will be used. */ @property (nonatomic, strong) NSGradient *bottomBarGradient; /** Color of the separator line between a window's title bar and content area, when the window is main. If this property is \c nil, the default color will be used. */ @property (nonatomic, strong) NSColor *baselineSeparatorColor; /** Color of the window's title text, when the window is main. If this property is \c nil, the default color will be used. */ @property (nonatomic, strong) NSColor *titleTextColor; /** Drop shadow under the window's title text, when the window is main. If this property is \c nil, the default shadow will be used. */ @property (nonatomic, strong) NSShadow *titleTextShadow; /** Gradient used to draw the window's title bar, when the window is not main. If this property is \c nil, the system gradient will be used. */ @property (nonatomic, strong) NSGradient *inactiveTitleBarGradient; /** Gradient used to draw the window's bottom bar, when the window is not main. If this property is \c nil, the system gradient will be used. */ @property (nonatomic, strong) NSGradient *inactiveBottomBarGradient; /** Color of the separator line between a window's title bar and content area, when the window is not main. If this property is \c nil, the default color will be used. */ @property (nonatomic, strong) NSColor *inactiveBaselineSeparatorColor; /** Color of the window's title text, when the window is not main. If this property is \c nil, the default color will be used. */ @property (nonatomic, strong) NSColor *inactiveTitleTextColor; /** Drop shadow under the window's title text, when the window is not main. If this property is \c nil, the default shadow will be used. */ @property (nonatomic, strong) NSShadow *inactiveTitleTextShadow; /** Block to override the drawing of the window title bar with a custom implementation. */ @property (nonatomic, copy) INAppStoreWindowBackgroundDrawingBlock titleBarDrawingBlock; /** Block to override the drawing of the window bottom bar with a custom implementation. */ @property (nonatomic, copy) INAppStoreWindowBackgroundDrawingBlock bottomBarDrawingBlock; /** Whether to draw a noise pattern overlay on the title bar on OS X 10.7-10.9. This property has no effect when running on OS X 10.10 or higher. */ @property (nonatomic) BOOL drawsTitlePatternOverlay; /*! Default system gradient used to draw a window's title bar. @param drawsAsMainWindow \c YES to return the gradient used when the window is drawn in its main state, \c NO to return the color used when the window is inactive. @note This gradient is identical to the one used by AppKit in OS X versions 10.7 through 10.9. For OS X 10.6 it is currently an approximation. */ + (NSGradient *)defaultTitleBarGradient:(BOOL)drawsAsMainWindow; /*! Default system gradient used to draw a window's bottom bar. @param drawsAsMainWindow \c YES to return the gradient used when the window is drawn in its main state, \c NO to return the color used when the window is inactive. */ + (NSGradient *)defaultBottomBarGradient:(BOOL)drawsAsMainWindow; /*! Default system color of the separator line between a window's title bar and content area. @param drawsAsMainWindow \c YES to return the color used when the window is drawn in its main state, \c NO to return the color used when the window is inactive. @note This color may be an approximation and is subject to change at any time. */ + (NSColor *)defaultBaselineSeparatorColor:(BOOL)drawsAsMainWindow; /*! Default system color of a window's title text. @param drawsAsMainWindow \c YES to return the color used when the window is drawn in its main state, \c NO to return the color used when the window is inactive. @note This color may be an approximation and is subject to change at any time. */ + (NSColor *)defaultTitleTextColor:(BOOL)drawsAsMainWindow; /** Sets the height of the title bar. By default, this is set to the standard title bar height. @param adjustWindowFrame Whether to adjust the window frame in response to the change in the title bar height. By default, the window frame is adjusted when the title bar height is changed. */ - (void)setTitleBarHeight:(CGFloat)titleBarHeight adjustWindowFrame:(BOOL)adjustWindowFrame; /** Returns the height of the window's NSToolbar. If the window has no NSToolbar, or if it's not visible, returns 0. */ - (CGFloat)toolbarHeight; @end
cparnot/INAppStoreWindow
INAppStoreWindow/INAppStoreWindowCompatibility.h
<filename>INAppStoreWindow/INAppStoreWindowCompatibility.h<gh_stars>100-1000 // // INAppStoreWindowCompatibility.h // INAppStoreWindow // // Copyright (c) 2011-2014 <NAME>. All rights reserved. // Copyright (c) 2014 Petroules Corporation. All rights reserved. // // Licensed under the BSD 2-clause License. See LICENSE file distributed in the source // code of this project. // #import <Cocoa/Cocoa.h> #ifndef NSAppKitVersionNumber10_7 #define NSAppKitVersionNumber10_7 1138 #endif #ifndef NSAppKitVersionNumber10_9 #define NSAppKitVersionNumber10_9 1265 #endif #ifndef NSAppKitVersionNumber10_10 #define NSAppKitVersionNumber10_10 1343 #endif #if __MAC_OS_X_VERSION_MAX_ALLOWED < 1070 enum { NSWindowDocumentVersionsButton = 6, NSWindowFullScreenButton = 7 }; enum { NSFullScreenWindowMask = 1 << 14 }; extern NSString * const NSAccessibilityFullScreenButtonSubrole; extern NSString * const NSWindowWillEnterFullScreenNotification; extern NSString * const NSWindowDidEnterFullScreenNotification; extern NSString * const NSWindowWillExitFullScreenNotification; extern NSString * const NSWindowDidExitFullScreenNotification; extern NSString * const NSWindowWillEnterVersionBrowserNotification; extern NSString * const NSWindowDidEnterVersionBrowserNotification; extern NSString * const NSWindowWillExitVersionBrowserNotification; extern NSString * const NSWindowDidExitVersionBrowserNotification; #endif #if __MAC_OS_X_VERSION_MAX_ALLOWED < 1080 @interface NSDictionary (INNSDictionaryBackwardCompatibility) // NS_AVAILABLE(10_8, 6_0), but this is a lie - this responds in 10.7 - (id)objectForKeyedSubscript:(id)aKey; @end @interface NSMutableDictionary (INNSMutableDictionaryBackwardCompatibility) // NS_AVAILABLE(10_8, 6_0), but this is a lie - this responds in 10.7 - (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key; @end #endif #if __MAC_OS_X_VERSION_MAX_ALLOWED < 1090 @interface NSArray (INNSArrayBackwardCompatibility) - (id)firstObject; // not present in the 10.8 SDK but available since 10.6 @end @interface NSData (INNSDataBackwardCompatibility) - (id)initWithBase64Encoding:(NSString *)base64String; @end #endif NS_INLINE bool INRunningLion() { return (NSInteger)NSAppKitVersionNumber >= NSAppKitVersionNumber10_7; } NS_INLINE bool INRunningMavericks() { return (NSInteger)NSAppKitVersionNumber >= NSAppKitVersionNumber10_9; } NS_INLINE bool INRunningYosemite() { return (NSInteger)NSAppKitVersionNumber >= NSAppKitVersionNumber10_10; }
ggtakec/chmpx
lib/chmstream.h
<filename>lib/chmstream.h /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMSTREAM_H #define CHMSTREAM_H #include <iostream> #include "chmcommon.h" #include "chmpx.h" #include "chmutil.h" #include "chmdbg.h" #include "chmcntrl.h" #include "chmkvp.h" //--------------------------------------------------------- // Template basic_chmstreambuf //--------------------------------------------------------- template<typename CharT, typename Traits> class basic_chmstreambuf : public std::basic_streambuf<CharT, Traits> { public: typedef CharT char_type; typedef Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; typedef std::ios_base::openmode open_mode; typedef std::basic_streambuf<CharT, Traits> streambuf_type; private: static const size_t pagesize = 4096; static const int default_timeout = 1 * 10; // 10ms ChmCntrl* pchmcntrl; PCOMPKT plastpkt; msgid_t msgid; open_mode mode; chmhash_t init_hash; bool is_init_hash; bool is_init_key; size_t input_buff_size; size_t output_buff_size; char_type* input_buff; char_type* output_buff; char_type* output_val_pos; int read_timeout; protected: virtual int sync(void); virtual int_type overflow(int_type ch = traits_type::eof()); virtual int_type pbackfail(int_type ch = traits_type::eof()); virtual int_type underflow(void); virtual pos_type seekoff(off_type offset, std::ios_base::seekdir bpostype, open_mode opmode = std::ios_base::in | std::ios_base::out); virtual pos_type seekpos(pos_type abspos, open_mode opmode = std::ios_base::in | std::ios_base::out); private: bool init_output_buff(void); bool send_sync(void); bool receive_sync(void); public: basic_chmstreambuf(open_mode opmode = std::ios_base::in | std::ios_base::out); // Do not call this basic_chmstreambuf(ChmCntrl* pchmobj, open_mode opmode = std::ios_base::in | std::ios_base::out); basic_chmstreambuf(ChmCntrl* pchmobj, chmhash_t hash, open_mode opmode = std::ios_base::in | std::ios_base::out); basic_chmstreambuf(ChmCntrl* pchmobj, const std::string& strkey, open_mode opmode = std::ios_base::in | std::ios_base::out); virtual ~basic_chmstreambuf(); bool reset(void); bool init(ChmCntrl* pchmobj, open_mode opmode = std::ios_base::in | std::ios_base::out); bool init(ChmCntrl* pchmobj, chmhash_t hash, open_mode opmode = std::ios_base::in | std::ios_base::out); bool init(ChmCntrl* pchmobj, const std::string& strkey, open_mode opmode = std::ios_base::in | std::ios_base::out); chmhash_t receivedhash(void) const { return (plastpkt ? plastpkt->head.hash : CHM_INVALID_HASHVAL); } }; //--------------------------------------------------------- // template basic_chmstreambuf //--------------------------------------------------------- template<typename CharT, typename Traits> basic_chmstreambuf<CharT, Traits>::basic_chmstreambuf(open_mode opmode) : pchmcntrl(NULL), plastpkt(NULL), msgid(CHM_INVALID_MSGID), mode(opmode), init_hash(CHM_INVALID_HASHVAL), is_init_hash(false), is_init_key(false), input_buff_size(0), output_buff_size(0), input_buff(reinterpret_cast<char_type*>(NULL)), output_buff(reinterpret_cast<char_type*>(NULL)), output_val_pos(reinterpret_cast<char_type*>(NULL)) { } template<typename CharT, typename Traits> basic_chmstreambuf<CharT, Traits>::basic_chmstreambuf(ChmCntrl* pchmobj, open_mode opmode) : pchmcntrl(NULL), plastpkt(NULL), msgid(CHM_INVALID_MSGID), mode(opmode), init_hash(CHM_INVALID_HASHVAL), is_init_hash(false), is_init_key(false), input_buff_size(0), output_buff_size(0), input_buff(reinterpret_cast<char_type*>(NULL)), output_buff(reinterpret_cast<char_type*>(NULL)), output_val_pos(reinterpret_cast<char_type*>(NULL)) { if(!pchmobj){ ERR_CHMPRN("Parameter is wrong."); return; } if(!init(pchmobj, opmode)){ WAN_CHMPRN("Parameter is something wrong"); return; } } template<typename CharT, typename Traits> basic_chmstreambuf<CharT, Traits>::basic_chmstreambuf(ChmCntrl* pchmobj, chmhash_t hash, open_mode opmode) : pchmcntrl(NULL), plastpkt(NULL), msgid(CHM_INVALID_MSGID), mode(opmode), init_hash(hash), is_init_hash(false), is_init_key(false), input_buff_size(0), output_buff_size(0), input_buff(reinterpret_cast<char_type*>(NULL)), output_buff(reinterpret_cast<char_type*>(NULL)), output_val_pos(reinterpret_cast<char_type*>(NULL)) { if(!pchmobj){ ERR_CHMPRN("Parameter is wrong."); return; } if(!init(pchmobj, hash, opmode)){ WAN_CHMPRN("Parameter is something wrong"); return; } } template<typename CharT, typename Traits> basic_chmstreambuf<CharT, Traits>::basic_chmstreambuf(ChmCntrl* pchmobj, const std::string& strkey, open_mode opmode) : pchmcntrl(NULL), plastpkt(NULL), msgid(CHM_INVALID_MSGID), mode(opmode), init_hash(CHM_INVALID_HASHVAL), is_init_hash(false), is_init_key(false), input_buff_size(0), output_buff_size(0), input_buff(reinterpret_cast<char_type*>(NULL)), output_buff(reinterpret_cast<char_type*>(NULL)), output_val_pos(reinterpret_cast<char_type*>(NULL)) { if(!pchmobj){ ERR_CHMPRN("Parameter is wrong."); return; } if(!init(pchmobj, strkey, opmode)){ WAN_CHMPRN("Parameter is something wrong"); return; } } template<typename CharT, typename Traits> basic_chmstreambuf<CharT, Traits>::~basic_chmstreambuf(void) { reset(); } template<typename CharT, typename Traits> bool basic_chmstreambuf<CharT, Traits>::reset(void) { // If there is no-flushed write buffer, flush it here. // if(pchmcntrl && streambuf_type::pbase() < streambuf_type::pptr()){ // If there are left data, send it. // Be careful, if is_init_key is true, current position must be over start os value data. // if(!is_init_key || (reinterpret_cast<char_type*>(&output_buff[strlen(output_buff) + 1]) < streambuf_type::pptr())){ if(!send_sync()){ WAN_CHMPRN("Could not put left write buffer into."); } } } if(pchmcntrl && CHM_INVALID_MSGID != msgid){ // close msgid if(!pchmcntrl->Close(msgid)){ WAN_CHMPRN("Could not close MQ."); } } pchmcntrl = NULL; msgid = CHM_INVALID_MSGID; mode = std::ios_base::in | std::ios_base::out; init_hash = CHM_INVALID_HASHVAL; is_init_hash = false; is_init_key = false; input_buff_size = 0; output_buff_size= 0; output_val_pos = reinterpret_cast<char_type*>(NULL); read_timeout = basic_chmstreambuf<CharT, Traits>::default_timeout; CHM_Free(input_buff); CHM_Free(output_buff); CHM_Free(plastpkt); return true; } template<typename CharT, typename Traits> bool basic_chmstreambuf<CharT, Traits>::init(ChmCntrl* pchmobj, open_mode opmode) { reset(); if(!pchmobj){ return true; } if(pchmobj->IsChmpxType()){ ERR_CHMPRN("ChmCntrl type does not server(slave) side."); return false; } pchmcntrl = pchmobj; mode = (opmode & (std::ios_base::in | std::ios_base::out)); if(opmode & std::ios_base::out){ output_buff_size = basic_chmstreambuf<CharT, Traits>::pagesize; if(reinterpret_cast<char_type*>(NULL) == (output_buff = reinterpret_cast<char_type*>(calloc(output_buff_size, sizeof(char_type))))){ ERR_CHMPRN("Could not allocate memory."); reset(); return false; } streambuf_type::setp(output_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(output_buff) + static_cast<off_type>(output_buff_size))); } if(opmode & std::ios_base::in){ // input_buff = NULL streambuf_type::setg(input_buff, input_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(input_buff) + static_cast<off_type>(input_buff_size))); } return true; } template<typename CharT, typename Traits> bool basic_chmstreambuf<CharT, Traits>::init(ChmCntrl* pchmobj, chmhash_t hash, open_mode opmode) { reset(); if(!pchmobj){ return true; } if(pchmobj->IsChmpxType()){ ERR_CHMPRN("ChmCntrl type does not server(slave) side."); return false; } if(0 == (opmode & std::ios_base::out)){ ERR_CHMPRN("open_mode does not have std::ios_base::out."); return false; } pchmcntrl = pchmobj; mode = (opmode & (std::ios_base::in | std::ios_base::out)); init_hash = hash; is_init_hash= true; if(opmode & std::ios_base::out){ output_buff_size = basic_chmstreambuf<CharT, Traits>::pagesize; if(reinterpret_cast<char_type*>(NULL) == (output_buff = reinterpret_cast<char_type*>(calloc(output_buff_size, sizeof(char_type))))){ ERR_CHMPRN("Could not allocate memory."); reset(); return false; } streambuf_type::setp(output_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(output_buff) + static_cast<off_type>(output_buff_size))); } if(opmode & std::ios_base::in){ // input_buff = NULL streambuf_type::setg(input_buff, input_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(input_buff) + static_cast<off_type>(input_buff_size))); } return true; } template<typename CharT, typename Traits> bool basic_chmstreambuf<CharT, Traits>::init(ChmCntrl* pchmobj, const std::string& strkey, open_mode opmode) { reset(); if(!pchmobj){ return true; } if(pchmobj->IsChmpxType()){ ERR_CHMPRN("ChmCntrl type does not server(slave) side."); return false; } if(0 == (opmode & std::ios_base::out)){ ERR_CHMPRN("open_mode does not have std::ios_base::out."); return false; } pchmcntrl = pchmobj; mode = (opmode & (std::ios_base::in | std::ios_base::out)); is_init_key = true; if(opmode & std::ios_base::out){ output_buff_size = ((strkey.length() + 1/* for \0 */ + 1/* for new adding buffer */) / basic_chmstreambuf<CharT, Traits>::pagesize + 1) * basic_chmstreambuf<CharT, Traits>::pagesize; if(reinterpret_cast<char_type*>(NULL) == (output_buff = reinterpret_cast<char_type*>(calloc(output_buff_size, sizeof(char_type))))){ ERR_CHMPRN("Could not allocate memory."); reset(); return false; } strcpy(output_buff, strkey.c_str()); // start position is after strkey string. streambuf_type::setp(output_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(output_buff) + static_cast<off_type>(output_buff_size))); streambuf_type::pbump(strlen(output_buff) + 1); // set value start pos output_val_pos = &output_buff[strlen(output_buff) + 1]; } if(opmode & std::ios_base::in){ // input_buff = NULL streambuf_type::setg(input_buff, input_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(input_buff) + static_cast<off_type>(input_buff_size))); } return true; } template<typename CharT, typename Traits> bool basic_chmstreambuf<CharT, Traits>::init_output_buff(void) { if(!pchmcntrl){ ERR_CHMPRN("This object did not initialized."); return false; } if(output_buff && is_init_key){ // do not erase key area, so only reset value pos. output_val_pos = &output_buff[strlen(output_buff) + 1]; // start position is after strkey string. streambuf_type::setp(output_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(output_buff) + static_cast<off_type>(output_buff_size))); streambuf_type::pbump(strlen(output_buff) + 1); }else{ // clear if(!output_buff || 0 == output_buff_size){ CHM_Free(output_buff); output_buff_size = basic_chmstreambuf<CharT, Traits>::pagesize; if(reinterpret_cast<char_type*>(NULL) == (output_buff = reinterpret_cast<char_type*>(calloc(output_buff_size, sizeof(char_type))))){ ERR_CHMPRN("Could not allocate memory."); reset(); return false; } } *output_buff = static_cast<char_type>('\0'); output_val_pos = reinterpret_cast<char_type*>(NULL); streambuf_type::setp(output_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(output_buff) + static_cast<off_type>(output_buff_size))); } return true; } template<typename CharT, typename Traits> bool basic_chmstreambuf<CharT, Traits>::send_sync(void) { if(!pchmcntrl){ ERR_CHMPRN("This object did not initialized."); return false; } // raw data chmhash_t local_hash = (is_init_hash ? init_hash : CHM_INVALID_HASHVAL); char_type* val_pos = output_val_pos ? output_val_pos : output_buff; // backup value before reinitializing size_t rawlength = 0L; unsigned char* rawdata = NULL; { if(!output_buff || 0 == output_buff_size){ ERR_CHMPRN("There is no data for sending."); init_output_buff(); return false; } // make key and value structure ChmBinData Key; ChmBinData Value; if((output_buff != val_pos && !Key.Set(reinterpret_cast<unsigned char*>(output_buff), strlen(output_buff) + 1)) || !Value.Set(reinterpret_cast<unsigned char*>(val_pos), strlen(val_pos) + 1)){ ERR_CHMPRN("Could not set key and value to chmbindata."); init_output_buff(); return false; } // make chmkvp ChmKVPair chmkvp; if(!chmkvp.SetKey(Key) || !chmkvp.SetValue(Value)){ ERR_CHMPRN("Could not set key and value to chmkvp."); init_output_buff(); return false; } // check hash value(for only slave) if(pchmcntrl->IsClientOnSlvType() && !is_init_hash){ if(output_buff == val_pos){ ERR_CHMPRN("Could not make hash value for sending on slave because of empty key value."); init_output_buff(); return false; } local_hash = chmkvp.GetHash(); } // make raw data if(NULL == (rawdata = chmkvp.Put(rawlength))){ ERR_CHMPRN("Could not convert raw data for sending."); init_output_buff(); return false; } // reset buffer init_output_buff(); } // sending if(pchmcntrl->IsClientOnSvrType()){ if(!plastpkt){ ERR_CHMPRN("There is no sending terminal."); CHM_Free(rawdata); return false; } if(!pchmcntrl->Reply(plastpkt, rawdata, rawlength)){ ERR_CHMPRN("Failed replying to server chmpx."); CHM_Free(rawdata); return false; } }else{ if(CHM_INVALID_MSGID == msgid){ if(CHM_INVALID_MSGID == (msgid = pchmcntrl->Open())){ ERR_CHMPRN("Could not open MQ."); CHM_Free(rawdata); return false; } } if(!pchmcntrl->Send(msgid, rawdata, rawlength, local_hash)){ ERR_CHMPRN("Failed sending to slave chmpx."); CHM_Free(rawdata); return false; } } CHM_Free(rawdata); return true; } template<typename CharT, typename Traits> bool basic_chmstreambuf<CharT, Traits>::receive_sync(void) { if(!pchmcntrl){ MSG_CHMPRN("This object did not initialized or could not open key because of not existing."); return false; } // receiving PCOMPKT pComPkt = NULL; unsigned char* pbody = NULL; size_t length = 0L; if(pchmcntrl->IsClientOnSvrType()){ // receive if(!pchmcntrl->Receive(&pComPkt, &pbody, &length, read_timeout) || !pbody || 0 == length){ //MSG_CHMPRN("Failed to receive from server chmpx."); CHM_Free(pbody); return false; } }else{ if(CHM_INVALID_MSGID == msgid){ ERR_CHMPRN("There is no receiving terminal."); return false; } if(!pchmcntrl->Receive(msgid, &pComPkt, &pbody, &length, read_timeout) || !pbody || 0 == length){ //MSG_CHMPRN("Failed to receive from slave chmpx."); CHM_Free(pbody); return false; } } // convert ChmKVPair chmkvp; if(!chmkvp.Load(pbody)){ ERR_CHMPRN("Could not load message body to chmkvp."); CHM_Free(pComPkt); CHM_Free(pbody); return false; } // make buffer const char* pkey = chmkvp.GetKey(); const char* pval = chmkvp.GetValue(); size_t newsize = (pkey ? (strlen(pkey) + 1) : 1) + (pval ? (strlen(pval) + 1) : 1); char_type* newbuff; if(reinterpret_cast<char_type*>(NULL) == (newbuff = reinterpret_cast<char_type*>(calloc(newsize, sizeof(char_type))))){ ERR_CHMPRN("Could not allocate memory."); CHM_Free(pComPkt); CHM_Free(pbody); return false; } // set input buffer(key terminated by LF) size_t setpos = 0; if(pkey){ strcpy(&newbuff[setpos], pkey); newbuff[setpos + strlen(pkey)] = static_cast<char_type>('\n'); // \0 -> \n setpos += strlen(pkey) + 1; }else{ newbuff[setpos++] = '\n'; } if(pval){ strcpy(&newbuff[setpos], pval); }else{ newbuff[setpos++] = '\0'; } CHM_Free(pbody); // reset input buffer CHM_Free(input_buff); CHM_Free(plastpkt); input_buff_size = 0; streambuf_type::setg(input_buff, input_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(input_buff) + static_cast<off_type>(input_buff_size))); // set internal buffer plastpkt = pComPkt; input_buff = newbuff; input_buff_size = newsize; streambuf_type::setg(input_buff, input_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(input_buff) + static_cast<off_type>(input_buff_size))); return true; } // // This stream only receives Manipulator(std::endl). // On server side: // If this gets Manipulator, sends output buffer as soon as possible. // But the object must start receiving at first, so if the compkt pointer // does not exist, fails to send(reply). // If the object has not got key value, sends with key value empty. // // On slave side: // If this gets Manipulator, depends on key value and default hash value. // If gets Manipulator when the object does not have default hash and key // value, this does not send and wait to get key value until getting next // Manipulator. // If gets when the object has default hash value, this sends with empty // key value.(not wait to get next Manipulator) // If gets second Manipulator, this sends key and value as soon as possible. // template<typename CharT, typename Traits> int basic_chmstreambuf<CharT, Traits>::sync(void) { if(!pchmcntrl){ ERR_CHMPRN("This object did not initialized."); return -1; } if(reinterpret_cast<char_type*>(NULL) == streambuf_type::pptr()){ MSG_CHMPRN("There is no current put pointer."); return -1; } // [NOTE] // If on slave chmpx and does not have default hash value and has not put key data. // Thus this sync means for putting key data, and waiting value data after this sync. // if(pchmcntrl->IsClientOnSlvType() && !is_init_hash && reinterpret_cast<char_type*>(NULL) == output_val_pos){ // check key length if(streambuf_type::pbase() == streambuf_type::pptr()){ ERR_CHMPRN("There is no key value."); return -1; } *(streambuf_type::pptr()) = static_cast<char_type>('\0'); // check last character(LF) streambuf_type::pbump(-1); if(traits_type::eq(static_cast<char_type>('\n'), *(streambuf_type::pptr()))){ *(streambuf_type::pptr()) = static_cast<char_type>('\0'); // recheck key length if(streambuf_type::pbase() == streambuf_type::pptr()){ ERR_CHMPRN("key value is empty."); return -1; } } streambuf_type::pbump(1); // key is OK. output_val_pos = streambuf_type::pptr(); // do not send, wait for value. return 0; } // check last character(LF) if(streambuf_type::pbase() < streambuf_type::pptr()){ *(streambuf_type::pptr()) = static_cast<char_type>('\0'); streambuf_type::pbump(-1); if(traits_type::eq(static_cast<char_type>('\n'), *(streambuf_type::pptr()))){ *(streambuf_type::pptr()) = static_cast<char_type>('\0'); } streambuf_type::pbump(1); } if(!send_sync()){ return -1; } return 0; } template<typename CharT, typename Traits> typename basic_chmstreambuf<CharT, Traits>::int_type basic_chmstreambuf<CharT, Traits>::underflow(void) { if(reinterpret_cast<char_type*>(NULL) == streambuf_type::eback() || streambuf_type::egptr() <= streambuf_type::gptr()){ // reached end of input buffer or nothing read data, so it means EOF. // try to read new data. if(!receive_sync()){ // reset input buffer CHM_Free(input_buff); input_buff_size = 0; streambuf_type::setg(input_buff, input_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(input_buff) + static_cast<off_type>(input_buff_size))); return traits_type::eof(); } } // Check EOF if(reinterpret_cast<char_type*>(NULL) == streambuf_type::eback() || reinterpret_cast<char_type*>(NULL) == streambuf_type::egptr()){ return traits_type::eof(); } return traits_type::to_int_type(streambuf_type::gptr()[0]); } template<typename CharT, typename Traits> typename basic_chmstreambuf<CharT, Traits>::int_type basic_chmstreambuf<CharT, Traits>::overflow(int_type ch) { if(!pchmcntrl){ ERR_CHMPRN("This object did not initialized."); return traits_type::eof(); } // for value position off_type val_offset = (reinterpret_cast<char_type*>(NULL) == output_val_pos || output_val_pos < output_buff) ? static_cast<off_type>(-1) : (output_val_pos - output_buff); // expand buffer area size_t newsize = output_buff_size + basic_chmstreambuf<CharT, Traits>::pagesize; char_type* newbuff; if(reinterpret_cast<char_type*>(NULL) == (newbuff = reinterpret_cast<char_type*>(realloc(output_buff, newsize)))){ ERR_CHMPRN("Could not allocate memory."); return traits_type::eof(); } // set newbuff streambuf_type::setp(newbuff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(newbuff) + static_cast<off_type>(newsize))); streambuf_type::pbump(output_buff_size); // add ch *(streambuf_type::pptr()) = ch; streambuf_type::pbump(1); // set internal data output_buff_size = newsize; output_buff = newbuff; output_val_pos = (static_cast<off_type>(-1) == val_offset) ? reinterpret_cast<char_type*>(NULL) : (output_buff + val_offset); return traits_type::to_int_type(ch); } template<typename CharT, typename Traits> typename basic_chmstreambuf<CharT, Traits>::int_type basic_chmstreambuf<CharT, Traits>::pbackfail(int_type ch) { if(!pchmcntrl){ ERR_CHMPRN("This object did not initialized."); return traits_type::eof(); } if(streambuf_type::eback() == streambuf_type::gptr()){ // now first position in reading buffer(data) return traits_type::eof(); }else if(streambuf_type::eback() < streambuf_type::gptr()){ if(!traits_type::eq(traits_type::to_char_type(ch), streambuf_type::gptr()[-1])){ streambuf_type::gbump(-1); return traits_type::eof(); } // decrement current streambuf_type::gbump(-1); }else{ // why ERR_CHMPRN("Something error in pbackfail."); return traits_type::eof(); } return traits_type::to_int_type(ch); } template<typename CharT, typename Traits> typename basic_chmstreambuf<CharT, Traits>::pos_type basic_chmstreambuf<CharT, Traits>::seekoff(off_type offset, std::ios_base::seekdir bpostype, open_mode opmode) { if(!(opmode & (std::ios_base::out | std::ios_base::in))){ ERR_CHMPRN("Parameter is wrong"); return pos_type(off_type(-1)); } if(!pchmcntrl){ ERR_CHMPRN("This object did not initialized."); return pos_type(off_type(-1)); } // seekp() if(opmode & std::ios_base::out){ // [NOTE] // Do not care for a case of that output_buff is NULL. // Following codes works good when it is NULL. // // make new current char_type* newcur = reinterpret_cast<char_type*>(NULL); off_type newoffset = offset; if(std::ios_base::beg == bpostype){ newcur = streambuf_type::pbase() + offset; newoffset -= (streambuf_type::pptr() - streambuf_type::pbase()); }else if(std::ios_base::end == bpostype){ char_type* endpos; if(reinterpret_cast<char_type*>(NULL) != output_val_pos){ endpos = &output_val_pos[strlen(output_val_pos)]; }else{ endpos = &output_buff[strlen(output_buff)]; } newcur = endpos + offset; newoffset = newcur - streambuf_type::pptr(); }else if(std::ios_base::cur == bpostype){ newcur = streambuf_type::pptr() + offset; } // check key value if(pchmcntrl->IsClientOnSlvType() && reinterpret_cast<char_type*>(NULL) != output_val_pos){ if(is_init_key){ // do not erase key area if(newcur < output_val_pos){ ERR_CHMPRN("Could not seek by underflow."); return pos_type(off_type(-1)); } }else{ if(newcur < output_val_pos){ // This case is seek backward to over key value separator. output_val_pos = reinterpret_cast<char_type*>(NULL); } } } // check overflow if(streambuf_type::epptr() < newcur){ // re-calc(from buffer start) newoffset = newcur - streambuf_type::pbase(); // buffer overflow -> expand size_t newsize = ((newcur - streambuf_type::pbase() + 1) / basic_chmstreambuf<CharT, Traits>::pagesize + 1) * basic_chmstreambuf<CharT, Traits>::pagesize; char_type* newbuff; if(reinterpret_cast<char_type*>(NULL) == (newbuff = reinterpret_cast<char_type*>(realloc(output_buff, newsize)))){ ERR_CHMPRN("Could not allocate memory."); return pos_type(off_type(-1)); } output_buff_size= newsize; output_buff = newbuff; // reset buffer streambuf_type::setp(output_buff, reinterpret_cast<char_type*>(reinterpret_cast<off_type>(output_buff) + static_cast<off_type>(output_buff_size))); } // move current streambuf_type::pbump(newoffset); // terminate *(streambuf_type::pptr()) = static_cast<char_type>('\0'); } // seekg() if(opmode & std::ios_base::in){ if(reinterpret_cast<char_type*>(NULL) == input_buff){ // Now have not loaded yet, so try to receiving. if(!receive_sync()){ WAN_CHMPRN("There is no receiving data, and failed to receiving, thus could not seek."); return pos_type(off_type(-1)); } } // make new current char_type* newcur = reinterpret_cast<char_type*>(NULL); off_type newoffset = offset; // offset from current if(std::ios_base::end == bpostype){ WAN_CHMPRN("Over end of receiving data, thus could not seek."); return pos_type(off_type(-1)); }else if(std::ios_base::beg == bpostype){ newcur = streambuf_type::eback() + offset; newoffset -= (streambuf_type::gptr() - streambuf_type::eback()); }else if(std::ios_base::cur == bpostype){ newcur = streambuf_type::gptr() + offset; } // check over end of input buffer if(streambuf_type::egptr() < newcur){ WAN_CHMPRN("Over end of receiving data, thus could not seek."); return pos_type(off_type(-1)); } // move current streambuf_type::gbump(newoffset); } return pos_type(off_type(0)); } template<typename CharT, typename Traits> typename basic_chmstreambuf<CharT, Traits>::pos_type basic_chmstreambuf<CharT, Traits>::seekpos(pos_type abspos, open_mode opmode) { return seekoff(off_type(abspos), std::ios_base::beg, opmode); } //--------------------------------------------------------- // Template basic_ichmstream //--------------------------------------------------------- template<typename CharT, typename Traits> class basic_ichmstream : public std::basic_istream<CharT, Traits> { public: typedef CharT char_type; typedef Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; typedef std::ios_base::openmode open_mode; typedef basic_chmstreambuf<CharT, Traits> chmstreambuf_type; typedef std::basic_istream<char_type, traits_type> istream_type; typedef std::basic_ios<char_type, traits_type> ios_type; private: chmstreambuf_type chmstreambuf; protected: basic_ichmstream(open_mode opmode = std::ios_base::in) : istream_type(), chmstreambuf(opmode | std::ios_base::in) { ios_type::init(&chmstreambuf); } public: basic_ichmstream(ChmCntrl* pchmobj, open_mode opmode = std::ios_base::in) : istream_type(), chmstreambuf(pchmobj, opmode | std::ios_base::in) { ios_type::init(&chmstreambuf); } ~basic_ichmstream() { } chmstreambuf_type* rdbuf() const { return const_cast<chmstreambuf_type*>(&chmstreambuf); } chmhash_t receivedhash(void) const { return chmstreambuf.receivedhash(); } }; //--------------------------------------------------------- // Template basic_ochmstream //--------------------------------------------------------- template <typename CharT, typename Traits> class basic_ochmstream : public std::basic_ostream<CharT, Traits> { public: typedef CharT char_type; typedef Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; typedef std::ios_base::openmode open_mode; typedef basic_chmstreambuf<CharT, Traits> chmstreambuf_type; typedef std::basic_ostream<char_type, traits_type> ostream_type; typedef std::basic_ios<char_type, traits_type> ios_type; private: chmstreambuf_type chmstreambuf; protected: basic_ochmstream(open_mode opmode = std::ios_base::out) : ostream_type(), chmstreambuf(opmode | std::ios_base::out) { ios_type::init(&chmstreambuf); } public: basic_ochmstream(ChmCntrl* pchmobj, open_mode opmode = std::ios_base::out) : ostream_type(), chmstreambuf(pchmobj, opmode | std::ios_base::out) { ios_type::init(&chmstreambuf); } basic_ochmstream(ChmCntrl* pchmobj, chmhash_t hash, open_mode opmode = std::ios_base::out) : ostream_type(), chmstreambuf(pchmobj, hash, opmode | std::ios_base::out) { ios_type::init(&chmstreambuf); } basic_ochmstream(ChmCntrl* pchmobj, const std::string& strkey, open_mode opmode = std::ios_base::out) : ostream_type(), chmstreambuf(pchmobj, strkey, opmode | std::ios_base::out) { ios_type::init(&chmstreambuf); } ~basic_ochmstream() { } chmstreambuf_type* rdbuf() const { return const_cast<chmstreambuf_type*>(&chmstreambuf); } chmhash_t receivedhash(void) const { return chmstreambuf.receivedhash(); } }; //--------------------------------------------------------- // Template basic_chmstream //--------------------------------------------------------- template <typename CharT, typename Traits> class basic_chmstream : public std::basic_iostream<CharT, Traits> { public: typedef CharT char_type; typedef Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; typedef std::ios_base::openmode open_mode; typedef basic_chmstreambuf<CharT, Traits> chmstreambuf_type; typedef std::basic_iostream<char_type, traits_type> iostream_type; typedef std::basic_ios<char_type, traits_type> ios_type; private: chmstreambuf_type chmstreambuf; protected: basic_chmstream(open_mode opmode = std::ios_base::out | std::ios_base::in) : iostream_type(), chmstreambuf(opmode | std::ios_base::out | std::ios_base::in) { ios_type::init(&chmstreambuf); } public: basic_chmstream(ChmCntrl* pchmobj, open_mode opmode = std::ios_base::out | std::ios_base::in) : iostream_type(), chmstreambuf(pchmobj, opmode | std::ios_base::out | std::ios_base::in) { ios_type::init(&chmstreambuf); } basic_chmstream(ChmCntrl* pchmobj, chmhash_t hash, open_mode opmode = std::ios_base::out | std::ios_base::in) : iostream_type(), chmstreambuf(pchmobj, hash, opmode | std::ios_base::out | std::ios_base::in) { ios_type::init(&chmstreambuf); } basic_chmstream(ChmCntrl* pchmobj, const std::string& strkey, open_mode opmode = std::ios_base::out | std::ios_base::in) : iostream_type(), chmstreambuf(pchmobj, strkey, opmode | std::ios_base::out | std::ios_base::in) { ios_type::init(&chmstreambuf); } ~basic_chmstream() { } chmstreambuf_type* rdbuf() const { return const_cast<chmstreambuf_type*>(&chmstreambuf); } chmhash_t receivedhash(void) const { return chmstreambuf.receivedhash(); } }; //--------------------------------------------------------- // Typedefs //--------------------------------------------------------- template<typename CharT, typename Traits = std::char_traits<CharT> > class basic_chmstreambuf; template<typename CharT, typename Traits = std::char_traits<CharT> > class basic_ichmstream; template<typename CharT, typename Traits = std::char_traits<CharT> > class basic_ochmstream; template<typename CharT, typename Traits = std::char_traits<CharT> > class basic_chmstream; typedef basic_chmstreambuf<char> chmstreambuf; typedef basic_ichmstream<char> ichmstream; typedef basic_ochmstream<char> ochmstream; typedef basic_chmstream<char> chmstream; #ifdef _GLIBCXX_USE_WCHAR_T typedef basic_chmstreambuf<wchar_t> wchmstreambuf; typedef basic_ichmstream<wchar_t> wichmstream; typedef basic_ochmstream<wchar_t> wochmstream; typedef basic_chmstream<wchar_t> wchmstream; #endif // _GLIBCXX_USE_WCHAR_T #endif // CHMSTREAM_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmutil.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMUTIL_H #define CHMUTIL_H #include <string> #include <vector> #include <list> #include <map> #include <sstream> #include <fullock/flckutil.h> #include "chmcommon.h" //--------------------------------------------------------- // String Utilities //--------------------------------------------------------- // RFC date std::string str_rfcdate(time_t date = -1); time_t rfcdate_time(const char* rfcdate); // is_xxx bool is_string_alpha(const char* str); bool is_string_number(const char* str); bool is_string_number_ex(const char* str, int max, bool allow_empty, bool is_decimal); bool cvt_string_to_number_raw(const char* pbase, uint64_t* presult, bool is_decimal); uint64_t cvt_string_to_number(const char* pbase, bool is_decimal); // array / mapping typedef std::list<std::string> strlst_t; typedef std::map<std::string, std::string> strmap_t; typedef std::vector<strmap_t> strmaparr_t; typedef std::map<std::string, strlst_t> strlstmap_t; struct strarr_sort { bool operator()(const std::string& lstr, const std::string& rstr) const { return lstr < rstr; } }; template<typename T1, typename T2> struct merge_map { typedef typename std::map<T1, T2> merge_map_t; typedef typename std::map<T1, T2>::const_iterator merge_map_iterator; merge_map(merge_map_t& map1, merge_map_t& map2) { for(merge_map_iterator iter = map2.begin(); iter != map2.end(); ++iter){ map1[iter->first] = iter->second; } } }; typedef merge_map<std::string, std::string> merge_strmap; // separate bool str_paeser(const char* pbase, strlst_t& strarr, const char* psep = NULL, bool istrim = true); bool str_split(const char* pbase, strlst_t& strarr, char sep, bool istrim = true); // others bool sorted_insert_strmaparr(strmaparr_t& sorted_smaps, strmap_t& smap, const char* pSortKey1, const char* pSortKey2 = NULL); //--------------------------------------------------------- // Utility Macros //--------------------------------------------------------- #define CHM_Free(ptr) \ { \ if(ptr){ \ free(ptr); \ ptr = NULL; \ } \ } #define CHM_Delete(ptr) \ { \ if(ptr){ \ delete ptr; \ ptr = NULL; \ } \ } #define CHM_CLOSE(fd) \ { \ if(CHM_INVALID_HANDLE != fd){ \ close(fd); \ fd = CHM_INVALID_HANDLE; \ } \ } #define CHM_CLOSESOCK(sock) \ { \ if(CHM_INVALID_SOCK != sock){ \ close(sock); \ sock = CHM_INVALID_SOCK; \ } \ } #define CHM_MUMMAP(fd, base, length) \ { \ if(NULL != base){ \ munmap(base, length); \ base = NULL; \ } \ CHM_CLOSE(fd); \ } //--------------------------------------------------------- // timespec //--------------------------------------------------------- #if defined(__cplusplus) template<typename T> inline void SET_TIMESPEC(T* ptr, time_t sec, long nsec) { (ptr)->tv_sec = sec; if(nsec >= (1000 * 1000 * 1000)){ (ptr)->tv_sec += (nsec / (1000 * 1000 * 1000)); nsec = (nsec % (1000 * 1000 * 1000)); } (ptr)->tv_nsec = nsec; } template<typename T> inline void COPY_TIMESPEC(T* dest, const T* src) { (dest)->tv_sec = (src)->tv_sec; (dest)->tv_nsec = (src)->tv_nsec; } template<typename T> inline int COMPARE_TIMESPEC(const T* data1, const T* data2) { if((data1)->tv_sec > (data2)->tv_sec){ return 1; }else if((data1)->tv_sec < (data2)->tv_sec){ return -1; }else if((data1)->tv_nsec > (data2)->tv_nsec){ return 1; }else if((data1)->tv_nsec < (data2)->tv_nsec){ return -1; } return 0; } template<typename T> inline void ADD_TIMESPEC(T* base, const T* val) { (base)->tv_sec += (val)->tv_sec; (base)->tv_nsec += (val)->tv_nsec; if(1 <= (((base)->tv_nsec) / (1000 * 1000 * 1000))){ ++((base)->tv_sec); ((base)->tv_nsec) = ((base)->tv_nsec) % (1000 * 1000 * 1000); } } template<typename T> inline void SUB_TIMESPEC(T* base, const T* val) { // Do not care down flow. // if((base)->tv_nsec < (val)->tv_nsec){ --((base)->tv_sec); (base)->tv_nsec += 1000 * 1000 * 1000; } (base)->tv_nsec -= (val)->tv_nsec; (base)->tv_sec -= (val)->tv_sec; } template<typename T> inline void INIT_TIMESPEC(T* ptr) { SET_TIMESPEC(ptr, 0, 0L); } template<typename T> inline bool RT_TIMESPEC(T* ptr) { if(-1 == clock_gettime(CLOCK_REALTIME_COARSE, ptr)){ return false; } return true; } template<typename T> inline void STR_MATE_TIMESPEC(T* ptr) { if(!RT_TIMESPEC(ptr)){ INIT_TIMESPEC(ptr); } } template<typename T> inline void FIN_MATE_TIMESPEC(T* ptr) { T ts; if(!RT_TIMESPEC(&ts)){ INIT_TIMESPEC(&ts); } SUB_TIMESPEC(&ts, ptr); COPY_TIMESPEC(ptr, &ts); } template<typename T> inline void FIN_MATE_TIMESPEC2(T* start, T* fin, T* elapsed) { if(!RT_TIMESPEC(fin)){ INIT_TIMESPEC(fin); } COPY_TIMESPEC(elapsed, fin); SUB_TIMESPEC(elapsed, start); } #else // __cplusplus #define SET_TIMESPEC(ptr, sec, nsec) \ { \ (ptr)->tv_sec = sec; \ if(nsec >= (1000 * 1000 * 1000)){ \ (ptr)->tv_sec += (nsec / (1000 * 1000 * 1000)); \ } \ (ptr)->tv_nsec = (nsec % (1000 * 1000 * 1000)); \ } #define COPY_TIMESPEC(dest, src) \ { \ (dest)->tv_sec = (src)->tv_sec; \ (dest)->tv_nsec = (src)->tv_nsec; \ } #define COMPARE_TIMESPEC(data1, data2) ( (data1)->tv_sec > (data2)->tv_sec ? 1 : \ (data1)->tv_sec < (data2)->tv_sec ? -1 : \ (data1)->tv_nsec > (data2)->tv_nsec ? 1 : \ (data1)->tv_nsec < (data2)->tv_nsec ? -1 : 0 ) #define ADD_TIMESPEC(base, val) \ { \ (base)->tv_sec = (val)->tv_sec; \ (base)->tv_nsec = (val)->tv_nsec; \ if(1 <= (((base)->tv_nsec) / (1000 * 1000 * 1000))){ \ ((base)->tv_sec)++; \ ((base)->tv_nsec) = ((base)->tv_nsec) % (1000 * 1000 * 1000); \ } \ } #define SUB_TIMESPEC(base, val) \ { \ if((base)->tv_nsec < (val)->tv_nsec){ \ --((base)->tv_sec); \ (base)->tv_nsec += 1000 * 1000 * 1000; \ } \ (base)->tv_nsec -= (val)->tv_nsec; \ (base)->tv_sec -= (val)->tv_sec; \ } #define INIT_TIMESPEC(ptr) SET_TIMESPEC(ptr, 0, 0L) #define RT_TIMESPEC(ptr) (0 == clock_gettime(CLOCK_REALTIME_COARSE, ptr)) #define STR_MATE_TIMESPEC(ptr) \ { \ if(!RT_TIMESPEC(ptr)){ \ INIT_TIMESPEC(ptr); \ } \ } #define FIN_MATE_TIMESPEC(ptr) \ { \ struct timespec ts; \ if(!RT_TIMESPEC(&ts)){ \ INIT_TIMESPEC(&ts); \ } \ SUB_TIMESPEC(&ts, ptr); \ COPY_TIMESPEC(ptr, &ts); \ } #define FIN_MATE_TIMESPEC2(start, fin, elapsed) \ { \ if(!RT_TIMESPEC(fin)){ \ INIT_TIMESPEC(fin); \ } \ COPY_TIMESPEC(elapsed, fin); \ SUB_TIMESPEC(elapsed, start); \ } #endif // __cplusplus //--------------------------------------------------------- // Utility Functions //--------------------------------------------------------- DECL_EXTERN_C_START // File ssize_t chm_pread(int fd, void *buf, size_t count, off_t offset); ssize_t chm_pwrite(int fd, const void *buf, size_t count, off_t offset); unsigned char* chm_read(int fd, size_t* psize); bool is_file_exist(const char* file); bool is_file_safe_exist(const char* file); bool is_file_safe_exist_ex(const char* file, bool is_msg); bool is_dir_exist(const char* path); bool get_file_size(const char* file, size_t& length); bool move_file_to_backup(const char* file, const char* pext); bool truncate_filling_zero(int fd, size_t length, int pagesize); DECL_EXTERN_C_END #endif // CHMUTIL_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmthread.h
<gh_stars>10-100 /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMTHREAD_H #define CHMTHREAD_H #include <pthread.h> #include <vector> #include <fullock/flckstructure.h> #include <fullock/flckbaselist.tcc> class ChmThread; //--------------------------------------------------------- // Utility inline function //--------------------------------------------------------- inline bool CHMTHREAD_INITIALIZE_CONDVAL(pthread_mutex_t& cond_mutex, pthread_cond_t& cond_val) { pthread_mutex_init(&cond_mutex, NULL); if(0 != pthread_cond_init(&cond_val, NULL)){ return false; } return true; } inline bool CHMTHREAD_DESTROY_CONDVAL(pthread_mutex_t& cond_mutex, pthread_cond_t& cond_val) { bool result = true; if(0 != pthread_cond_destroy(&cond_val)){ result = false; } if(0 != pthread_mutex_destroy(&cond_mutex)){ result = false; } return result; } //--------------------------------------------------------- // Typedefs //--------------------------------------------------------- typedef int chmthsts_t; typedef uint64_t chmthparam_t; typedef bool (*Tfp_Chm_WorkerProc)(void*, chmthparam_t); // result: true -> continue, false -> exit thread typedef bool (*Tfp_Chm_FreeParameter)(void*, chmthparam_t); typedef struct chmth_wp_param{ std::string thread_name; ChmThread* pchmthread; // pointer to ChmThread volatile chmthsts_t status; // exit, sleep, working... bool is_once; // if true, thread exits after working once bool is_nosleep; // if true, thread never sleep bool is_keep_evcnt; // if false, no event stacking Tfp_Chm_WorkerProc work_proc; void* common_param; chmthparam_t wp_param; pthread_mutex_t cond_mutex; pthread_cond_t cond_val; pthread_t threadid; // thread id chmth_wp_param() : thread_name(""), pchmthread(NULL), status(0), is_once(false), is_nosleep(false), is_keep_evcnt(true), work_proc(NULL), common_param(NULL), wp_param(0) // status = CHMTHCOM_SLEEP { CHMTHREAD_INITIALIZE_CONDVAL(cond_mutex, cond_val); } ~chmth_wp_param() { CHMTHREAD_DESTROY_CONDVAL(cond_mutex, cond_val); } }CHMTHWP_PARAM, *PCHMTHWP_PARAM; typedef std::vector<PCHMTHWP_PARAM> chmthlist_t; typedef std::map<chmthparam_t, PCHMTHWP_PARAM> chmthmap_t; //--------------------------------------------------------- // ChmThread Class //--------------------------------------------------------- class ChmThread { public: static const chmthsts_t CHMTHCOM_EXIT = -1; static const chmthsts_t CHMTHCOM_SLEEP = 0; static const chmthsts_t CHMTHCOM_WORK = 1; // 1 and over 1 protected: std::string thread_name; Tfp_Chm_FreeParameter free_proc; volatile int list_lockval; // like mutex chmthlist_t chmthlist; // all threads chmthlist_t chmthsleeps; // sleeping threads chmthmap_t chmthworkmap; // working threads protected: static void* WorkerProc(void* param); PCHMTHWP_PARAM DispatchThread(chmthparam_t req_param, bool is_wait, bool* pis_already_working); bool WaitExitThread(PCHMTHWP_PARAM thread_param); public: explicit ChmThread(const char* pname = NULL); virtual ~ChmThread(); bool HasThread(void) const { return (0 < chmthlist.size()); } int GetThreadCount(void) const { return chmthlist.size(); } int CreateThreads(int thread_cnt, Tfp_Chm_WorkerProc work_func, Tfp_Chm_FreeParameter free_func = NULL, void* common_param = NULL, chmthparam_t wp_param = 0, bool is_sleep_at_start = true, bool is_once = false, bool is_nosleep = false, bool is_keep_evcnt = true); int ExitThreads(int thread_cnt, bool is_wait = true); bool ExitAllThreads(void); bool IsThreadRun(void); bool DoWorkThread(chmthparam_t req_param = 0); bool ClearSelfWorkerStatus(void); chmthparam_t GetSelfWorkerParam(void); }; #endif // CHMTHREAD_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmcommon.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMCOMMON_H #define CHMCOMMON_H #ifdef HAVE_CONFIG_H #include "config.h" #endif //--------------------------------------------------------- // Macros for compiler //--------------------------------------------------------- #ifndef CHMPX_NOWEAK #define CHMPX_ATTR_WEAK __attribute__ ((weak,unused)) #else #define CHMPX_ATTR_WEAK #endif #ifndef CHMPX_NOPADDING #define CHMPX_ATTR_PACKED __attribute__ ((packed)) #else #define CHMPX_ATTR_PACKED #endif #if defined(__cplusplus) #define DECL_EXTERN_C_START extern "C" { #define DECL_EXTERN_C_END } #else // __cplusplus #define DECL_EXTERN_C_START #define DECL_EXTERN_C_END #endif // __cplusplus //--------------------------------------------------------- // Templates & macros //--------------------------------------------------------- #if defined(__cplusplus) template<typename T> inline bool CHMEMPTYSTR(const T pstr) { return (NULL == (pstr) || '\0' == *(pstr)) ? true : false; } #else // __cplusplus #define CHMEMPTYSTR(pstr) (NULL == (pstr) || '\0' == *(pstr)) #endif // __cplusplus #define CHMPXSTRJOIN(first, second) first ## second #if defined(__cplusplus) #define CHM_OFFSET(baseaddr, offset, type) (offset > 0 ? reinterpret_cast<type>(reinterpret_cast<off_t>(baseaddr) + offset) : reinterpret_cast<type>(baseaddr)) // convert pointer with offset #define CHM_ABS(baseaddr, offset, type) (reinterpret_cast<off_t>(offset) > 0 ? reinterpret_cast<type>(reinterpret_cast<off_t>(baseaddr) + reinterpret_cast<off_t>(offset)) : 0) // To Absolute address #define CHM_REL(baseaddr, address, type) (address > 0 ? reinterpret_cast<type>(reinterpret_cast<off_t>(address) - reinterpret_cast<off_t>(baseaddr)) : 0) // To Relative address #else // __cplusplus #define CHM_OFFSET(baseaddr, offset, type) (offset > 0 ? (type)((off_t)baseaddr + offset) : (type)baseaddr) // convert pointer with offset #define CHM_ABS(baseaddr, offset, type) (offset > 0 ? (type)((off_t)baseaddr + (off_t)offset) : 0) // To Absolute address #define CHM_REL(baseaddr, address, type) (address > 0 ? (type)((off_t)address - (off_t)baseaddr) : 0) // To Relative address #endif // __cplusplus //--------------------------------------------------------- // Symbols //--------------------------------------------------------- #define CHM_INVALID_HANDLE (-1) #define CHM_INVALID_SOCK (-1) #define CHM_INVALID_TID 0 #define CHM_MAX_PATH_LEN 1024 #define CHMPX_VERSION_MAX 32 #define COMMIT_HASH_MAX 32 #define CUK_MAX 2048 // the CUK value is usually around 512 bytes, thus 2Kbytes is the upper limit with a margin. #define CUSTOM_ID_SEED_MAX 2048 // 2Kbytes maximum. #define EXTERNAL_EP_MAX 4 // can set 4 external endpoints #define GATEWAY_PEER_MAX 4 // can set 4 gateways #define FORWARD_PEER_MAX (GATEWAY_PEER_MAX) #define REVERSE_PEER_MAX (GATEWAY_PEER_MAX) #if defined(__cplusplus) #define CHM_INVALID_CHMPXHANDLE static_cast<uint64_t>(CHM_INVALID_HANDLE) #else // __cplusplus #define CHM_INVALID_CHMPXHANDLE (uint64_t)(CHM_INVALID_HANDLE) #endif // __cplusplus //--------------------------------------------------------- // For endian //--------------------------------------------------------- #ifndef _BSD_SOURCE #define _BSD_SOURCE #define SET_LOCAL_BSD_SOURCE 1 #endif #ifdef HAVE_ENDIAN_H #include <endian.h> #else #ifdef HAVE_SYS_ENDIAN_H #include <sys/endian.h> #endif #endif #ifdef SET_LOCAL_BSD_SOURCE #undef _BSD_SOURCE #endif //--------------------------------------------------------- // Compatibility //--------------------------------------------------------- // For clock_gettime #ifndef CLOCK_BOOTTIME #define CLOCK_BOOTTIME CLOCK_MONOTONIC #endif //--------------------------------------------------------- // types //--------------------------------------------------------- #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif // CHMCOMMON_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmstructure.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMSTRUCTURE_H #define CHMSTRUCTURE_H #include <netdb.h> #include <k2hash/k2hash.h> #include "chmcommon.h" DECL_EXTERN_C_START //--------------------------------------------------------- // Variable types //--------------------------------------------------------- typedef uint64_t chmpxid_t; typedef uint64_t msgid_t; typedef uint64_t serial_t; typedef unsigned char msgflag_t; typedef k2h_hash_t chmhash_t; typedef uint64_t chmpxsts_t; typedef uint64_t chmpxpos_t; typedef uint64_t logtype_t; typedef int chmss_ver_t; // SSL/TLS minimum version typedef enum chmpx_mode{ CHMPX_UNKNOWN = 0, CHMPX_SERVER, CHMPX_SLAVE }CHMPXMODE; typedef enum chmpxid_seed_type{ CHMPXID_SEED_NAME = 0, // default, seed from name and control port(before v1.0.71) CHMPXID_SEED_CUK, // seed from cuk CHMPXID_SEED_CTLENDPOINTS, // seed from control endpoints(no particular order) CHMPXID_SEED_CUSTOM // seed from CUSTOM_ID_SEED }CHMPXID_SEED_TYPE; //--------------------------------------------------------- // Symbols for CHMINFO structure version //--------------------------------------------------------- // Version 1.0 after chmpx version 1.0.59 // Version 1.1 after chmpx version 1.0.71 // // [NOTE] // Before CHMPX version 1.0.59, those do not have the CHMINFO structure version. // #define CHM_CHMINFO_VERSION_BUFLEN 32 #define CHM_CHMINFO_VERSION_PREFIX "CHMINFO_VERSION" #define CHM_CHMINFO_OLD_VERSION_1_0 "1.0" #define CHM_CHMINFO_CUR_VERSION "1.1" #define CHM_CHMINFO_CUR_VERSION_STR CHM_CHMINFO_VERSION_PREFIX " " CHM_CHMINFO_CUR_VERSION //--------------------------------------------------------- // Symbols for SSL/TLS minimum version //--------------------------------------------------------- // [NOTE] // These symbols is used in chmconf.cc for analyzing option. // #define CHM_SSLTLS_VER_ERROR -1 #define CHM_SSLTLS_VER_DEFAULT 0 #define CHM_SSLTLS_VER_SSLV2 (CHM_SSLTLS_VER_DEFAULT + 1) #define CHM_SSLTLS_VER_SSLV3 (CHM_SSLTLS_VER_SSLV2 + 1) #define CHM_SSLTLS_VER_TLSV1_0 (CHM_SSLTLS_VER_SSLV3 + 1) #define CHM_SSLTLS_VER_TLSV1_1 (CHM_SSLTLS_VER_TLSV1_0 + 1) #define CHM_SSLTLS_VER_TLSV1_2 (CHM_SSLTLS_VER_TLSV1_1 + 1) #define CHM_SSLTLS_VER_TLSV1_3 (CHM_SSLTLS_VER_TLSV1_2 + 1) #define CHM_SSLTLS_VER_MAX CHM_SSLTLS_VER_TLSV1_3 #define CHM_GET_STR_SSLTLS_VERSION(ver) ( CHM_SSLTLS_VER_DEFAULT == ver ? "(default)": \ CHM_SSLTLS_VER_SSLV2 == ver ? "SSL v2" : \ CHM_SSLTLS_VER_SSLV3 == ver ? "SSL v3" : \ CHM_SSLTLS_VER_TLSV1_0 == ver ? "TLS v1.0" : \ CHM_SSLTLS_VER_TLSV1_1 == ver ? "TLS v1.1" : \ CHM_SSLTLS_VER_TLSV1_2 == ver ? "TLS v1.2" : \ CHM_SSLTLS_VER_TLSV1_3 == ver ? "TLS v1.3" : "Unknown" \ ) //--------------------------------------------------------- // Symbols & Macros //--------------------------------------------------------- #define CHM_INVALID_ID (-1) #define CHM_INVALID_PORT (-1) #define CHM_INVALID_CHMPXLISTPOS 0L #define CHM_INVALID_PID 0 DECL_EXTERN_C_END #if defined(__cplusplus) #define CHM_INVALID_CHMPXID static_cast<chmpxid_t>(CHM_INVALID_ID) #define CHM_INVALID_MSGID static_cast<msgid_t>(CHM_INVALID_ID) #define CHM_INVALID_HASHVAL static_cast<chmhash_t>(-1) // when hash range is under 64bit. #else // __cplusplus #define CHM_INVALID_CHMPXID (chmpxid_t)(CHM_INVALID_ID) #define CHM_INVALID_MSGID (msgid_t)(CHM_INVALID_ID) #define CHM_INVALID_HASHVAL (chmhash_t)(-1) // when hash range is under 64bit. #endif // __cplusplus DECL_EXTERN_C_START #define MAX_GROUP_LENGTH 256 #define DEFAULT_CHMPX_COUNT 1024 // default maximum node(server & slave) count #define MAX_CHMPX_COUNT (1024 * 32) // maximum node(server & slave) count #define DEFAULT_REPLICA_COUNT 0 // default replica count(always random mode sets this value) #define CHMPXID_MAP_SIZE 4096 // chmpxid map array size(maximum average conflict MAX_CHMPX_COUNT / CHMPXID_MAP_SIZE) #define CHMPXID_MAP_MASK (CHMPXID_MAP_SIZE - 1) // 0xFFF #define MAX_MQUEUE_COUNT 32768 // Maximum MQ count in boxes #define MAX_SERVER_MQ_CNT 128 // Maximum MQ count server used #define DEFAULT_SERVER_MQ_CNT 1 // #define MAX_CLIENT_MQ_CNT (MAX_MQUEUE_COUNT - MAX_SERVER_MQ_CNT) // Maximum MQ count all client processes used #define DEFAULT_CLIENT_MQ_CNT 8192 // #define MAX_QUEUE_PER_SERVERMQ 128 // Maximum Queue count by each server/slave node MQ #define DEFAULT_QUEUE_PER_SERVERMQ 8 // #define MAX_QUEUE_PER_CLIENTMQ 128 // Maximum Queue count by each client processes MQ #define DEFAULT_QUEUE_PER_CLIENTMQ 1 // #define MAX_MQ_PER_CLIENT MAX_SERVER_MQ_CNT // Maximum MQ count by each client processes #define DEFAULT_MQ_PER_CLIENT 1 // #define MAX_MQ_PER_ATTACH MAX_SERVER_MQ_CNT // Maximum MQ count by attaching #define DEFAULT_MQ_PER_ATTACH 1 // #define DEFAULT_MQUEUE_COUNT (DEFAULT_CLIENT_MQ_CNT + DEFAULT_SERVER_MQ_CNT) // Default MQ count in boxes #define DEFAULT_HISTLOG_COUNT 8192 // default #define MAX_HISTLOG_COUNT 32768 // upper limit //--------------------- // CHMPX Status(chmpxsts_t) //--------------------- // Status value is following bit parts. // //------------------------------------------------------------------------------- // LIVE RING/SERVICE ACTION OPERATE SUSPEND(NOT JOIN CLIENT) //------------------------------------------------------------------------------- // UP SLAVE NOACT NOTHING NOSUP // DOWN SERVICE IN ADD PENDING SUSPEND // SERVICE OUT DELETE DOING // DONE //------------------------------------------------------------------------------- // #define CHMPXSTS_MASK_LIVE 0x1 // #define CHMPXSTS_MASK_RING 0x30 // #define CHMPXSTS_MASK_ACTION 0x300 // #define CHMPXSTS_MASK_OPERATE 0x3000 // #define CHMPXSTS_MASK_SUSPEND 0x10000 // #define CHMPXSTS_MASK_ALL (CHMPXSTS_MASK_LIVE | CHMPXSTS_MASK_RING | CHMPXSTS_MASK_ACTION | CHMPXSTS_MASK_OPERATE | CHMPXSTS_MASK_SUSPEND) //--------------------- // (status & CHMPXSTS_MASK_LIVE) #define CHMPXSTS_VAL_DOWN 0x0 // Server/Slave is DOWN #define CHMPXSTS_VAL_UP 0x1 // Server/Slave is UP // (status & CHMPXSTS_MASK_RING) #define CHMPXSTS_VAL_SLAVE 0x00 // SLAVE (not on RING) #define CHMPXSTS_VAL_SRVOUT 0x10 // SERVER is SERVICE OUT (on RING) #define CHMPXSTS_VAL_SRVIN 0x20 // SERVER is SERVICE IN (on RING) // (status & CHMPXSTS_MASK_ACTION) #define CHMPXSTS_VAL_NOACT 0x000 // No Action #define CHMPXSTS_VAL_ADD 0x100 // Action is ADD #define CHMPXSTS_VAL_DELETE 0x200 // Action is DELETE // (status & CHMPXSTS_MASK_ACTION) #define CHMPXSTS_VAL_NOTHING 0x0000 // No Operating #define CHMPXSTS_VAL_PENDING 0x1000 // PENDING #define CHMPXSTS_VAL_DOING 0x2000 // DOING #define CHMPXSTS_VAL_DONE 0x3000 // DONE // (status & CHMPXSTS_MASK_SUSPEND) #define CHMPXSTS_VAL_NOSUP 0x00000 // NO SUSPEND #define CHMPXSTS_VAL_SUSPEND 0x10000 // SUSPEND //--------------------- #define CHMPXSTS_SLAVE_UP_NORMAL (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SLAVE | CHMPXSTS_VAL_NOACT | CHMPXSTS_VAL_NOTHING) #define CHMPXSTS_SLAVE_DOWN_NORMAL (CHMPXSTS_VAL_DOWN | CHMPXSTS_VAL_SLAVE | CHMPXSTS_VAL_NOACT | CHMPXSTS_VAL_NOTHING) #define CHMPXSTS_SRVOUT_UP_NORMAL (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVOUT | CHMPXSTS_VAL_NOACT | CHMPXSTS_VAL_NOTHING) #define CHMPXSTS_SRVOUT_DOWN_NORMAL (CHMPXSTS_VAL_DOWN | CHMPXSTS_VAL_SRVOUT | CHMPXSTS_VAL_NOACT | CHMPXSTS_VAL_NOTHING) #define CHMPXSTS_SRVIN_UP_NORMAL (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_NOACT | CHMPXSTS_VAL_NOTHING) #define CHMPXSTS_SRVIN_UP_PENDING (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_NOACT | CHMPXSTS_VAL_PENDING) #define CHMPXSTS_SRVIN_UP_MERGING (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_NOACT | CHMPXSTS_VAL_DOING) #define CHMPXSTS_SRVIN_UP_MERGED (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_NOACT | CHMPXSTS_VAL_DONE) #define CHMPXSTS_SRVIN_UP_ADDPENDING (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_ADD | CHMPXSTS_VAL_PENDING) #define CHMPXSTS_SRVIN_UP_ADDING (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_ADD | CHMPXSTS_VAL_DOING) #define CHMPXSTS_SRVIN_UP_ADDED (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_ADD | CHMPXSTS_VAL_DONE) #define CHMPXSTS_SRVIN_UP_DELPENDING (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_DELETE | CHMPXSTS_VAL_PENDING) #define CHMPXSTS_SRVIN_UP_DELETING (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_DELETE | CHMPXSTS_VAL_DOING) #define CHMPXSTS_SRVIN_UP_DELETED (CHMPXSTS_VAL_UP | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_DELETE | CHMPXSTS_VAL_DONE) #define CHMPXSTS_SRVIN_DOWN_NORMAL (CHMPXSTS_VAL_DOWN | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_NOACT | CHMPXSTS_VAL_NOTHING) #define CHMPXSTS_SRVIN_DOWN_DELPENDING (CHMPXSTS_VAL_DOWN | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_DELETE | CHMPXSTS_VAL_PENDING) #define CHMPXSTS_SRVIN_DOWN_DELETED (CHMPXSTS_VAL_DOWN | CHMPXSTS_VAL_SRVIN | CHMPXSTS_VAL_DELETE | CHMPXSTS_VAL_DONE) //--------------------- #define SET_CHMPXSTS_DOWN(status) (status = (status & ~CHMPXSTS_MASK_LIVE) ) #define SET_CHMPXSTS_UP(status) (status = (status & ~CHMPXSTS_MASK_LIVE) | CHMPXSTS_VAL_UP) #define SET_CHMPXSTS_SLAVE(status) (status = (status & ~CHMPXSTS_MASK_RING) ) #define SET_CHMPXSTS_SRVOUT(status) (status = (status & ~CHMPXSTS_MASK_RING) | CHMPXSTS_VAL_SRVOUT) #define SET_CHMPXSTS_SRVIN(status) (status = (status & ~CHMPXSTS_MASK_RING) | CHMPXSTS_VAL_SRVIN) #define SET_CHMPXSTS_NOACT(status) (status = (status & ~CHMPXSTS_MASK_ACTION) ) #define SET_CHMPXSTS_ADD(status) (status = (status & ~CHMPXSTS_MASK_ACTION) | CHMPXSTS_VAL_ADD) #define SET_CHMPXSTS_DELETE(status) (status = (status & ~CHMPXSTS_MASK_ACTION) | CHMPXSTS_VAL_DELETE) #define SET_CHMPXSTS_NOTHING(status) (status = (status & ~CHMPXSTS_MASK_OPERATE) ) #define SET_CHMPXSTS_PENDING(status) (status = (status & ~CHMPXSTS_MASK_OPERATE) | CHMPXSTS_VAL_PENDING) #define SET_CHMPXSTS_DOING(status) (status = (status & ~CHMPXSTS_MASK_OPERATE) | CHMPXSTS_VAL_DOING) #define SET_CHMPXSTS_DONE(status) (status = (status & ~CHMPXSTS_MASK_OPERATE) | CHMPXSTS_VAL_DONE) #define SET_CHMPXSTS_NOSUP(status) (status = (status & ~CHMPXSTS_MASK_SUSPEND) ) #define SET_CHMPXSTS_SUSPEND(status) (status = (status & ~CHMPXSTS_MASK_SUSPEND) | CHMPXSTS_VAL_SUSPEND) //--------------------- #define IS_CHMPXSTS_DOWN(status) (CHMPXSTS_VAL_DOWN == (status & CHMPXSTS_MASK_LIVE)) #define IS_CHMPXSTS_UP(status) (CHMPXSTS_VAL_UP == (status & CHMPXSTS_MASK_LIVE)) #define IS_CHMPXSTS_SLAVE(status) (CHMPXSTS_VAL_SLAVE == (status & CHMPXSTS_MASK_RING)) #define IS_CHMPXSTS_SRVOUT(status) (CHMPXSTS_VAL_SRVOUT == (status & CHMPXSTS_MASK_RING)) #define IS_CHMPXSTS_SRVIN(status) (CHMPXSTS_VAL_SRVIN == (status & CHMPXSTS_MASK_RING)) #define IS_CHMPXSTS_SERVER(status) (IS_CHMPXSTS_SRVOUT(status) || IS_CHMPXSTS_SRVIN(status)) #define IS_CHMPXSTS_ONRING(status) IS_CHMPXSTS_SERVER(status) #define IS_CHMPXSTS_NOACT(status) (CHMPXSTS_VAL_NOACT == (status & CHMPXSTS_MASK_ACTION)) #define IS_CHMPXSTS_ADD(status) (CHMPXSTS_VAL_ADD == (status & CHMPXSTS_MASK_ACTION)) #define IS_CHMPXSTS_DELETE(status) (CHMPXSTS_VAL_DELETE == (status & CHMPXSTS_MASK_ACTION)) #define IS_CHMPXSTS_NOTHING(status) (CHMPXSTS_VAL_NOTHING == (status & CHMPXSTS_MASK_OPERATE)) #define IS_CHMPXSTS_PENDING(status) (CHMPXSTS_VAL_PENDING == (status & CHMPXSTS_MASK_OPERATE)) #define IS_CHMPXSTS_DOING(status) (CHMPXSTS_VAL_DOING == (status & CHMPXSTS_MASK_OPERATE)) #define IS_CHMPXSTS_DONE(status) (CHMPXSTS_VAL_DONE == (status & CHMPXSTS_MASK_OPERATE)) #define IS_CHMPXSTS_NOSUP(status) (CHMPXSTS_VAL_NOSUP == (status & CHMPXSTS_MASK_SUSPEND)) #define IS_CHMPXSTS_SUSPEND(status) (CHMPXSTS_VAL_SUSPEND == (status & CHMPXSTS_MASK_SUSPEND)) #define IS_CHMPXSTS_OPERATING(status) (IS_CHMPXSTS_DOING(status) || IS_CHMPXSTS_DONE(status)) #define IS_SAFE_CHMPXSTS_EX(status) ( CHMPXSTS_SLAVE_UP_NORMAL == status || \ CHMPXSTS_SLAVE_DOWN_NORMAL == status || \ CHMPXSTS_SRVIN_UP_NORMAL == status || \ CHMPXSTS_SRVIN_UP_PENDING == status || \ CHMPXSTS_SRVIN_UP_MERGING == status || \ CHMPXSTS_SRVIN_UP_MERGED == status || \ CHMPXSTS_SRVIN_UP_ADDPENDING == status || \ CHMPXSTS_SRVIN_UP_ADDING == status || \ CHMPXSTS_SRVIN_UP_ADDED == status || \ CHMPXSTS_SRVIN_UP_DELPENDING == status || \ CHMPXSTS_SRVIN_UP_DELETING == status || \ CHMPXSTS_SRVIN_UP_DELETED == status || \ CHMPXSTS_SRVIN_DOWN_NORMAL == status || \ CHMPXSTS_SRVIN_DOWN_DELPENDING == status || \ CHMPXSTS_SRVIN_DOWN_DELETED == status || \ CHMPXSTS_SRVOUT_UP_NORMAL == status || \ CHMPXSTS_SRVOUT_DOWN_NORMAL == status ) #define IS_SAFE_CHMPXSTS(status) ( (0 == (status & ~CHMPXSTS_MASK_ALL)) && \ IS_SAFE_CHMPXSTS_EX((status & ~CHMPXSTS_MASK_SUSPEND)) ) //--------------------- #define IS_CHMPXSTS_SERVICING(status) ( CHMPXSTS_SRVIN_UP_NORMAL == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_DELPENDING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_DELETING == (status & ~CHMPXSTS_MASK_SUSPEND) ) #define IS_CHMPXSTS_BASEHASH(status) ( CHMPXSTS_SRVIN_UP_NORMAL == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_PENDING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_MERGING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_MERGED == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_DELPENDING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_DELETING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_DELETED == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_DOWN_NORMAL == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_DOWN_DELPENDING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_DOWN_DELETED == (status & ~CHMPXSTS_MASK_SUSPEND) ) #define IS_CHMPXSTS_PENDINGHASH(status) ( CHMPXSTS_SRVIN_UP_NORMAL == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_PENDING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_MERGING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_MERGED == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_ADDPENDING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_ADDING == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_UP_ADDED == (status & ~CHMPXSTS_MASK_SUSPEND) || \ CHMPXSTS_SRVIN_DOWN_NORMAL == (status & ~CHMPXSTS_MASK_SUSPEND) ) //--------------------- #define STR_CHMPXSTS_ISSAFE(status) ( IS_SAFE_CHMPXSTS(status) ? "SAFE" : "NOT SAFE") #define STR_CHMPXSTS_LIVE(status) ( IS_CHMPXSTS_DOWN(status) ? "[DOWN]" : "[UP]" ) #define STR_CHMPXSTS_RING(status) ( IS_CHMPXSTS_SLAVE(status) ? "[SLAVE]" : \ IS_CHMPXSTS_SRVOUT(status) ? "[SERVICE OUT]" : \ IS_CHMPXSTS_SRVIN(status) ? "[SERVICE IN]" : "[Unknown RING]") #define STR_CHMPXSTS_ACTION(status) ( IS_CHMPXSTS_NOACT(status) ? "[n/a]" : \ IS_CHMPXSTS_ADD(status) ? "[ADD]" : \ IS_CHMPXSTS_DELETE(status) ? "[DELETE]" : "[unknown ACTION]") #define STR_CHMPXSTS_OPERATE(status) ( IS_CHMPXSTS_NOTHING(status) ? "[Nothing]" : \ IS_CHMPXSTS_PENDING(status) ? "[Pending]" : \ IS_CHMPXSTS_DOING(status) ? "[Doing]" : \ IS_CHMPXSTS_DONE(status) ? "[Done]" : "[unknown OPERATION]") #define STR_CHMPXSTS_SUSPEND(status) ( IS_CHMPXSTS_NOSUP(status) ? "[NoSuspend]" : \ IS_CHMPXSTS_SUSPEND(status) ? "[Suspend]" : "[unknown SUSPEND]") //--------------------- #define CHANGE_CHMPXSTS_TO_DOWN(status) \ { \ if(IS_CHMPXSTS_SRVIN(status)){ \ if(IS_CHMPXSTS_UP(status)){ \ if(IS_CHMPXSTS_NOACT(status)){ \ status = CHMPXSTS_SRVIN_DOWN_NORMAL; \ }else if(IS_CHMPXSTS_ADD(status)){ \ status = CHMPXSTS_SRVOUT_DOWN_NORMAL; \ }else if(IS_CHMPXSTS_DELETE(status)){ \ if(IS_CHMPXSTS_OPERATING(status)){ \ status = CHMPXSTS_SRVIN_DOWN_DELETED; \ }else{ \ status = CHMPXSTS_SRVIN_DOWN_DELPENDING; \ } \ } \ }else if(IS_CHMPXSTS_DOWN(status)){ \ if(IS_CHMPXSTS_DELETE(status)){ \ status = CHMPXSTS_SRVIN_DOWN_DELPENDING; \ }else{ \ status = CHMPXSTS_SRVIN_DOWN_NORMAL; \ } \ } \ }else if(IS_CHMPXSTS_SRVOUT(status)){ \ status = CHMPXSTS_SRVOUT_DOWN_NORMAL; \ } \ } #define CHANGE_CHMPXSTS_TO_SRVOUT(status) \ { \ if(IS_CHMPXSTS_SRVIN(status)){ \ if(IS_CHMPXSTS_UP(status)){ \ if(IS_CHMPXSTS_NOACT(status)){ \ if(!IS_CHMPXSTS_OPERATING(status)){ \ status = CHMPXSTS_SRVIN_UP_DELPENDING; \ if(IS_CHMPXSTS_NOSUP(status)){ \ CHANGE_CHMPXSTS_TO_NOSUP(status); \ }else{ \ CHANGE_CHMPXSTS_TO_SUSPEND(status); \ } \ } \ }else if(IS_CHMPXSTS_ADD(status)){ \ if(!IS_CHMPXSTS_OPERATING(status)){ \ status = CHMPXSTS_SRVOUT_UP_NORMAL; \ if(IS_CHMPXSTS_NOSUP(status)){ \ CHANGE_CHMPXSTS_TO_NOSUP(status); \ }else{ \ CHANGE_CHMPXSTS_TO_SUSPEND(status); \ } \ } \ } \ }else if(IS_CHMPXSTS_DOWN(status)){ \ if(IS_CHMPXSTS_NOACT(status)){ \ status = CHMPXSTS_SRVIN_DOWN_DELPENDING; \ } \ } \ } \ } #define CHANGE_CHMPXSTS_TO_SRVIN(status) \ { \ if(IS_CHMPXSTS_SRVIN(status)){ \ if(IS_CHMPXSTS_UP(status)){ \ if(IS_CHMPXSTS_DELETE(status)){ \ if(IS_CHMPXSTS_PENDING(status)){ \ if(IS_CHMPXSTS_NOSUP(status)){ \ status = CHMPXSTS_SRVIN_UP_PENDING; \ }else{ \ status = CHMPXSTS_SRVIN_UP_NORMAL; \ CHANGE_CHMPXSTS_TO_SUSPEND(status); \ } \ } \ } \ } \ }else if(IS_CHMPXSTS_SRVOUT(status)){ \ if(IS_CHMPXSTS_UP(status)){ \ if(IS_CHMPXSTS_NOACT(status)){ \ if(IS_CHMPXSTS_NOSUP(status)){ \ status = CHMPXSTS_SRVIN_UP_ADDPENDING; \ } \ } \ } \ } \ } #define CHANGE_CHMPXSTS_SUSPEND_FLAG(status, is_suspend) \ { \ if(IS_CHMPXSTS_DOWN(status) || IS_CHMPXSTS_SLAVE(status)){ \ SET_CHMPXSTS_NOSUP(status); \ }else{ \ if(is_suspend){ \ SET_CHMPXSTS_SUSPEND(status); \ }else{ \ SET_CHMPXSTS_NOSUP(status); \ } \ } \ } #define CHANGE_CHMPXSTS_TO_SUSPEND(status) CHANGE_CHMPXSTS_SUSPEND_FLAG(status, true) #define CHANGE_CHMPXSTS_TO_NOSUP(status) CHANGE_CHMPXSTS_SUSPEND_FLAG(status, false) //--------------------- // MQMSGHEAD flag //--------------------- // This flag has two status. // 1) Assigned or not assigned. // 2) Activated or disactivated in assigned MQ // * Not assigned flag must not be set with activated flag. // #define MQFLAG_VAL_NOTASSIGNED 0x0 // not assigned #define MQFLAG_VAL_ASSIGNED 0x1 // assigned #define MQFLAG_VAL_ACTIVATED 0x2 // activated #define MQFLAG_VAL_CHMPXPROC 0x4 // chmpx process used #define MQFLAG_VAL_CLIENTPROC 0x8 // client process used #define MQFLAG_MASK_ASSIGNED (MQFLAG_VAL_ASSIGNED) #define MQFLAG_MASK_ACTIVATED (MQFLAG_VAL_ACTIVATED) #define MQFLAG_MASK_KIND (MQFLAG_VAL_CHMPXPROC | MQFLAG_VAL_CLIENTPROC) #define MQFLAG_MASK_STATUS (MQFLAG_MASK_ASSIGNED | MQFLAG_MASK_ACTIVATED) #define MQFLAG_MASK_ALL (MQFLAG_MASK_ASSIGNED | MQFLAG_MASK_ACTIVATED | MQFLAG_MASK_KIND) #define SET_MQFLAG_INITIALIZED(flag) (flag = 0x0) #define SET_MQFLAG_NOTASSIGNED(flag) (flag = (flag & ~MQFLAG_MASK_STATUS) ) #define SET_MQFLAG_ASSIGNED(flag) (flag = (flag & ~MQFLAG_MASK_STATUS) | MQFLAG_VAL_ASSIGNED) #define SET_MQFLAG_ACTIVATED(flag) (flag = (flag & ~MQFLAG_MASK_STATUS) | MQFLAG_VAL_ASSIGNED | MQFLAG_VAL_ACTIVATED) #define SET_MQFLAG_DISACTIVATED(flag) SET_MQFLAG_ASSIGNED(flag) #define SET_MQFLAG_CHMPXPROC(flag) (flag = (flag & ~MQFLAG_MASK_KIND) | MQFLAG_VAL_CHMPXPROC) #define SET_MQFLAG_CLIENTPROC(flag) (flag = (flag & ~MQFLAG_MASK_KIND) | MQFLAG_VAL_CLIENTPROC) #define IS_MQFLAG_NOTASSIGNED(flag) (MQFLAG_VAL_NOTASSIGNED == (flag & MQFLAG_MASK_ASSIGNED)) #define IS_MQFLAG_ASSIGNED(flag) (MQFLAG_VAL_ASSIGNED == (flag & MQFLAG_MASK_ASSIGNED)) #define IS_MQFLAG_ACTIVATED(flag) (MQFLAG_VAL_ACTIVATED == (flag & MQFLAG_MASK_ACTIVATED)) #define IS_MQFLAG_DISACTIVATED(flag) (MQFLAG_VAL_ACTIVATED != (flag & MQFLAG_MASK_ACTIVATED)) #define IS_MQFLAG_CHMPXPROC(flag) (MQFLAG_VAL_CHMPXPROC == (flag & MQFLAG_MASK_KIND)) #define IS_MQFLAG_CLIENTPROC(flag) (MQFLAG_VAL_CLIENTPROC == (flag & MQFLAG_MASK_KIND)) #define STR_MQFLAG_ASSIGNED(flag) (IS_MQFLAG_ASSIGNED(flag) ? "[Assigned]" : "[Not Assigned]" ) #define STR_MQFLAG_ACTIVATED(flag) (IS_MQFLAG_ACTIVATED(flag) ? "[Activated]" : "[Disactivated]" ) #define STR_MQFLAG_KIND(flag) (IS_MQFLAG_CHMPXPROC(flag) ? "[Chmpx]" : IS_MQFLAG_CLIENTPROC(flag) ? "[Client]" : "[Free]" ) //--------------------- // CHMLOG type //--------------------- #define CHMLOG_TYPE_UNKOWN 0x0 #define CHMLOG_TYPE_ASSIGNED 0x1 #define CHMLOG_TYPE_OUTPUT 0x2 #define CHMLOG_TYPE_INPUT 0x4 #define CHMLOG_TYPE_SOCKET 0x8 #define CHMLOG_TYPE_MQ 0x10 #define CHMLOG_MASK_ASSIGNED (CHMLOG_TYPE_ASSIGNED) #define CHMLOG_MASK_DIRECTION (CHMLOG_TYPE_OUTPUT | CHMLOG_TYPE_INPUT) #define CHMLOG_MASK_DEVICE (CHMLOG_TYPE_SOCKET | CHMLOG_TYPE_MQ) #define CHMLOG_TYPE_NOTASSIGNED ( CHMLOG_TYPE_UNKOWN ) #define CHMLOG_TYPE_OUT_SOCKET ( CHMLOG_TYPE_ASSIGNED | CHMLOG_TYPE_OUTPUT | CHMLOG_TYPE_SOCKET ) #define CHMLOG_TYPE_IN_SOCKET ( CHMLOG_TYPE_ASSIGNED | CHMLOG_TYPE_INPUT | CHMLOG_TYPE_SOCKET ) #define CHMLOG_TYPE_OUT_MQ ( CHMLOG_TYPE_ASSIGNED | CHMLOG_TYPE_OUTPUT | CHMLOG_TYPE_MQ ) #define CHMLOG_TYPE_IN_MQ ( CHMLOG_TYPE_ASSIGNED | CHMLOG_TYPE_INPUT | CHMLOG_TYPE_MQ ) #define IS_CHMLOG_ASSIGNED(logtype) ( CHMLOG_TYPE_ASSIGNED == ( logtype & CHMLOG_MASK_ASSIGNED) ) #define IS_CHMLOG_INPUT(logtype) ( (CHMLOG_TYPE_ASSIGNED | CHMLOG_TYPE_INPUT) == ( logtype & (CHMLOG_MASK_ASSIGNED | CHMLOG_TYPE_INPUT)) ) #define IS_CHMLOG_OUTPUT(logtype) ( (CHMLOG_TYPE_ASSIGNED | CHMLOG_TYPE_OUTPUT) == ( logtype & (CHMLOG_MASK_ASSIGNED | CHMLOG_TYPE_OUTPUT)) ) #define IS_CHMLOG_SOCKET(logtype) ( (CHMLOG_TYPE_ASSIGNED | CHMLOG_TYPE_SOCKET) == ( logtype & (CHMLOG_MASK_ASSIGNED | CHMLOG_TYPE_SOCKET)) ) #define IS_CHMLOG_MQ(logtype) ( (CHMLOG_TYPE_ASSIGNED | CHMLOG_TYPE_MQ) == ( logtype & (CHMLOG_MASK_ASSIGNED | CHMLOG_TYPE_MQ)) ) #define IS_SAFE_CHMLOG_TYPE(logtype) ( CHMLOG_TYPE_NOTASSIGNED == logtype || \ CHMLOG_TYPE_OUT_SOCKET == logtype || \ CHMLOG_TYPE_IN_SOCKET == logtype || \ CHMLOG_TYPE_OUT_MQ == logtype || \ CHMLOG_TYPE_IN_MQ == logtype ) #define IS_SAFE_CHMLOG_MASK(logtype) ( 0 != (logtype & CHMLOG_MASK_ASSIGNED) || \ 0 != (logtype & CHMLOG_MASK_DIRECTION) || \ 0 != (logtype & CHMLOG_MASK_DEVICE) ) #define STR_CHMLOG_TYPE(logtype) ( CHMLOG_TYPE_NOTASSIGNED == logtype ? "[NotAssigned]" : \ CHMLOG_TYPE_OUT_SOCKET == logtype ? "[Output Socket]" : \ CHMLOG_TYPE_IN_SOCKET == logtype ? "[Input Socket]" : \ CHMLOG_TYPE_OUT_MQ == logtype ? "[Output MQ]" : \ CHMLOG_TYPE_IN_MQ == logtype ? "[Input MQ]" : "[Unsafe type]" ) //--------------------- // Set/Get sock flag //--------------------- #define SOCKTG_SOCK 0x1 #define SOCKTG_CTLSOCK 0x2 #define SOCKTG_SELFSOCK 0x4 #define SOCKTG_SELFCTLSOCK 0x8 #define SOCKTG_BOTH (SOCKTG_SOCK | SOCKTG_CTLSOCK) #define SOCKTG_BOTHSELF (SOCKTG_SELFSOCK | SOCKTG_SELFCTLSOCK) #define SOCKTG_ALL (SOCKTG_SOCK | SOCKTG_CTLSOCK | SOCKTG_SELFSOCK | SOCKTG_SELFCTLSOCK) #define IS_SOCKTG_SOCK(type) (0 != (type & SOCKTG_SOCK)) #define IS_SOCKTG_CTLSOCK(type) (0 != (type & SOCKTG_CTLSOCK)) #define IS_SOCKTG_SELFSOCK(type) (0 != (type & SOCKTG_SELFSOCK)) #define IS_SOCKTG_SELFCTLSOCK(type) (0 != (type & SOCKTG_SELFCTLSOCK)) //--------------------- // Close sock flag //--------------------- #define CLOSETG_SERVERS 1 #define CLOSETG_SLAVES 2 #define CLOSETG_BOTH (CLOSETG_SERVERS | CLOSETG_SLAVES) #define IS_CLOSETG_SERVERS(type) (0 != (type & CLOSETG_SERVERS)) #define IS_CLOSETG_SLAVES(type) (0 != (type & CLOSETG_SLAVES)) //--------------------- // Set/Get hash flag //--------------------- #define HASHTG_BASE 1 #define HASHTG_PENDING 2 #define HASHTG_BOTH (HASHTG_BASE | HASHTG_PENDING) #define IS_HASHTG_BASE(type) (0 != (type & HASHTG_BASE)) #define IS_HASHTG_PENDING(type) (0 != (type & HASHTG_PENDING)) //--------------------- // CLTPROCLIST //--------------------- #define MAX_CLTPROCLIST_COUNT(max_client_mq_cnt, mqcnt_per_attach) (1 + (max_client_mq_cnt / mqcnt_per_attach) + 1) //--------------------- // Others //--------------------- #define MASK64_HIBIT 0xFFFFFFFF00000000 #define MASK64_LOWBIT 0x00000000FFFFFFFF #define COMPOSE64(hi, low) (((hi & MASK64_LOWBIT) << 32) | (low & MASK64_LOWBIT)) // CHMPXMODE enum #define STRCHMPXMODE(mode) (CHMPX_SERVER == mode ? "server" : CHMPX_SLAVE == mode ? "slave" : CHMPX_UNKNOWN == mode ? "n/a" : "unknown") //--------------------------------------------------------- // Structure : Shared memory //--------------------------------------------------------- // CHMSHM // +-----------------------------------------+ // | CHMINFO | // | +---------------------------------+ | // | | .... | | // | | CHMPXMAN | | // | | +-------------------------+ | | // | | | .... | | | // | | | PCHMPX | | |------------+ // | | | PCHMPXLIST | | |------------+ // | | | PCHMPXLIST[ARRAY] | | |------------+ // | | | PCHMPX[ARRAY] | | |--------------+ // | | | PCHMPX[ARRAY] | | |--------------+ // | | | CHMSTAT | | | | | // | | | +-----------------+ | | | | | // | | | | .... | | | | | | // | | | +-----------------+ | | | | | // | | | CHMSTAT | | | | | // | | | +-----------------+ | | | | | // | | | | .... | | | | | | // | | | +-----------------+ | | | | | // | | +-------------------------+ | | | | // | | .... | | | | // | | PMQMSGHEADLIST | |----------+ | | // | | PMQMSGHEADLIST | |----------+ | | // | +---------------------------------+ | | | | // | PCHMPXLIST |--------+ | | | // | MQMSGHEADLIST |------+ | | | | // | CLTPROCLIST |----+ | | | | | // | CHMLOG | | | | | | | // | +---------------------------------+ | | | | | | | // | | .... | | | | | | | | // | | PCHMLOGRAW | |--+ | | | | | | // | | PCHMLOGRAW | |--+ | | | | | | // | | PCHMLOGRAW | |--+ | | | | | | // | +---------------------------------+ | | | | | | | | // +-----------------------------------------+ | | | | | | | // +-----------------------------------------+ | | | | | | | // | CHMPXLIST[XXX] |<-------+---+ | // | | | | | | | // +-----------------------------------------+ | | | | | // +-----------------------------------------+ | | | | | // | PCHMPX[XXX] |<-------------+ // | | | | | | // +-----------------------------------------+ | | | | // +-----------------------------------------+ | | | | // | MQMSGHEADLIST[XXX] |<-----+---+ // | | | | // +-----------------------------------------+ | | // +-----------------------------------------+ | | // | CLTPROCLIST[XXX] |<---+ // | | | // +-----------------------------------------+ | // +-----------------------------------------+ | // | CHMLOGRAW[XXX] |<-+ // | | // +-----------------------------------------+ // +-----------------------------------------+ // | CHMSOCKLIST[XXX] | // | (pointed from CHMPX) | // +-----------------------------------------+ // // CHMSHM has all data for chmpx servers list, stats, mq list, and logs. // We can have the chmpx servers list in class, but stats and status // should be read from another process. And server's data should be had // one place. So that, CHMPX managed datas are in one CHMSHM. // // [NOTICE] // These structure is not set packed attribute, because chmpx // uses each member with locking it. Then each member is aligned // 64bit byte order. // //--------------------------------- // Socket List typedef struct chm_sock_list{ struct chm_sock_list* prev; struct chm_sock_list* next; int sock; }CHMSOCKLIST, *PCHMSOCKLIST; //--------------------------------- // Peer Information(Host + Port) typedef struct chmpx_host_port_raw_pair{ char name[NI_MAXHOST]; // = 1025 for getnameinfo() short port; }CHMPX_ATTR_PACKED CHMPXHP_RAWPAIR, *PCHMPXHP_RAWPAIR; //--------------------------------- // Chmpx typedef struct chmpx{ chmpxid_t chmpxid; char name[NI_MAXHOST]; // = 1025 for getnameinfo() CHMPXMODE mode; chmhash_t base_hash; chmhash_t pending_hash; short port; short ctlport; bool is_ssl; // ssl mode bool verify_peer; // verify ssl client peer on server(always false on client chmpx) bool is_ca_file; // flag for CA path is directory or file char capath[CHM_MAX_PATH_LEN]; // CA directory path char server_cert[CHM_MAX_PATH_LEN]; // signed server cert file path char server_prikey[CHM_MAX_PATH_LEN]; // signed server private key file path char slave_cert[CHM_MAX_PATH_LEN]; // signed slave cert file path char slave_prikey[CHM_MAX_PATH_LEN]; // signed slave private key file path PCHMSOCKLIST socklist; // sock means session connecting to server port. int ctlsock; // ctlsock means session connecting to server ctlport. int selfsock; // If only self chmpx, selfsock means listening port. not self does not use. int selfctlsock; // If only self chmpx, selfctlsock means listening ctlport. not self does not use. time_t last_status_time; chmpxsts_t status; // [NOTE] adding after v1.0.71 char cuk[CUK_MAX]; // cuk char custom_seed[CUSTOM_ID_SEED_MAX]; // custom id seed CHMPXHP_RAWPAIR endpoints[EXTERNAL_EP_MAX]; // external endpoint host/port information CHMPXHP_RAWPAIR ctlendpoints[EXTERNAL_EP_MAX]; // external endpoint host/control port information CHMPXHP_RAWPAIR forward_peers[FORWARD_PEER_MAX]; // forward gateway(NAT) peer hostname(ip address) CHMPXHP_RAWPAIR reverse_peers[REVERSE_PEER_MAX]; // reverse gateway(NAT) peer hostname(ip address) }CHMPX, *PCHMPX; // Chmpx list typedef struct chmpx_list{ struct chmpx_list* prev; // For RING list struct chmpx_list* next; // For RING list struct chmpx_list* same; // For conflicting Hash list CHMPX chmpx; }CHMPXLIST, *PCHMPXLIST; // Stats for chmpx process typedef struct chm_stat{ long total_sent_count; long total_received_count; size_t total_body_bytes; size_t min_body_bytes; size_t max_body_bytes; struct timespec total_elapsed_time; struct timespec min_elapsed_time; struct timespec max_elapsed_time; }CHMSTAT, *PCHMSTAT; // All Chmpx manage structure // // chmpxid_map mapping for chmpxid to chmpxlist pointer(offset) // care for some same chmpxid in this mapping array and // server/slave chmpxid in this. // chmpx_base_srvs This is sequence, and holds a pointer to chmpx* in // order of base hash value. // chmpx_pend_srvs This is sequence, and holds a pointer to chmpx* in // order of pending hash value. // chmpx_self for own bind port/ctlport // chmpx_servers server mode(service in/out) on RING, information for // connection to servers(self -> other server) // chmpx_slaves slaves information which is connection from other // chmpx to own(other server/slave -> self) // typedef struct chmpx_manage{ char group[MAX_GROUP_LENGTH]; long cfg_revision; time_t cfg_date; long replica_count; // replication count long chmpx_count; // = max CHMPX count(server + slave) PCHMPXLIST chmpxid_map[CHMPXID_MAP_SIZE]; // 32KB = 4K * pointer(8byte) PCHMPX* chmpx_base_srvs; // offset pointer to CHMPX array for base hash servers PCHMPX* chmpx_pend_srvs; // offset pointer to CHMPX array for pending hash servers PCHMPXLIST chmpx_self; // own chmpx, if server mode, this is included pointer in servers list. long chmpx_bhash_count; // base hash chmpx count long chmpx_server_count; PCHMPXLIST chmpx_servers; // servers chmpx list( with self chmpx list if server mode ) long chmpx_slave_count; PCHMPXLIST chmpx_slaves; // slaves chmpx list( with self chmpx list if slave mode ) long chmpx_free_count; PCHMPXLIST chmpx_frees; long sock_free_count; PCHMSOCKLIST sock_frees; // free socket list bool is_operating; // operating chmpxid_t last_chmpxid; // last random chmpxid CHMSTAT server_stat; CHMSTAT slave_stat; }CHMPXMAN, *PCHMPXMAN; //--------------------------------- // Head for Message queue typedef struct mq_msg_head{ msgid_t msgid; msgflag_t flag; pid_t pid; }MQMSGHEAD, *PMQMSGHEAD; // Message queue head list typedef struct mq_msg_head_list{ struct mq_msg_head_list* prev; struct mq_msg_head_list* next; MQMSGHEAD msghead; }MQMSGHEADLIST, *PMQMSGHEADLIST; //--------------------------------- // Client processes list typedef struct client_proc_list{ struct client_proc_list* prev; struct client_proc_list* next; pid_t pid; }CLTPROCLIST, *PCLTPROCLIST; //--------------------------------- // chmpx information // // [NOTE] // ssl_min_ver and nssdb_dir members should be a member of CHMPX structure, but these are // extended option for SSL/TLS, and there are too many changes to set these in the CHMPX // structure. // In particular, since the CHMPX structure is used for CHMPX interprocess communication // packets, there are many changes. In addition, ssl_min_ver and nssdb_dir are values that // can be restricted throughout the CHMPX process, then these are member of CHMINFO structure // as a setting value of the entire CHMPX process. // typedef struct chminfo{ char chminfo_version[CHM_CHMINFO_VERSION_BUFLEN];// version number for CHMINFO(old version does not have this member) size_t chminfo_size; // CHMINFO structure size(old version does not have this member) pid_t pid; time_t start_time; CHMPXMAN chmpx_man; CHMPXID_SEED_TYPE chmpxid_type; // Seed type for creating chmpxid chmss_ver_t ssl_min_ver; // SSL/TLS minimum version(old version does not have this member, and see NOTE) char nssdb_dir[CHM_MAX_PATH_LEN]; // NSSDB directory path like "SSL_DIR" environment for NSS int evsock_thread_cnt; // socket thread count int evmq_thread_cnt; // MQ thread count bool is_random_deliver; bool is_auto_merge; bool is_auto_merge_suspend; // suspend auto merging flag for that is_auto_merge is true bool is_do_merge; long max_mqueue; // = max MQ count long chmpx_mqueue; // = Chmpx MQ count long max_q_per_chmpxmq; // = max queue per chmpx MQ long max_q_per_cltmq; // = max queue per client MQ long max_mq_per_client; // = MQ per client long mq_per_attach; // = MQ per attach bool mq_ack; // MQ ACK int max_sock_pool; // max socket count per chmpx time_t sock_pool_timeout; // timeout value till closing for not used socket in pool int sock_retrycnt; // retry count for socket suseconds_t timeout_wait_socket; // wait timeout for read/write socket suseconds_t timeout_wait_connect; // wait timeout for connect socket int mq_retrycnt; // retry count for MQ long timeout_wait_mq; // wait timeout for MQ time_t timeout_merge; // wait timeout for merging msgid_t base_msgid; long chmpx_msg_count; // MQ count for chmpx process PMQMSGHEADLIST chmpx_msgs; // MQ list for chmpx process long activated_msg_count; // Activated MQ count for client process PMQMSGHEADLIST activated_msgs; // Activated MQ list for client process long assigned_msg_count; // Assigned(NOT activated) MQ count for client process PMQMSGHEADLIST assigned_msgs; // Assigned(NOT activated) MQ list for client process long free_msg_count; PMQMSGHEADLIST free_msgs; msgid_t last_msgid_chmpx; // last random msgid for chmpx process msgid_t last_msgid_activated; // last random activated msgid for client process msgid_t last_msgid_assigned; // last random assigned msgid for client process PMQMSGHEADLIST rel_chmpxmsgarea; // same as in CHMSHM PCLTPROCLIST client_pids; // Client process(pid) list PCLTPROCLIST free_pids; bool k2h_fullmap; int k2h_mask_bitcnt; int k2h_cmask_bitcnt; int k2h_max_element; long histlog_count; // history log count }CHMINFO, *PCHMINFO; //--------------------------------- // Login History Raw typedef struct chm_log_raw{ logtype_t log_type; size_t length; struct timespec start_time; // time for starting sending/receiving struct timespec fin_time; // time for end of sending/receiving }CHMLOGRAW, *PCHMLOGRAW; // Login History Area typedef struct chm_log{ bool enable; time_t start_time; // time for enabled log time_t stop_time; // time for disabled log long max_log_count; long next_pos; PCHMLOGRAW start_log_rel_area; }CHMLOG, *PCHMLOG; //--------------------------------- // Shared memory for chmpx typedef struct chmshm{ CHMINFO info; PCHMPXLIST rel_chmpxarea; PCHMPX* rel_pchmpxarrarea; PMQMSGHEADLIST rel_chmpxmsgarea; PCLTPROCLIST rel_chmpxpidarea; PCHMSOCKLIST rel_chmsockarea; CHMLOG chmpxlog; }CHMSHM, *PCHMSHM; //--------------------------------------------------------- // Structure for communication //--------------------------------------------------------- // Chmpx ssl information(notice: all member is byte order) typedef struct chmpx_ssl{ bool is_ssl; bool verify_peer; bool is_ca_file; char capath[CHM_MAX_PATH_LEN]; char server_cert[CHM_MAX_PATH_LEN]; char server_prikey[CHM_MAX_PATH_LEN]; char slave_cert[CHM_MAX_PATH_LEN]; char slave_prikey[CHM_MAX_PATH_LEN]; }CHMPX_ATTR_PACKED CHMPXSSL, *PCHMPXSSL; // Chmpx server information typedef struct chmpx_server{ chmpxid_t chmpxid; char name[NI_MAXHOST]; // = 1025 for getnameinfo() chmhash_t base_hash; chmhash_t pending_hash; short port; short ctlport; CHMPXSSL ssl; time_t last_status_time; chmpxsts_t status; char cuk[CUK_MAX]; // adding after v1.0.71 char custom_seed[CUSTOM_ID_SEED_MAX]; // adding after v1.0.71 CHMPXHP_RAWPAIR endpoints[EXTERNAL_EP_MAX]; // adding after v1.0.71 CHMPXHP_RAWPAIR ctlendpoints[EXTERNAL_EP_MAX]; // adding after v1.0.71 CHMPXHP_RAWPAIR forward_peers[FORWARD_PEER_MAX]; // adding after v1.0.71 CHMPXHP_RAWPAIR reverse_peers[REVERSE_PEER_MAX]; // adding after v1.0.71 }CHMPX_ATTR_PACKED CHMPXSVR, *PCHMPXSVR; // Old chmpx server information for backward compatibility typedef struct chmpx_server_v1{ chmpxid_t chmpxid; char name[NI_MAXHOST]; // = 1025 for getnameinfo() chmhash_t base_hash; chmhash_t pending_hash; short port; short ctlport; CHMPXSSL ssl; time_t last_status_time; chmpxsts_t status; }CHMPX_ATTR_PACKED CHMPXSVRV1, *PCHMPXSVRV1; #define COPY_PCHMPXSVR(pdest, psrc) \ { \ (pdest)->chmpxid = (psrc)->chmpxid; \ (pdest)->base_hash = (psrc)->base_hash; \ (pdest)->pending_hash = (psrc)->pending_hash; \ (pdest)->port = (psrc)->port; \ (pdest)->ctlport = (psrc)->ctlport; \ (pdest)->ssl.is_ssl = (psrc)->ssl.is_ssl; \ (pdest)->ssl.verify_peer = (psrc)->ssl.verify_peer; \ (pdest)->ssl.is_ca_file = (psrc)->ssl.is_ca_file; \ (pdest)->last_status_time = (psrc)->last_status_time; \ (pdest)->status = (psrc)->status; \ memcpy((pdest)->name, (psrc)->name, NI_MAXHOST); \ memcpy((pdest)->ssl.capath, (psrc)->ssl.capath, CHM_MAX_PATH_LEN); \ memcpy((pdest)->ssl.server_cert, (psrc)->ssl.server_cert, CHM_MAX_PATH_LEN); \ memcpy((pdest)->ssl.server_prikey, (psrc)->ssl.server_prikey, CHM_MAX_PATH_LEN); \ memcpy((pdest)->ssl.slave_cert, (psrc)->ssl.slave_cert, CHM_MAX_PATH_LEN); \ memcpy((pdest)->ssl.slave_prikey, (psrc)->ssl.slave_prikey, CHM_MAX_PATH_LEN); \ memcpy((pdest)->cuk, (psrc)->cuk, CUK_MAX); \ memcpy((pdest)->custom_seed, (psrc)->custom_seed, CUSTOM_ID_SEED_MAX); \ { \ int _copy_chmpxsvr_cnt; \ for(_copy_chmpxsvr_cnt = 0; _copy_chmpxsvr_cnt < EXTERNAL_EP_MAX; ++_copy_chmpxsvr_cnt){ \ memcpy((pdest)->endpoints[_copy_chmpxsvr_cnt].name, (psrc)->endpoints[_copy_chmpxsvr_cnt].name, NI_MAXHOST); \ (pdest)->endpoints[_copy_chmpxsvr_cnt].port = (psrc)->endpoints[_copy_chmpxsvr_cnt].port; \ } \ for(_copy_chmpxsvr_cnt = 0; _copy_chmpxsvr_cnt < EXTERNAL_EP_MAX; ++_copy_chmpxsvr_cnt){ \ memcpy((pdest)->ctlendpoints[_copy_chmpxsvr_cnt].name, (psrc)->ctlendpoints[_copy_chmpxsvr_cnt].name, NI_MAXHOST); \ (pdest)->ctlendpoints[_copy_chmpxsvr_cnt].port = (psrc)->ctlendpoints[_copy_chmpxsvr_cnt].port; \ } \ for(_copy_chmpxsvr_cnt = 0; _copy_chmpxsvr_cnt < FORWARD_PEER_MAX; ++_copy_chmpxsvr_cnt){ \ memcpy((pdest)->forward_peers[_copy_chmpxsvr_cnt].name, (psrc)->forward_peers[_copy_chmpxsvr_cnt].name, NI_MAXHOST); \ (pdest)->forward_peers[_copy_chmpxsvr_cnt].port = (psrc)->forward_peers[_copy_chmpxsvr_cnt].port; \ } \ for(_copy_chmpxsvr_cnt = 0; _copy_chmpxsvr_cnt < REVERSE_PEER_MAX; ++_copy_chmpxsvr_cnt){ \ memcpy((pdest)->reverse_peers[_copy_chmpxsvr_cnt].name, (psrc)->reverse_peers[_copy_chmpxsvr_cnt].name, NI_MAXHOST); \ (pdest)->reverse_peers[_copy_chmpxsvr_cnt].port = (psrc)->reverse_peers[_copy_chmpxsvr_cnt].port; \ } \ } \ } #define COPY_PCHMPXSVRV1(pdest, psrc) \ { \ (pdest)->chmpxid = (psrc)->chmpxid; \ (pdest)->base_hash = (psrc)->base_hash; \ (pdest)->pending_hash = (psrc)->pending_hash; \ (pdest)->port = (psrc)->port; \ (pdest)->ctlport = (psrc)->ctlport; \ (pdest)->ssl.is_ssl = (psrc)->ssl.is_ssl; \ (pdest)->ssl.verify_peer = (psrc)->ssl.verify_peer; \ (pdest)->ssl.is_ca_file = (psrc)->ssl.is_ca_file; \ (pdest)->last_status_time = (psrc)->last_status_time; \ (pdest)->status = (psrc)->status; \ memcpy((pdest)->name, (psrc)->name, NI_MAXHOST); \ memcpy((pdest)->ssl.capath, (psrc)->ssl.capath, CHM_MAX_PATH_LEN); \ memcpy((pdest)->ssl.server_cert, (psrc)->ssl.server_cert, CHM_MAX_PATH_LEN); \ memcpy((pdest)->ssl.server_prikey, (psrc)->ssl.server_prikey, CHM_MAX_PATH_LEN); \ memcpy((pdest)->ssl.slave_cert, (psrc)->ssl.slave_cert, CHM_MAX_PATH_LEN); \ memcpy((pdest)->ssl.slave_prikey, (psrc)->ssl.slave_prikey, CHM_MAX_PATH_LEN); \ } #define HTON_PCHMPXSVR(pdata) \ { \ (pdata)->chmpxid = htobe64((pdata)->chmpxid); \ (pdata)->base_hash = htobe64((pdata)->base_hash); \ (pdata)->pending_hash = htobe64((pdata)->pending_hash); \ (pdata)->port = htobe16((pdata)->port); \ (pdata)->ctlport = htobe16((pdata)->ctlport); \ (pdata)->last_status_time = htobe64((pdata)->last_status_time); \ (pdata)->status = htobe64((pdata)->status); \ { \ int _hton_hostport_pair_cnt; \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->endpoints[_hton_hostport_pair_cnt].port = htobe16((pdata)->endpoints[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->ctlendpoints[_hton_hostport_pair_cnt].port = htobe16((pdata)->ctlendpoints[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < FORWARD_PEER_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->forward_peers[_hton_hostport_pair_cnt].port = htobe16((pdata)->forward_peers[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < REVERSE_PEER_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->reverse_peers[_hton_hostport_pair_cnt].port = htobe16((pdata)->reverse_peers[_hton_hostport_pair_cnt].port); \ } \ } \ } #define HTON_PCHMPXSVRV1(pdata) \ { \ (pdata)->chmpxid = htobe64((pdata)->chmpxid); \ (pdata)->base_hash = htobe64((pdata)->base_hash); \ (pdata)->pending_hash = htobe64((pdata)->pending_hash); \ (pdata)->port = htobe16((pdata)->port); \ (pdata)->ctlport = htobe16((pdata)->ctlport); \ (pdata)->last_status_time = htobe64((pdata)->last_status_time); \ (pdata)->status = htobe64((pdata)->status); \ } #define NTOH_PCHMPXSVR(pdata) \ { \ (pdata)->chmpxid = be64toh((pdata)->chmpxid); \ (pdata)->base_hash = be64toh((pdata)->base_hash); \ (pdata)->pending_hash = be64toh((pdata)->pending_hash); \ (pdata)->port = be16toh((pdata)->port); \ (pdata)->ctlport = be16toh((pdata)->ctlport); \ (pdata)->last_status_time = be64toh((pdata)->last_status_time); \ (pdata)->status = be64toh((pdata)->status); \ { \ int _hton_hostport_pair_cnt; \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->endpoints[_hton_hostport_pair_cnt].port = be16toh((pdata)->endpoints[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->ctlendpoints[_hton_hostport_pair_cnt].port = be16toh((pdata)->ctlendpoints[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < FORWARD_PEER_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->forward_peers[_hton_hostport_pair_cnt].port = be16toh((pdata)->forward_peers[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < REVERSE_PEER_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->reverse_peers[_hton_hostport_pair_cnt].port = be16toh((pdata)->reverse_peers[_hton_hostport_pair_cnt].port); \ } \ } \ } #define NTOH_PCHMPXSVRV1(pdata) \ { \ (pdata)->chmpxid = be64toh((pdata)->chmpxid); \ (pdata)->base_hash = be64toh((pdata)->base_hash); \ (pdata)->pending_hash = be64toh((pdata)->pending_hash); \ (pdata)->port = be16toh((pdata)->port); \ (pdata)->ctlport = be16toh((pdata)->ctlport); \ (pdata)->last_status_time = be64toh((pdata)->last_status_time); \ (pdata)->status = be64toh((pdata)->status); \ } #define CVT_PCHMPXSVRV1_TO_PCHMPXSVR(pv2, pv1) \ { \ (pv2)->chmpxid = (pv1)->chmpxid; \ (pv2)->base_hash = (pv1)->base_hash; \ (pv2)->pending_hash = (pv1)->pending_hash; \ (pv2)->port = (pv1)->port; \ (pv2)->ctlport = (pv1)->ctlport; \ (pv2)->ssl.is_ssl = (pv1)->ssl.is_ssl; \ (pv2)->ssl.verify_peer = (pv1)->ssl.verify_peer; \ (pv2)->ssl.is_ca_file = (pv1)->ssl.is_ca_file; \ (pv2)->last_status_time = (pv1)->last_status_time; \ (pv2)->status = (pv1)->status; \ memcpy((pv2)->name, (pv1)->name, NI_MAXHOST); \ memcpy((pv2)->ssl.capath, (pv1)->ssl.capath, CHM_MAX_PATH_LEN); \ memcpy((pv2)->ssl.server_cert, (pv1)->ssl.server_cert, CHM_MAX_PATH_LEN); \ memcpy((pv2)->ssl.server_prikey,(pv1)->ssl.server_prikey, CHM_MAX_PATH_LEN); \ memcpy((pv2)->ssl.slave_cert, (pv1)->ssl.slave_cert, CHM_MAX_PATH_LEN); \ memcpy((pv2)->ssl.slave_prikey, (pv1)->ssl.slave_prikey, CHM_MAX_PATH_LEN); \ memset((pv2)->cuk, 0, CUK_MAX); \ memset((pv2)->custom_seed, 0, CUSTOM_ID_SEED_MAX); \ { \ int _copy_hostport_pair_cnt; \ for(_copy_hostport_pair_cnt = 0; _copy_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_copy_hostport_pair_cnt){ \ memset((pv2)->endpoints[_copy_hostport_pair_cnt].name, 0, NI_MAXHOST); \ (pv2)->endpoints[_copy_hostport_pair_cnt].port = CHM_INVALID_PORT; \ } \ for(_copy_hostport_pair_cnt = 0; _copy_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_copy_hostport_pair_cnt){ \ memset((pv2)->ctlendpoints[_copy_hostport_pair_cnt].name, 0, NI_MAXHOST); \ (pv2)->ctlendpoints[_copy_hostport_pair_cnt].port = CHM_INVALID_PORT; \ } \ for(_copy_hostport_pair_cnt = 0; _copy_hostport_pair_cnt < FORWARD_PEER_MAX; ++_copy_hostport_pair_cnt){ \ memset((pv2)->forward_peers[_copy_hostport_pair_cnt].name, 0, NI_MAXHOST); \ (pv2)->forward_peers[_copy_hostport_pair_cnt].port = CHM_INVALID_PORT; \ } \ for(_copy_hostport_pair_cnt = 0; _copy_hostport_pair_cnt < REVERSE_PEER_MAX; ++_copy_hostport_pair_cnt){ \ memset((pv2)->reverse_peers[_copy_hostport_pair_cnt].name, 0, NI_MAXHOST); \ (pv2)->reverse_peers[_copy_hostport_pair_cnt].port = CHM_INVALID_PORT; \ } \ } \ } #define CVT_PCHMPXSVR_TO_PCHMPXSVRV1(pv1, pv2) \ { \ (pv1)->chmpxid = (pv2)->chmpxid; \ (pv1)->base_hash = (pv2)->base_hash; \ (pv1)->pending_hash = (pv2)->pending_hash; \ (pv1)->port = (pv2)->port; \ (pv1)->ctlport = (pv2)->ctlport; \ (pv1)->ssl.is_ssl = (pv2)->ssl.is_ssl; \ (pv1)->ssl.verify_peer = (pv2)->ssl.verify_peer; \ (pv1)->ssl.is_ca_file = (pv2)->ssl.is_ca_file; \ (pv1)->last_status_time = (pv2)->last_status_time; \ (pv1)->status = (pv2)->status; \ memcpy((pv1)->name, (pv2)->name, NI_MAXHOST); \ memcpy((pv1)->ssl.capath, (pv2)->ssl.capath, CHM_MAX_PATH_LEN); \ memcpy((pv1)->ssl.server_cert, (pv2)->ssl.server_cert, CHM_MAX_PATH_LEN); \ memcpy((pv1)->ssl.server_prikey,(pv2)->ssl.server_prikey, CHM_MAX_PATH_LEN); \ memcpy((pv1)->ssl.slave_cert, (pv2)->ssl.slave_cert, CHM_MAX_PATH_LEN); \ memcpy((pv1)->ssl.slave_prikey, (pv2)->ssl.slave_prikey, CHM_MAX_PATH_LEN); \ } DECL_EXTERN_C_END #endif // CHMSTRUCTURE_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmnetdb.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMNETDB_H #define CHMNETDB_H #include <regex.h> #include <fullock/flckstructure.h> #include <fullock/flckbaselist.tcc> #include "chmcommon.h" #include "chmutil.h" //--------------------------------------------------------- // Structure //--------------------------------------------------------- typedef struct chm_netdb_cache{ strlst_t ipaddresses; strlst_t hostnames; time_t cached_time; // set 0 if not cashed out. chm_netdb_cache() : cached_time(0) {} }CHMNDBCACHE, *PCHMNDBCACHE; typedef std::map<std::string, CHMNDBCACHE> chmndbmap_t; // Key is ipaddress or hostname typedef std::list<struct addrinfo*> addrinfolist_t; //--------------------------------------------------------- // Class ChmNetDb //--------------------------------------------------------- class ChmNetDb { protected: static const time_t ALIVE_TIME = 60; // default 60s static int lockval; // like mutex static const size_t PORT_NMATCH = 5; // maximum 3 matches + 2(reserve) chmndbmap_t cachemap; time_t timeout; // 0 means no timeout std::string fulllocalname; // local hostname from uname(gethostname), this is Full FQDN. strlst_t localaddrs; // local ip addresses strlst_t localnames; // local hostname from getnameinfo, sometimes this name is without domain name if set in /etc/hosts. regex_t regobj_checkport; // for checking regular expression for port specification bool is_init_regobj; // protected: static bool CheckHostnameInResolv(const char* hostname, bool is_default_domain = false); ChmNetDb(); virtual ~ChmNetDb(); bool InitializeLocalHostInfo(void); bool InitializeLocalHostIpAddresses(void); bool InitializeLocalHostnames(void); bool ClearEx(void); bool CacheOutEx(void); bool RawAddCache(const std::string& target, const strlst_t& addlist, bool is_noexp, bool is_hostname, bool is_reentrant = false); bool HostnammeAddCache(const std::string& hostname, const std::string& ipaddr, bool is_noexp = false); bool HostnammeAddCache(const std::string& hostname, const strlst_t& ipaddrs, bool is_noexp = false); bool IpAddressAddCache(const std::string& ipaddr, const std::string& hostname, bool is_noexp = false); bool IpAddressAddCache(const std::string& ipaddr, const strlst_t& hostnames, bool is_noexp = false); bool SearchCache(const char* target, CHMNDBCACHE& data); bool Search(const char* target, CHMNDBCACHE& data, bool is_cvt_localhost); bool GetHostAddressInfo(const char* target, CHMNDBCACHE& data); void AddFullLocalHostname(strlst_t& hostnames); public: static ChmNetDb* Get(void); static time_t SetTimeout(time_t value); static bool Clear(void); static bool CacheOut(void); static bool GetLocalHostname(std::string& hostname); static bool GetLocalHostnameList(strlst_t& hostnames); static bool GetLocalHostList(strlst_t& hostinfo, bool remove_localhost = false); static bool GetAnyAddrInfo(short port, struct addrinfo** ppaddrinfo, bool is_inetv6); static bool CvtAddrInfoToIpAddress(struct sockaddr_storage* info, socklen_t infolen, std::string& stripaddress); static bool CvtSockToLocalPort(int sock, short& port); static bool CvtSockToPeerPort(int sock, short& port); static bool CvtV4MappedAddrInfo(struct sockaddr_storage* info, socklen_t& addrlen); static bool GetIPv4MappedIPv6Address(const char* target, std::string& stripv4); static std::string CvtIPv4MappedIPv6Address(const std::string& target); static void FreeAddrInfoList(addrinfolist_t& infolist); static std::string GetNoZoneIndexIpAddress(const std::string& ipaddr); static bool IsLocalhostKeyword(const char* host); static bool ParseHostPortString(const std::string& target, short default_port, std::string& strHost, short& port); bool GetAddrInfo(const char* target, short port, struct addrinfo** ppaddrinfo, bool is_cvt_localhost); // Must freeaddrinfo for *ppaddrinfo bool GetAddrInfoList(const char* target, short port, addrinfolist_t& infolist, bool is_cvt_localhost); // Must FreeAddrInfoList for clear bool GetHostname(const char* target, std::string& hostname, bool is_cvt_localhost); bool GetHostnameList(const char* target, strlst_t& hostnames, bool is_cvt_localhost); bool GetIpAddressString(const char* target, std::string& ipaddress, bool is_cvt_localhost); bool GetIpAddressStringList(const char* target, strlst_t& ipaddrs, bool is_cvt_localhost); bool GetAllHostList(const char* target, strlst_t& expandlist, bool is_cvt_localhost); }; #endif // CHMNETDB_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmssopenssl.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Mon May 13 2018 * REVISION: * */ #ifndef CHMSSOPENSSL_H #define CHMSSOPENSSL_H #include <openssl/ssl.h> #include <openssl/err.h> #include "chmeventsock.h" //--------------------------------------------------------- // Common type for ChmEventSock //--------------------------------------------------------- typedef SSL_CTX* ChmSSCtx; //--------------------------------------------------------- // ChmSecureSock Class for OpenSSL //--------------------------------------------------------- class ChmSecureSock { protected: static int CHM_SSL_VERIFY_DEPTH; // SSL cert verify depth static const char* strVerifyCBDataIndex; // string keyword for data index static int verify_cb_data_index; // Data index for verify callback function static int ssl_session_id; // Session ID static bool is_self_sigined; // For DEBUG static int init_count; // flag for initialization static bool is_verify_peer; // Verify Peer mode on server static chmss_ver_t ssl_min_ver; // SSL/TLS minimum version protected: ChmSSCtx svr_sslctx; // SSL Context for server ChmSSCtx slv_sslctx; // SSL Context for slave protected: static bool InitLibrary(const char* CApath, const char* CAfile, bool is_verify_peer); static bool FreeLibrary(void); static std::string& GetCAPath(void); // CA directory path if exists static std::string& GetCAFile(void); // CA file path if exists static bool SetCA(const char* CApath, const char* CAfile); static bool SetMinVersion(SSL_CTX* ctx); static std::string GetSessionInfo(SSL* ssl); static ChmSSCtx MakeSSLContext(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); static int VerifyCallBackSSL(int preverify_ok, X509_STORE_CTX* store_ctx); static ChmSSSession HandshakeSSL(ChmSSCtx ctx, int sock, bool is_accept, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); public: static void AllowSelfSignedCert(void); // For only debugging static void DenySelfSignedCert(void); static const char* LibraryName(void); static bool IsCAPathAllowFile(void); static bool IsCertAllowName(void); static bool SetSslMinVersion(chmss_ver_t ssver); static bool SetExtValue(const char* key, const char* value); static bool CheckResultSSL(int sock, ChmSSSession sslsession, long action_result, int type, bool& is_retry, bool& is_close, int retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static ChmSSSession AcceptSSL(ChmSSCtx ctx, int sock, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static ChmSSSession ConnectSSL(ChmSSCtx ctx, int sock, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool ShutdownSSL(int sock, ChmSSSession sslsession, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static int Read(ChmSSSession sslsession, void* pbuf, int length); static int Write(ChmSSSession sslsession, const void* pbuf, int length); ChmSecureSock(const char* CApath = NULL, const char* CAfile = NULL, bool is_verify_peer = false); virtual ~ChmSecureSock(); bool Clean(void); bool IsSafeSSLContext(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); ChmSSCtx GetSSLContext(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); void FreeSSLContext(ChmSSCtx ctx); }; #endif // CHMSSOPENSSL_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmpx.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMPX_H #define CHMPX_H #include <k2hash/k2hash.h> #include "chmcommon.h" #include "chmstructure.h" DECL_EXTERN_C_START //--------------------------------------------------------- // Typedefs //--------------------------------------------------------- typedef uint64_t chmpx_h; // ChmCntrl object handle typedef uint64_t chmpx_pkt_h; // COMPKT handle //--------------------------------------------------------- // Symbols //--------------------------------------------------------- #define RCV_NO_WAIT 0 // no wait for receiving(=EVENT_NOWAIT) //--------------------------------------------------------- // Structure & Utilities //--------------------------------------------------------- // Utility structure for binary message which has key and value. // // Some function gets CHMKVP pointer for sending message. // These structure and functions help you make binary message pack // and make hash code. // // This structure types are based and defined in k2hash. // typedef K2HBIN CHMBIN; typedef PK2HBIN PCHMBIN; #define CHM_FREE_CHMBIN free_k2hbin #define CHM_FREE_CHMBINS free_k2hbins typedef struct chmpx_kv_pair{ CHMBIN key; CHMBIN val; }CHMKVP, *PCHMKVP; typedef struct chm_merge_getparam{ chmhash_t starthash; struct timespec startts; // start time for update datas struct timespec endts; // end time for update datas chmhash_t target_hash; // target hash value(0 ... target_max_hash) chmhash_t target_max_hash; // max target hash value chmhash_t old_hash; // old hash value(0 ... old_max_hash) chmhash_t old_max_hash; // max old target hash value long target_hash_range; // range for hash value(use both target_hash and old_hash) bool is_expire_check; // whether checking expire time }CHM_MERGE_GETPARAM, *PCHM_MERGE_GETPARAM; //--------------------------------------------------------- // Prototype functions //--------------------------------------------------------- // Callback prototype function for merging // // chm_merge_lastts_cb // This callback function is called for getting lastest update time in // client dadabase before merging. // The return value(time) from this function will be used start time of // target data for merging. // If you did not specify this callback at chmpx_create_ex, the start // time should be zero for merging. It means the target data is all of // database. // // chm_merge_get_cb // This callback function is called for getting target data for merging. // The parameter CHM_MERGE_GETPARAM means start of hash value, range // from start hash value and time range(start to end). // This callback function should return the datas which has minimum hash // value in range of hash value. // If there are some target hash datas, you have to return all of them. // The return value for pnexthash should be set next start hash value. // When there is no more data, this function have to return the zero in // pdatacnt. // If you did not specify this callback at chmpx_create_ex, no data is // merged. // // chm_merge_set_cb // This callback function is called for setting one data for merging. // The parameters are datas which must be merged into database. // If you did not specify this callback at chmpx_create_ex, no data is // merged. // typedef bool (*chm_merge_lastts_cb)(chmpx_h handle, struct timespec* pts); typedef bool (*chm_merge_get_cb)(chmpx_h handle, const PCHM_MERGE_GETPARAM pparam, chmhash_t* pnexthash, PCHMBIN* ppdatas, size_t* pdatacnt); typedef bool (*chm_merge_set_cb)(chmpx_h handle, size_t length, const unsigned char* pdata, const struct timespec* pts); //--------------------------------------------------------- // Functions //--------------------------------------------------------- // [debug] // // chmpx_bump_debug_level bumpup debugging level(silent -> error -> warning -> messages ->...) // chmpx_set_debug_level_silent set silent for debugging level // chmpx_set_debug_level_error set error for debugging level // chmpx_set_debug_level_warning set warning for debugging level // chmpx_set_debug_level_message set message for debugging level // chmpx_set_debug_level_dump set dump for debugging level // chmpx_set_debug_file set file path for debugging message // chmpx_unset_debug_file unset file path for debugging message to stderr(default) // chmpx_load_debug_env set debugging level and file path by loading environment. // extern void chmpx_bump_debug_level(void); extern void chmpx_set_debug_level_silent(void); extern void chmpx_set_debug_level_error(void); extern void chmpx_set_debug_level_warning(void); extern void chmpx_set_debug_level_message(void); extern void chmpx_set_debug_level_dump(void); extern bool chmpx_set_debug_file(const char* filepath); extern bool chmpx_unset_debug_file(void); extern bool chmpx_load_debug_env(void); // [load hash library] // // chmpx_load_hash_library load extra hash library(lap k2hash function) // chmpx_unload_hash_library unload extra hash library(lap k2hash function) // extern bool chmpx_load_hash_library(const char* libpath); extern bool chmpx_unload_hash_library(void); // [create/destroy] // // chmpx_create_ex create(join) chmpx process as client with callback function(only join to server) // chmpx_create create(join) chmpx process as client // chmpx_destroy destroy(leave) chmpx process // chmpx_pkth_destroy destroy compkt handle // extern chmpx_h chmpx_create_ex(const char* conffile, bool is_on_server, bool is_auto_rejoin, chm_merge_get_cb getfp, chm_merge_set_cb setfp, chm_merge_lastts_cb lastupdatefp); extern chmpx_h chmpx_create(const char* conffile, bool is_on_server, bool is_auto_rejoin); extern bool chmpx_destroy(chmpx_h handle); extern bool chmpx_pkth_destroy(chmpx_pkt_h pckthandle); // [send/receive for server side] // // chmpx_svr_send send message // chmpx_svr_send_kvp send message by CHMKVP structure // chmpx_svr_send_kvp_ex send message with(out) self chmpx mode by CHMKVP structure // chmpx_svr_send_kv send message by key and value // chmpx_svr_send_kv_ex send message with(out) self chmpx mode by key and value // chmpx_svr_broadcast send(broadcast) message // chmpx_svr_broadcast_ex send(broadcast) message with(out) self chmpx mode by key and value // chmpx_svr_replicate send(replicate) message without self chmpx mode // chmpx_svr_replicate_ex send(replicate) message with(out) self chmpx mode by key and value // chmpx_svr_receive receive message(ppbody, plength are allowed NULL, timeout_ms can be set RCV_NO_WAIT) // extern bool chmpx_svr_send(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash, bool is_routing); extern bool chmpx_svr_send_kvp(chmpx_h handle, const PCHMKVP pkvp, bool is_routing); extern bool chmpx_svr_send_kvp_ex(chmpx_h handle, const PCHMKVP pkvp, bool is_routing, bool without_self); extern bool chmpx_svr_send_kv(chmpx_h handle, unsigned char* pkey, size_t keylen, unsigned char* pval, size_t vallen, bool is_routing); extern bool chmpx_svr_send_kv_ex(chmpx_h handle, unsigned char* pkey, size_t keylen, unsigned char* pval, size_t vallen, bool is_routing, bool without_self); extern bool chmpx_svr_broadcast(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash); extern bool chmpx_svr_broadcast_ex(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash, bool without_self); extern bool chmpx_svr_replicate(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash); extern bool chmpx_svr_replicate_ex(chmpx_h handle, const unsigned char* pbody, size_t blength, chmhash_t hash, bool without_self); extern bool chmpx_svr_receive(chmpx_h handle, chmpx_pkt_h* ppckthandle, unsigned char** ppbody, size_t* plength, int timeout_ms, bool no_giveup_rejoin); // [send/receive for slave side] // // chmpx_open open message handle // chmpx_close close message handle // chmpx_msg_send send message // chmpx_msg_send_kvp send message by CHMKVP // chmpx_msg_send_kv send message by key and value // chmpx_msg_broadcast send(broadcast) message // chmpx_msg_replicate send(replicate) message // chmpx_msg_receive receive message(timeout_ms can be set RCV_NO_WAIT) // extern msgid_t chmpx_open(chmpx_h handle, bool no_giveup_rejoin); extern bool chmpx_close(chmpx_h handle, msgid_t msgid); extern bool chmpx_msg_send(chmpx_h handle, msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt, bool is_routing); extern bool chmpx_msg_send_kvp(chmpx_h handle, msgid_t msgid, const PCHMKVP pkvp, long* preceivercnt, bool is_routing); extern bool chmpx_msg_send_kv(chmpx_h handle, msgid_t msgid, unsigned char* pkey, size_t keylen, unsigned char* pval, size_t vallen, long* preceivercnt, bool is_routing); extern bool chmpx_msg_broadcast(chmpx_h handle, msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt); extern bool chmpx_msg_replicate(chmpx_h handle, msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt); extern bool chmpx_msg_receive(chmpx_h handle, msgid_t msgid, chmpx_pkt_h* ppckthandle, unsigned char** ppbody, size_t* plength, int timeout_ms); // [reply for both server and slave side] // // chmpx_msg_reply reply message // chmpx_msg_reply_kvp reply message by CHMKVP // chmpx_msg_reply_kv reply message by key and value // extern bool chmpx_msg_reply(chmpx_h handle, chmpx_pkt_h pckthandle, const unsigned char* pbody, size_t blength); extern bool chmpx_msg_reply_kvp(chmpx_h handle, chmpx_pkt_h pckthandle, const PCHMKVP pkvp); extern bool chmpx_msg_reply_kv(chmpx_h handle, chmpx_pkt_h pckthandle, unsigned char* pkey, size_t keylen, unsigned char* pval, size_t vallen); // [check chmpx process] // // is_chmpx_proc_exists check chmpx process exists // extern bool is_chmpx_proc_exists(chmpx_h handle); //--------------------------------------------------------- // Version //--------------------------------------------------------- extern void chmpx_print_version(FILE* stream); extern const char* chmpx_get_version(void); extern const char* chmpx_get_raw_version(bool is_commit_hash); extern uint64_t chmpx_get_bin_version(void); //--------------------------------------------------------- // Utility Functions(Key Value Pair) //--------------------------------------------------------- extern unsigned char* cvt_kvp_bin(const PCHMKVP pkvp, size_t* plength); extern bool cvt_bin_kvp(PCHMKVP pkvp, unsigned char* bydata, size_t length); extern chmhash_t make_chmbin_hash(const PCHMBIN pchmbin); extern chmhash_t make_kvp_hash(const PCHMKVP pkvp); DECL_EXTERN_C_END #endif // CHMPX_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmopts.h
<filename>lib/chmopts.h /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMOPTS_H #define CHMOPTS_H #include "chmutil.h" //--------------------------------------------------------- // ChmOpts Class //--------------------------------------------------------- class ChmOpts { protected: strlstmap_t optmap; std::string sepchars; public: ChmOpts(int argc = 0, char** argv = NULL, const char* strsepchars = NULL); virtual ~ChmOpts(); bool Initialize(int argc, char** argv); bool Get(const char* popt, std::string& param); bool Get(const char* popt, strlst_t& params); bool Find(const char* popt) const; long Count(void) const { return static_cast<long>(optmap.size()); } }; #endif // CHMOPTS_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmeventshm.h
<gh_stars>10-100 /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMEVENTSHM_H #define CHMEVENTSHM_H #include <string> #include "chmcommon.h" #include "chmutil.h" #include "chmeventbase.h" #include "chmthread.h" //--------------------------------------------------------- // Class ChmEventShm //--------------------------------------------------------- // This class is to catch client process down realtime for // cleaning MQ management data in CHMSHM. // class ChmEventShm : public ChmEventBase { protected: std::string chmshmfile; int inotifyfd; int watchfd; ChmThread checkthread; protected: static bool IsProcessRunning(pid_t pid); bool IsWatching(void) const { return (CHM_INVALID_HANDLE != watchfd); } bool CheckNotifyEvent(void) const; bool ResetEventQueue(void); public: static bool CheckProcessRunning(void* common_param, chmthparam_t wp_param); ChmEventShm(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL, const char* file = NULL); virtual ~ChmEventShm(); virtual bool Clean(void); virtual bool GetEventQueueFds(event_fds_t& fds); virtual bool SetEventQueue(void); virtual bool UnsetEventQueue(void); virtual bool IsEventQueueFd(int fd); virtual bool Send(PCOMPKT pComPkt, const unsigned char* pbody, size_t blength); virtual bool Receive(int fd); virtual bool NotifyHup(int fd); virtual bool Processing(PCOMPKT pComPkt); }; #endif // CHMEVENTSHM_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmeventbase.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMEVENTBASE_H #define CHMEVENTBASE_H #include <vector> #include "chmcomstructure.h" //--------------------------------------------------------- // Prototype //--------------------------------------------------------- class ChmCntrl; //--------------------------------------------------------- // Typedefs //--------------------------------------------------------- typedef std::vector<int> event_fds_t; //--------------------------------------------------------- // ChmEventBase Class //--------------------------------------------------------- class ChmEventBase { protected: int eqfd; // backup ChmCntrl* pChmCntrl; public: ChmEventBase(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL); virtual ~ChmEventBase(); bool IsEmpty(void) const { return (!pChmCntrl || CHM_INVALID_HANDLE == eqfd); } bool SetEventQueueFd(int eventqfd); bool SetChmCntrlObj(ChmCntrl* pcntrl); virtual bool Clean(void); virtual bool UpdateInternalData(void); virtual bool GetEventQueueFds(event_fds_t& fds) = 0; virtual bool SetEventQueue(void) = 0; virtual bool UnsetEventQueue(void) = 0; virtual bool IsEventQueueFd(int fd) = 0; virtual bool Send(PCOMPKT pComPkt, const unsigned char* pbody, size_t blength) = 0; virtual bool Receive(int fd) = 0; virtual bool NotifyHup(int fd) = 0; virtual bool Processing(PCOMPKT pComPkt) = 0; }; #endif // CHMEVENTBASE_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmlock.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMLOCK_H #define CHMLOCK_H #include <pthread.h> #include <vector> #include <fullock/rwlockrcsv.h> //--------------------------------------------------------- // Symbols(enum) //--------------------------------------------------------- typedef enum chm_lock_kind{ CHMLT_IMDATA, CHMLT_SOCKET, CHMLT_MQ, CHMLT_MQOBJ // use internal MQ event object }CHMLOCKKIND; typedef enum chm_lock_type{ CHMLT_READ, CHMLT_WRITE }CHMLOCKTYPE; #define CHM_STR_CHMLOCKKIND(kind) ( CHMLT_IMDATA == kind ? "IMDATA" : \ CHMLT_SOCKET == kind ? "SOCKET" : \ CHMLT_MQ == kind ? "MQ" : "MQOBJ") #define CHM_STR_CHMLOCKTYPE(type) ( CHMLT_READ == type ? "READ" : "WRITE" ) //--------------------------------------------------------- // ChmLock Class //--------------------------------------------------------- // This class wraps FLRwlRcsv class // class ChmLock : public FLRwlRcsv { protected: CHMLOCKKIND kind; // Lock target kind protected: ChmLock(void); // Not use by any public: ChmLock(CHMLOCKKIND LockKind, CHMLOCKTYPE LockType); ChmLock(CHMLOCKTYPE LockType, int TargetFd, off_t FileOffset); virtual ~ChmLock(); bool IsLocked(void) const { return is_locked; } bool Lock(void); bool UnLock(void); }; #endif // CHMLOCK_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmconfutil.h
<gh_stars>10-100 /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Thu Nor 17 2016 * REVISION: * */ #ifndef CHMCONFUTIL_H #define CHMCONFUTIL_H #include <yaml.h> #include <vector> #include <string> #include "chmcommon.h" //--------------------------------------------------------- // Symbols //--------------------------------------------------------- // Environment #define CHM_CONFFILE_ENV_NAME "CHMCONFFILE" #define CHM_JSONCONF_ENV_NAME "CHMJSONCONF" //--------------------------------------------------------- // Enum //--------------------------------------------------------- // enum for check_chmconf_type(_ex) functions // typedef enum chm_conf_type{ CHMCONF_TYPE_UNKNOWN = -1, CHMCONF_TYPE_NULL = 0, CHMCONF_TYPE_INI_FILE, CHMCONF_TYPE_YAML_FILE, CHMCONF_TYPE_JSON_FILE, CHMCONF_TYPE_JSON_STRING }CHMCONFTYPE; //--------------------------------------------------------- // Utility Functions //--------------------------------------------------------- DECL_EXTERN_C_START bool right_check_json_string(const char* target); bool have_env_chm_conf(void); DECL_EXTERN_C_END bool extract_conf_value(std::string& value); bool getenv_chm_conffile(std::string& value); bool getenv_chm_jsonconf(std::string& value); CHMCONFTYPE check_chmconf_type(const char* config); CHMCONFTYPE check_chmconf_type_ex(const char* config, const char* env_conf_name, const char* env_json_name, std::string* normalize_config); //--------------------------------------------------------- // Structure for CHMYamlDataStack //--------------------------------------------------------- typedef struct chm_yaml_data_pair_type{ yaml_event_type_t first; yaml_event_type_t second; explicit chm_yaml_data_pair_type(yaml_event_type_t first_type = YAML_NO_EVENT) : first(first_type), second(YAML_NO_EVENT) {} }CHM_YAML_DATAPAIR; typedef std::vector<CHM_YAML_DATAPAIR> chm_yaml_datas_t; //--------------------------------------------------------- // Class CHMYamlDataStack //--------------------------------------------------------- class CHMYamlDataStack { private: chm_yaml_datas_t stack; public: CHMYamlDataStack() {} virtual ~CHMYamlDataStack() {} bool empty(void) const { return stack.empty(); } bool add(const yaml_event_type_t& type); }; #endif // CHMCONFUTIL_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmss.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Mon May 13 2018 * REVISION: * */ #ifndef CHMSS_H #define CHMSS_H //--------------------------------------------------------- // Utility Macros //--------------------------------------------------------- #define CVT_ESTR_NULL(pstr) (CHMEMPTYSTR(pstr) ? NULL : pstr) //--------------------------------------------------------- // ChmSecureSock class by each SSL/TLS Library //--------------------------------------------------------- // [NOTE] // It is easier to make ChmSecureSock class a virtual class with base class. // However, instead of switching the SSL / TLS library at run time, the // implementation of the class is fixed at link time, and since it is only // one entity, it is not virtualized. // class ChmSecureSock; //--------------------------------------------------------- // Typedefs for ChmSecureSock class //--------------------------------------------------------- typedef void* ChmSSSession; //--------------------------------------------------------- // Common symbols/macros for ChmSecureSock::CheckResultSSL //--------------------------------------------------------- #define CHKRESULTSSL_TYPE_CON 0 // SSL_accept / SSL_connect #define CHKRESULTSSL_TYPE_RW 1 // SSL_read / SSL_write #define CHKRESULTSSL_TYPE_SD 2 // SSL_shutdown #define IS_SAFE_CHKRESULTSSL_TYPE(type) (CHKRESULTSSL_TYPE_CON == type || CHKRESULTSSL_TYPE_RW == type || CHKRESULTSSL_TYPE_SD == type) //--------------------------------------------------------- // Symbols for ChmSecureSock::SetExtValue method //--------------------------------------------------------- #define CHM_NSS_NSSDB_DIR_KEY "NSSDB_DIR" //--------------------------------------------------------- // Switch SSL/TLS library //--------------------------------------------------------- #ifdef SSL_TLS_TYPE_OPENSSL // OpenSSL #include "chmssopenssl.h" #elif SSL_TLS_TYPE_NSS // NSS #include "chmssnss.h" #elif SSL_TLS_TYPE_GNUTLS // GnuTLS #include "chmssgnutls.h" #endif #endif // CHMSS_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmregex.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMREGEX_H #define CHMREGEX_H //--------------------------------------------------------- // Utilities //--------------------------------------------------------- bool IsSimpleRegexHostname(const char* hostname); bool ExpandSimpleRegexHostname(const char* hostname, strlst_t& expand_lst, bool is_cvt_localhost, bool is_cvt_fqdn = true, bool is_strict = false); bool IsInHostnameList(const char* target, strlst_t& hostname_list, std::string& foundname, bool is_cvt_localhost = false); bool IsMatchHostname(const char* target, strlst_t& regex_lst, std::string& foundname); bool IsMatchCuk(const std::string& cuk, const std::string& basecuk); #endif // CHMREGEX_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmsigcntrl.h
<filename>lib/chmsigcntrl.h /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMSIGCNTRL_H #define CHMSIGCNTRL_H #include <signal.h> #include <map> #include <fullock/flckstructure.h> #include <fullock/flckbaselist.tcc> //--------------------------------------------------------- // ChmSigCntrl Class //--------------------------------------------------------- class ChmSigCntrlHelper; class ChmSigCntrl { protected: static ChmSigCntrlHelper& GetHelper(void); bool SetHandlerEx(int signum, sighandler_t handler, bool is_locked); // can set NULL/SIG_DFL/SIG_IGN bool FindSignalEx(int signum, bool is_locked); bool ResetAllHandler(void); public: ChmSigCntrl(void); virtual ~ChmSigCntrl(); bool Initialize(int* psignums, int count); bool GetSignalMask(sigset_t& sigset); bool SetSignalProcMask(void); bool SetHandler(int signum, sighandler_t handler) { return SetHandlerEx(signum, handler, false); } }; #endif // CHMSIGCNTRL_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmeventsock.h
<filename>lib/chmeventsock.h /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMEVENTSOCK_H #define CHMEVENTSOCK_H #include <pthread.h> #include <string> #include <map> #include "chmeventbase.h" #include "chmthread.h" #include "chmlockmap.tcc" #include "chmconf.h" //--------------------------------------------------------- // Symbols (must be defined before chmss.h) //--------------------------------------------------------- #define PXCOMPKT_AUTO_LENGTH (-1) #define WAIT_READ_FD 1 #define WAIT_WRITE_FD 2 #define WAIT_BOTH_FD (WAIT_READ_FD | WAIT_WRITE_FD) #define ISSAFE_WAIT_FD(type) (0 != (type & WAIT_BOTH_FD)) #define IS_WAIT_READ_FD(type) (0 != (type & WAIT_READ_FD)) #define IS_WAIT_WRITE_FD(type) (0 != (type & WAIT_WRITE_FD)) #define CHMEVENTSOCK_RETRY_DEFAULT (-1) #define CHMEVENTSOCK_TIMEOUT_DEFAULT (0) // // Include SSL/TLS implement header // #include "chmss.h" //--------------------------------------------------------- // Structure //--------------------------------------------------------- typedef struct chm_send_sock_status{ pid_t tid; // thread id of locking socket time_t last_time; // last using(locking) time }CHMSSSTAT, *PCHMSSSTAT; //--------------------------------------------------------- // Typedefs //--------------------------------------------------------- typedef std::map<chmpxid_t, reqidmapflag_t> mergeidmap_t; typedef chm_lock_map<int, chmpxid_t> sock_ids_map_t; typedef chm_lock_map<int, std::string> sock_pending_map_t; typedef chm_lock_map<int, ChmSSSession> sock_ssl_map_t; typedef chm_lock_map<int, PCHMSSSTAT> sendlockmap_t; //--------------------------------------------------------- // ChmEventSock Class //--------------------------------------------------------- // [NOTE] About multi-threading // // This class should have exclusion control for socket on multi-threading. // Then this class controls closing/opening/accepting socket as exclusion, // thus these processing can not run at same time. // And this class can send data to particular socket by only one thread at // same time because the socket is locked by that thread. // These two exclusion control are independent of each other, so we can // open new socket during sending data as an example. // // And contrary to the above, this class does not lock the socket for // receiving. The reason is that the receiving from the same socket is // processed sequentially, thus we do not need to lock the socket for // receiving. However the processing such as open(close) is caught during // we are receiving from the socket, but we can probably fail to receive // by closing the socket. // Thus we can stop the processing to receive by getting error. // class ChmEventSock : public ChmEventBase { public: static const int DEFAULT_SOCK_THREAD_CNT = 0; // socket processing thread count static const int DEFAULT_MAX_SOCK_POOL = 1; // max socket count for each chmpx static const time_t DEFAULT_SOCK_POOL_TIMEOUT = 60; // timeout value till closing for not used socket in pool static const time_t NO_SOCK_POOL_TIMEOUT = 0; // no timeout for socket pool static const int DEFAULT_KEEPIDLE = 60; // time until sending keep alive static const int DEFAULT_KEEPINTERVAL = 10; // interval for sending keep alive static const int DEFAULT_KEEPCOUNT = 3; // maximum count of sending keep alive static const int DEFAULT_LISTEN_BACKLOG = 256; static const int DEFAULT_RETRYCNT = 500; // retry count for send and receive(total default wait = 200us * 500 = 100ms) static const int DEFAULT_RETRYCNT_CONNECT = 200; // retry count for connect.( total = 5ms * 200 = 1s ) static const suseconds_t DEFAULT_WAIT_SOCKET = 200; // timeout/count for send and receive.(200us) static const suseconds_t DEFAULT_WAIT_CONNECT = 5 * 1000; // timeout/count for connect.(5ms) protected: typedef enum chm_downsvr_merge_type{ // for ChangeDownSvrStatusBeforeMerge method CHM_DOWNSVR_MERGE_START, CHM_DOWNSVR_MERGE_COMPLETE, CHM_DOWNSVR_MERGE_ABORT }CHMDOWNSVRMERGE; ChmSecureSock* pSecureSock; // SSL/TLS Library wrapper object sock_ids_map_t seversockmap; // to server sockets sock_ids_map_t slavesockmap; // from slave sockets sock_pending_map_t acceptingmap; // from slave sockets before accepting sock_ids_map_t ctlsockmap; // from client sockets to ctlport sock_ssl_map_t sslmap; // to server/from slave ssl object mapping sendlockmap_t sendlockmap; // lock socket map for sending bool startup_servicein; // SERVICE IN pending at start when automerge mode is true volatile bool is_run_merge; // whichever run or abort in merging ChmThread procthreads; // processing threads ChmThread mergethread; // merge thread volatile int sockfd_lockval; // lock variable for open/close/accept socket time_t last_check_time; // last unix time at checking socket pool timeout volatile int dyna_sockfd_lockval; // lock variable for new connection dynamic volatile int mergeidmap_lockval; // lock variable for chmpxid mapping mergeidmap_t mergeidmap; // chmpxid mapping for update datas bool is_server_mode; // cache value for ChmIMData::IsServerMode() int max_sock_pool; // cache value for ChmIMData::GetMaxSockPool() time_t sock_pool_timeout; // cache value for ChmIMData::GetSockPoolTimeout() int sock_retry_count; // cache value for retry count for send and receive int con_retry_count; // cache value for retry count for connect suseconds_t sock_wait_time; // cache value for timeout/count for send and receive suseconds_t con_wait_time; // cache value for total timeout for connect comver_t comproto_ver; // communication protocol version available for RING bool is_merge_done_processing; // flag for processing to merge done protected: static bool SetNonblocking(int sock); static int Listen(const char* hostname, short port); static int RawListen(struct addrinfo* paddrinfo); static int Connect(const char* hostname, short port, bool is_blocking = false, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool RawSend(int sock, ChmSSSession ssl, PCOMPKT pComPkt, bool& is_closed, bool is_blocking = false, int retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool RawSend(int sock, ChmSSSession ssl, const unsigned char* pbydata, size_t length, bool& is_closed, bool is_blocking = false, int retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool RawReceiveByte(int sock, ChmSSSession ssl, bool& is_closed, unsigned char* pbuff, size_t length, bool is_blocking = false, int retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool RawReceiveAny(int sock, bool& is_closed, unsigned char* pbuff, size_t* plength, bool is_blocking = false, int retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool RawReceive(int sock, ChmSSSession ssl, bool& is_closed, PCOMPKT* ppComPkt, size_t pktlength = 0L, bool is_blocking = false, int retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool RawSendCtlPort(const char* hostname, short ctlport, const unsigned char* pbydata, size_t length, std::string& strResult, volatile int& sockfd_lockval, int retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool hton(PCOMPKT pComPkt, size_t& length); static bool ntoh(PCOMPKT pComPkt, bool is_except_compkt = false); static PCOMPKT AllocatePxComPacket(pxcomtype_t type, ssize_t ext_length = PXCOMPKT_AUTO_LENGTH); static PCOMPKT DuplicateComPkt(PCOMPKT pComPkt); // callback functions for thread class static bool ReceiveWorkerProc(void* common_param, chmthparam_t wp_param); // callback functions for merging static bool MergeWorkerFunc(void* common_param, chmthparam_t wp_param); // callback functions for locked map class static bool ServerSockMapCallback(const sock_ids_map_t::iterator& iter, void* psockobj); static bool SlaveSockMapCallback(const sock_ids_map_t::iterator& iter, void* psockobj); static bool AcceptMapCallback(const sock_pending_map_t::iterator& iter, void* psockobj); static bool ControlSockMapCallback(const sock_ids_map_t::iterator& iter, void* psockobj); static bool SslSockMapCallback(const sock_ssl_map_t::iterator& iter, void* psockobj); static bool SendLockMapCallback(const sendlockmap_t::iterator& iter, void* psockobj); // close connection bool CloseSelfSocks(void); bool CloseFromSlavesSocks(void); bool CloseCtlportClientSocks(void); bool CloseToServersSocks(void); bool CloseFromSlavesAcceptingSocks(void); bool CloseSSL(int sock, bool with_sock = true); bool CloseAllSSL(void); bool CloseSocketWithEpoll(int sock); // SSL ChmSSSession GetSSL(int sock); bool IsSafeParamsForSSL(void); // Socket lock for sending bool LockSendSock(int sock) { return RawLockSendSock(sock, true, false); } bool TryLockSendSock(int sock) { return RawLockSendSock(sock, true, true); } bool UnlockSendSock(int sock) { return RawLockSendSock(sock, false, false); } bool RawLockSendSock(int sock, bool is_lock, bool is_once); bool GetLockedSendSock(chmpxid_t chmpxid, int& sock, bool is_check_slave); // Send with locking bool LockedSend(int sock, ChmSSSession ssl, PCOMPKT pComPkt, bool is_blocking = false); bool LockedSend(int sock, ChmSSSession ssl, const unsigned char* pbydata, size_t length, bool is_blocking = false); // Utility chmpxid_t GetAssociateChmpxid(int fd); std::string GetAssociateAcceptHostName(int fd); bool RawClearSelfWorkerStatus(int fd); // Receive bool RawReceive(int fd, bool& is_closed); // connect/accept bool ConnectServer(chmpxid_t chmpxid, int& sock, bool without_set_imdata); bool RawConnectServer(chmpxid_t chmpxid, int& sock, bool without_set_imdata, bool is_lock); bool CloseRechainRing(chmpxid_t nowchmpxid); bool RechainRing(chmpxid_t newchmpxid); bool CheckRechainRing(chmpxid_t newchmpxid, bool& is_rechain); chmpxid_t GetNextRingChmpxId(void); bool IsSafeDeptAndNextChmpxId(chmpxid_t dept_chmpxid, chmpxid_t next_chmpxid); bool Accept(int sock); bool AcceptCtlport(int ctlsock); bool InitialComVersion(int sock, chmpxid_t chmpxid, comver_t& com_proto_version); bool Processing(int sock, const char* pCommand); // for merge bool IsAutoMerge(void); bool IsDoMerge(void); bool ContinuousAutoMerge(void); bool CheckAllStatusForMergeStart(void) const; bool CheckAllStatusForMergeComplete(void) const; bool ChangeStatusBeforeMergeStart(void); bool ChangeDownSvrStatusByMerge(CHMDOWNSVRMERGE mode); bool MergeStart(void); bool MergeAbort(void); bool MergeDone(void); bool MergeComplete(void); bool RequestMergeStart(std::string* pstring = NULL); bool RequestMergeAbort(std::string* pstring = NULL); bool RequestMergeComplete(std::string* pstring = NULL); bool RequestMergeSuspend(std::string* pstring = NULL); bool RequestMergeNoSuspend(std::string* pstring = NULL); bool RequestServiceIn(std::string* pstring = NULL); bool RequestServiceOut(chmpxid_t chmpxid = CHM_INVALID_CHMPXID, std::string* pstring = NULL); // notification bool RawNotifyHup(int fd); bool ServerDownNotifyHup(chmpxid_t chmpxid); bool ServerSockNotifyHup(int fd, bool& is_close, chmpxid_t& chmpxid); bool SlaveSockNotifyHup(int fd, bool& is_close); bool AcceptingSockNotifyHup(int fd, bool& is_close); bool ControlSockNotifyHup(int fd, bool& is_close); // ctlport commands bool SendCtlPort(chmpxid_t chmpxid, const unsigned char* pbydata, size_t length, std::string& strResult); bool CtlComDump(std::string& strResponse); bool CtlComMergeStart(std::string& strResponse); bool CtlComMergeAbort(std::string& strResponse); bool CtlComMergeComplete(std::string& strResponse); bool CtlComMergeSuspend(std::string& strResponse); bool CtlComMergeNoSuspend(std::string& strResponse); bool CtlComServiceIn(std::string& strResponse); bool CtlComServiceOut(const char* hostname, short ctlport, const char* cuk, const char* ctlendpoints, const char* custom_seed, const char* pOrgCommand, std::string& strResponse); bool CtlComSelfStatus(std::string& strResponse); bool CtlComAllServerStatus(std::string& strResponse); bool CtlComUpdateStatus(std::string& strResponse); bool CtlComAllTraceSet(std::string& strResponse, bool enable); bool CtlComAllTraceView(std::string& strResponse, logtype_t dirmask, logtype_t devmask, long count); // px2px commands bool PxComSendStatusReq(int sock, chmpxid_t chmpxid, bool need_sock_close); bool PxComReceiveStatusReq(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComReceiveStatusRes(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt, bool is_init_process = false); bool PxComSendConinitReq(int sock, chmpxid_t chmpxid); bool PxComReceiveConinitReq(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt, comver_t& comver, std::string& name, chmpxid_t& from_chmpxid, short& ctlport, std::string& cuk, std::string& custom_seed, hostport_list_t& endpoints, hostport_list_t& ctlendpoints, hostport_list_t& forward_peers, hostport_list_t& reverse_peers); bool PxComSendConinitRes(int sock, chmpxid_t chmpxid, comver_t comver, pxcomres_t result); bool PxComReceiveConinitRes(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt, pxcomres_t& result); bool PxComSendJoinRing(chmpxid_t chmpxid, PCHMPXSVR pserver); bool PxComReceiveJoinRing(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComSendStatusUpdate(chmpxid_t chmpxid, PCHMPXSVR pchmpxsvrs, long count); bool PxComReceiveStatusUpdate(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComSendStatusConfirm(chmpxid_t chmpxid, PCHMPXSVR pchmpxsvrs, long count); bool PxComReceiveStatusConfirm(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComSendStatusChange(chmpxid_t chmpxid, PCHMPXSVR pserver, bool is_send_slaves = true); bool PxComSendSlavesStatusChange(PCHMPXSVR pserver); bool PxComReceiveStatusChange(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComSendMergeStart(chmpxid_t chmpxid); bool PxComReceiveMergeStart(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComSendMergeAbort(chmpxid_t chmpxid); bool PxComReceiveMergeAbort(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComSendMergeComplete(chmpxid_t chmpxid); bool PxComReceiveMergeComplete(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt, bool& is_completed); bool PxComSendMergeSuspend(chmpxid_t chmpxid); bool PxComReceiveMergeSuspend(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComSendMergeNoSuspend(chmpxid_t chmpxid); bool PxComReceiveMergeNoSuspend(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComSendMergeSuspendGet(int sock, chmpxid_t chmpxid); bool PxComReceiveMergeSuspendGet(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComReceiveMergeSuspendRes(PCOMHEAD pComHead, PPXCOM_ALL pComAll); bool PxComSendServerDown(chmpxid_t chmpxid, chmpxid_t downchmpxid); bool PxComReceiveServerDown(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxCltReceiveJoinNotify(PCOMHEAD pComHead, PPXCLT_ALL pComAll); bool PxComSendReqUpdateData(chmpxid_t chmpxid, const PPXCOMMON_MERGE_PARAM pmerge_param); bool PxComReceiveReqUpdateData(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt); bool PxComReceiveResUpdateData(PCOMHEAD pComHead, PPXCOM_ALL pComAll); bool PxComReceiveResultUpdateData(PCOMHEAD pComHead, PPXCOM_ALL pComAll); bool PxComSendVersionReq(int sock, chmpxid_t chmpxid, bool need_sock_close); // 1.0.71 or later bool PxComReceiveVersionReq(int sock, PCOMHEAD pComHead, PPXCOM_ALL pComAll); // 1.0.71 or later bool PxComReceiveVersionRes(PCOMHEAD pComHead, PPXCOM_ALL pComAll, PCOMPKT* ppResComPkt, comver_t& com_proto_version); // 1.0.71 or later public: static void AllowSelfSignedCert(void); static void DenySelfSignedCert(void); static int WaitForReady(int sock, int type, int retrycnt, bool is_check_so_error = false, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); ChmEventSock(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL, bool is_ssl = false); virtual ~ChmEventSock(); bool InitialAllServerStatus(void); bool ConnectRing(void); bool ConnectServers(void); bool DoSuspend(void); virtual bool Clean(void); virtual bool UpdateInternalData(void); virtual bool GetEventQueueFds(event_fds_t& fds); virtual bool SetEventQueue(void); // Make Socket for receiver side and add it to event queue fd. virtual bool UnsetEventQueue(void); // Unset mqfd from event queue fd, and destroy it. virtual bool IsEventQueueFd(int fd); virtual bool Send(PCOMPKT pComPkt, const unsigned char* pbody, size_t blength); virtual bool Receive(int fd); virtual bool NotifyHup(int fd); virtual bool Processing(PCOMPKT pComPkt); bool PxComSendResUpdateData(chmpxid_t chmpxid, size_t length, const unsigned char* pdata, const struct timespec* pts); bool PxComSendResultUpdateData(chmpxid_t chmpxid, reqidmapflag_t result_updatedata); }; #endif // CHMEVENTSOCK_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmimdata.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMIMDATA_H #define CHMIMDATA_H #include <k2hash/k2hash.h> #include <k2hash/k2hshm.h> #include <fullock/rwlockrcsv.h> #include "chmstructure.tcc" //--------------------------------------------------------- // Prototype //--------------------------------------------------------- class CHMConf; //--------------------------------------------------------- // Structures //--------------------------------------------------------- typedef struct chminfo_ex{ PCHMINFO pchminfo; char shmpath[CHM_MAX_PATH_LEN]; size_t shmsize; char k2hashpath[CHM_MAX_PATH_LEN]; }CHMINFOEX, *PCHMINFOEX; //--------------------------------------------------------- // Class ChmIMData //--------------------------------------------------------- // Chm Internal Management Data Class // class ChmIMData { protected: typedef enum mkfpath_mode{ MKFILEPATH_SHM = 0, MKFILEPATH_K2H }MKFPMODE; protected: static const int SYSPAGE_SIZE = 4096; std::string ShmPath; // ChmShm file path PCHMSHM pChmShm; // SHM mmap base int ShmFd; // SHM fd size_t ShmSize; // SHM size CHMConf* pConfObj; // CHMConf file object K2HShm* pK2hash; // K2HASH object int eqfd; // backup bool isChmpxProc; // CHMPX process or Client library pid_t ChmpxPid; // backup chmpx pid for checking process down on slave protected: static bool MakeFilePath(const char* groupname, short port, MKFPMODE mode, std::string& shmpath); static bool MakeShmFilePath(const char* groupname, short port, std::string& shmpath); static bool MakeK2hashFilePath(const char* groupname, short port, std::string& shmpath); static bool CompareChmpxNameAndCustomSeed(const CHMPXSVR& src1, const CHMPXSVR& src2, bool is_check_custom_seed); static bool CompareChmpxSvrs(PCHMPXSVR pbase, long bcount, PCHMPXSVR pmerge, long mcount, bool is_check_custom_seed, bool is_status = true, bool ignore_down = true); off_t GetLockOffsetForMQ(void) const; bool CloseShm(void); bool InitializeShm(void); bool InitializeShmEx(const CHMCFGINFO& chmcfg, const CHMNODE_CFGINFO* pself, const char* pnormalizedname); bool IsAttachedShm(void) const { return (NULL != pChmShm); } bool AttachShm(void); // For client process library bool InitializeOther(void); bool CloseK2hash(void); bool InitializeK2hash(void); bool IsAttachedK2hash(void) const { return (NULL != pK2hash); } bool AttachK2hash(void); // For client process library msgid_t AssignMsg(bool is_chmpx, bool is_activated); // Assign MQ bool ActivateMsgEx(msgid_t msgid, bool is_activate); // set msgid activated status msgid_t GetRandomMsgId(bool is_chmpx); // Process running bool LockChmpxPid(void); bool UnlockChmpxPid(void); bool IsChmpxProcessRunning(pid_t& pid) const; // Client pid list bool RawLockClientPidList(FLRwlRcsv& lockobj, bool is_read) const; bool ReadLockClientPidList(FLRwlRcsv& lockobj) const { return RawLockClientPidList(lockobj, true); } bool WriteLockClientPidList(FLRwlRcsv& lockobj) const { return RawLockClientPidList(lockobj, false); } // Do not call these method, must call SetSlaveAll bool SetSlaveBase(chmpxid_t chmpxid, const char* hostname, short ctlport, const char* cuk, const char* custom_seed, const hostport_list_t& endpoints, const hostport_list_t& ctlendpoints, const hostport_list_t& forward_peers, const hostport_list_t& reverse_peers, const PCHMPXSSL pssl); bool SetSlaveSock(chmpxid_t chmpxid, int sock); bool SetSlaveStatus(chmpxid_t chmpxid, chmpxsts_t status); bool RemoveSlave(chmpxid_t chmpxid); public: static void FreeDupAllChmInfo(PCHMINFOEX ptr); // for free memory allocated by DupAllChmInfo() static void FreeDupSelfChmpxInfo(PCHMPX ptr); // for free memory allocated by DupSelfChmpxInfo() static bool IsSafeCHMINFO(const PCHMINFO pchminfo); explicit ChmIMData(bool is_chmpx_proc = true); virtual ~ChmIMData(); bool Close(void); bool CloseSocks(int type = CLOSETG_BOTH); bool IsInitialized(void) const { return (pChmShm && CHM_INVALID_HANDLE != ShmFd && pConfObj && pK2hash); } bool Initialize(CHMConf* cfgobj, int eventqfd, bool is_chmpx_proc); bool ReloadConfiguration(void); // now reload without server/slave list const CHMSHM* GetShmBase(void) const { return pChmShm; } const char* GetShmPath(void) const { return ShmPath.c_str(); } K2HShm* GetK2hashObj(void) { return pK2hash; } bool Dump(std::stringstream& sstream) const; bool DumpSelfChmpxSvr(std::stringstream& sstream) const; PCHMINFOEX DupAllChmInfo(void); PCHMPX DupSelfChmpxInfo(void); // MQ msgid_t GetBaseMsgId(void) const; bool FreeMsg(msgid_t msgid); // Free msgid bool IsMsgidActivated(msgid_t msgid) const; bool FreeMsgs(const pidlist_t& pidlist, msgidlist_t& freedmsgids); // Free msgids by pid msgid_t AssignMsgOnChmpx(void) { return AssignMsg(true, true); } msgid_t AssignMsgOnServer(void) { return AssignMsg(false, true); } msgid_t AssignMsgOnSlave(bool is_activated = true) { return AssignMsg(false, is_activated); } bool ActivateMsg(msgid_t msgid) { return ActivateMsgEx(msgid, true); } // Activate Msgid bool DisactivateMsg(msgid_t msgid) { return ActivateMsgEx(msgid, false); } // Disactivate Msgid msgid_t GetRandomChmpxMsgId(void) { return GetRandomMsgId(true); } // get msgid from assigned list for chmpx msgid_t GetRandomClientMsgId(void) { return GetRandomMsgId(false); } // get msgid from assigned list for not chmpx bool GetMsgidListByPid(pid_t pid, msgidlist_t& list); // get all msgid list by pid bool GetMsgidListByUniqPid(msgidlist_t& list); // get msgid list for all uniq pid // CHMSHM bool GetSelfChmpxSvr(PCHMPXSVR chmpxsvr) const; bool GetChmpxSvr(chmpxid_t chmpxid, PCHMPXSVR chmpxsvr) const; bool GetChmpxSvrs(PCHMPXSVR* ppchmpxsvrs, long& count) const; bool CompareChmpxSvrs(PCHMPXSVR pchmpxsvrs, long count); bool MergeChmpxSvrs(PCHMPXSVR pchmpxsvrs, long count, bool is_remove = true, bool is_init_process = false, int eqfd = CHM_INVALID_HANDLE); bool MergeChmpxSvrsForStatusUpdate(PCHMPXSVR pchmpxsvrs, long count, int eqfd); bool GetGroup(std::string& group) const; bool IsRandomDeliver(void) const; bool IsAutoMerge(void) const; bool IsDoMerge(void) const; bool SuspendAutoMerge(void); bool ResetAutoMerge(void); bool GetAutoMergeMode(void) const; chmss_ver_t GetSslMinVersion(void) const; const char* GetNssdbDir(void) const; int GetSocketThreadCount(void) const; int GetMQThreadCount(void) const; int GetMaxSockPool(void) const; time_t GetSockPoolTimeout(void) const; long GetMaxMQCount(void) const; long GetChmpxMQCount(void) const; long GetMaxQueuePerChmpxMQ(void) const; long GetMaxQueuePerClientMQ(void) const; long GetMQPerClient(void) const; long GetMQPerAttach(void) const; bool IsAckMQ(void) const; int GetSockRetryCnt(void) const; suseconds_t GetSockTimeout(void) const; suseconds_t GetConnectTimeout(void) const; int GetMQRetryCnt(void) const; long GetMQTimeout(void) const; time_t GetMergeTimeout(void) const; bool IsServerMode(void) const; bool IsSlaveMode(void) const; long GetReplicaCount(void) const; long GetMaxHistoryLogCount(void) const; bool IsChmpxProcess(void) const { return isChmpxProc; } chmpxid_t GetSelfChmpxId(void) const; long GetServerCount(void) const; long GetSlaveCount(void) const; long GetUpServerCount(void) const; chmpxpos_t GetSelfServerPos(void) const; chmpxpos_t GetNextServerPos(chmpxpos_t startpos, chmpxpos_t nowpos, bool is_skip_self, bool is_cycle) const; bool GetNextServerBase(std::string* pname, chmpxid_t* pchmpxid, short* pport, short* pctlport, hostport_list_t* pendpoints = NULL, hostport_list_t* pctlendpoints = NULL) const; chmpxid_t GetNextServerChmpxId(void) const; chmpxid_t GetNextRingChmpxId(chmpxid_t chmpxid = CHM_INVALID_CHMPXID) const; bool IsOperating(void); bool IsServerChmpxId(chmpxid_t chmpxid) const; chmpxid_t GetChmpxIdBySock(int sock, int type = CLOSETG_BOTH) const; chmpxid_t GetChmpxIdByToServerSock(int sock) const { return GetChmpxIdBySock(sock, CLOSETG_SERVERS); } chmpxid_t GetChmpxIdByFromSlaveSock(int sock) const { return GetChmpxIdBySock(sock, CLOSETG_SLAVES); } chmpxid_t GetChmpxIdByToServerName(const char* hostname, short ctlport, const char* cuk, const char* ctlendpoints, const char* custom_seed) const; chmpxid_t GetChmpxIdByStatus(chmpxsts_t status, bool part_match = false) const; chmpxid_t GetRandomServerChmpxId(bool without_suspend = false); chmpxid_t GetServerChmpxIdByHash(chmhash_t hash) const; bool GetServerChmHashsByHashs(chmhash_t hash, chmhashlist_t& basehashs, bool with_pending = true, bool without_down = true, bool without_suspend = true); bool GetServerChmpxIdByHashs(chmhash_t hash, chmpxidlist_t& chmpxids, bool with_pending = true, bool without_down = true, bool without_suspend = true); long GetServerChmpxIdByBaseHash(chmhash_t basehash, chmpxidlist_t& chmpxids) const; long GetServerChmpxIdForMerge(chmpxidlist_t& list) const; long GetServerChmpxIds(chmpxidlist_t& list) const; bool GetServerBase(long pos, std::string* pname = NULL, chmpxid_t* pchmpxid = NULL, short* pport = NULL, short* pctlport = NULL, hostport_list_t* pendpoints = NULL, hostport_list_t* pctlendpoints = NULL) const; bool GetServerBase(chmpxid_t chmpxid, std::string* pname = NULL, short* pport = NULL, short* pctlport = NULL, hostport_list_t* pendpoints = NULL, hostport_list_t* pctlendpoints = NULL) const; bool GetServerBase(chmpxid_t chmpxid, CHMPXSSL& ssl) const; bool GetServerSocks(chmpxid_t chmpxid, socklist_t& socklist, int& ctlsock) const; bool GetServerSock(chmpxid_t chmpxid, socklist_t& socklist) const { int tmp; return GetServerSocks(chmpxid, socklist, tmp); } bool IsConnectServer(chmpxid_t chmpxid) const { socklist_t tmpsocklist; return (GetServerSock(chmpxid, tmpsocklist) && !tmpsocklist.empty()); } bool GetServerCtlSock(chmpxid_t chmpxid, int& ctlsock) const { socklist_t tmplist; return GetServerSocks(chmpxid, tmplist, ctlsock); } bool GetServerHash(chmpxid_t chmpxid, chmhash_t& base, chmhash_t& pending) const; bool GetServerBaseHash(chmpxid_t chmpxid, chmhash_t& hash) const { chmhash_t tmp; return GetServerHash(chmpxid, hash, tmp); } bool GetServerPendingHash(chmpxid_t chmpxid, chmhash_t& hash) const { chmhash_t tmp; return GetServerHash(chmpxid, tmp, hash); } bool GetMaxHashCount(chmhash_t& basehash, chmhash_t& pendinghash) const; bool GetMaxBaseHashCount(chmhash_t& basehash) const { chmhash_t tmp; return GetMaxHashCount(basehash, tmp); } bool GetMaxPendingHashCount(chmhash_t& pendinghash) const { chmhash_t tmp; return GetMaxHashCount(tmp, pendinghash); } bool IsPendingExchangeData(void) const; long GetReceiverChmpxids(chmhash_t hash, c2ctype_t c2ctype, chmpxidlist_t& chmpxids); chmpxsts_t GetServerStatus(chmpxid_t chmpxid) const; bool GetSelfPorts(short& port, short& ctlport) const; bool GetSelfSocks(int& sock, int& ctlsock) const; bool GetSelfHash(chmhash_t& base, chmhash_t& pending) const; bool GetSelfBaseHash(chmhash_t& hash) const { chmhash_t tmp; return GetSelfHash(hash, tmp); } bool GetSelfPendingHash(chmhash_t& hash) const { chmhash_t tmp; return GetSelfHash(tmp, hash); } chmpxsts_t GetSelfStatus(void) const; bool GetSelfSsl(CHMPXSSL& ssl) const; bool GetSelfBase(std::string* pname = NULL, short* pport = NULL, short* pctlport = NULL, std::string* pcuk = NULL, std::string* pcustom_seed = NULL, hostport_list_t* pendpoints = NULL, hostport_list_t* pctlendpoints = NULL, hostport_list_t* pforward_peers = NULL, hostport_list_t* preverse_peers = NULL) const; long GetSlaveChmpxIds(chmpxidlist_t& list) const; bool GetSlaveBase(chmpxid_t chmpxid, std::string* pname = NULL, short* pctlport = NULL, std::string* pcuk = NULL, std::string* pcustom_seed = NULL, hostport_list_t* pendpoints = NULL, hostport_list_t* pctlendpoints = NULL, hostport_list_t* pforward_peers = NULL, hostport_list_t* preverse_peers = NULL) const; bool GetSlaveSock(chmpxid_t chmpxid, socklist_t& socklist) const; bool IsConnectSlave(chmpxid_t chmpxid) const { socklist_t tmplist; return (GetSlaveSock(chmpxid, tmplist) && !tmplist.empty()); } chmpxsts_t GetSlaveStatus(chmpxid_t chmpxid) const; bool SetServerSocks(chmpxid_t chmpxid, int sock, int ctlsock, int type); bool SetServerHash(chmpxid_t chmpxid, chmhash_t base, chmhash_t pending, int type); bool SetServerBaseHash(chmpxid_t chmpxid, chmhash_t hash) { return SetServerHash(chmpxid, hash, 0L, HASHTG_BASE); } bool SetServerPendingHash(chmpxid_t chmpxid, chmhash_t hash) { return SetServerHash(chmpxid, 0L, hash, HASHTG_PENDING); } bool SetServerStatus(chmpxid_t chmpxid, chmpxsts_t status); bool UpdateSelfLastStatusTime(void) { return UpdateLastStatusTime(CHM_INVALID_CHMPXID); } bool UpdateLastStatusTime(chmpxid_t chmpxid); bool RemoveServerSock(chmpxid_t chmpxid, int sock); bool UpdateHash(int type, bool is_allow_operating = true); bool SetSelfSocks(int sock, int ctlsock); bool SetSelfHash(chmhash_t base, chmhash_t pending, int type); bool SetSelfBaseHash(chmhash_t hash) { return SetSelfHash(hash, 0L, HASHTG_BASE); } bool SetSelfPendingHash(chmhash_t hash) { return SetSelfHash(0L, hash, HASHTG_PENDING); } bool SetSelfStatus(chmpxsts_t status); bool SetSlaveAll(chmpxid_t chmpxid, const char* hostname, short ctlport, const char* cuk, const char* custom_seed, const hostport_list_t* pendpoints, const hostport_list_t* pctlendpoints, const hostport_list_t* pforward_peers, const hostport_list_t* preverse_peers, const PCHMPXSSL pssl, int sock, chmpxsts_t status); bool RemoveSlaveSock(chmpxid_t chmpxid, int sock); bool CheckSockInAllChmpx(int sock) const; // Stats bool AddStat(chmpxid_t chmpxid, bool is_sent, size_t bodylength, const struct timespec& elapsed_time); bool GetStat(PCHMSTAT pserver, PCHMSTAT pslave) const; // Trace(History) long GetTraceCount(void) const; bool IsTraceEnable(void) const; bool EnableTrace(void); bool DisableTrace(void); bool AddTrace(logtype_t logtype, size_t length, const struct timespec& start, const struct timespec& fin); bool GetTrace(PCHMLOGRAW plograwarr, long& arrsize, logtype_t dirmask, logtype_t devmask) const; // Process running bool RetrieveClientPid(pid_t pid); bool AddClientPid(pid_t pid); bool GetAllPids(pidlist_t& list); bool IsClientPids(void) const; bool IsNeedDetach(void) const; // Others CHMPXID_SEED_TYPE GetChmpxSeedType(void) const; bool IsAllowHost(const char* hostname); bool IsAllowHostStrictly(const char* hostname, short ctlport, const char* cuk, std::string& normalizedname, PCHMPXSSL pssl); }; #endif // CHMIMDATA_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmconf.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMCONF_H #define CHMCONF_H #include <k2hash/k2hshm.h> #include <string> #include <list> #include "chmcommon.h" #include "chmutil.h" #include "chmstructure.h" #include "chmeventbase.h" //--------------------------------------------------------- // Symbols //--------------------------------------------------------- #define UNINITIALIZE_REVISION (-1) //--------------------------------------------------------- // Structures //--------------------------------------------------------- // // configuration information for host and port // typedef struct host_port_pair{ std::string host; short port; host_port_pair() : host(""), port(0) {} explicit host_port_pair(const struct host_port_pair& other) : host(other.host), port(other.port) {} bool compare(const struct host_port_pair& other) const { return (host == other.host && port == other.port); } struct host_port_pair& operator=(const struct host_port_pair& other) { host = other.host; port = other.port; return *this; } bool operator==(const struct host_port_pair& other) const { return compare(other); } bool operator!=(const struct host_port_pair& other) const { return !compare(other); } std::string get_string(void) const { std::string result(host); if(CHM_INVALID_PORT != port){ result += ":"; result += to_string(port); } return result; } }HOSTPORTPAIR, *PHOSTPORTPAIR; typedef std::list<HOSTPORTPAIR> hostport_list_t; inline std::string get_hostports_string(const hostport_list_t& list) { std::string result; for(hostport_list_t::const_iterator iter = list.begin(); list.end() != iter; ++iter){ if(!result.empty()){ result += ","; } result += iter->get_string(); } return result; } inline bool compare_hostports(const hostport_list_t& src1, const hostport_list_t& src2) { if(src1.size() != src2.size()){ return false; } hostport_list_t::const_iterator iter1; hostport_list_t::const_iterator iter2; for(iter1 = src1.begin(), iter2 = src2.begin(); iter1 != src1.end() && iter2 != src2.end(); ++iter1, ++iter2){ if(iter1->host != iter2->host || iter1->port != iter2->port){ return false; } } return true; } // // configuration information for node // typedef struct chm_node_cfg_info{ std::string name; short port; short ctlport; bool is_ssl; bool verify_peer; // verify ssl client peer on server bool is_ca_file; std::string capath; std::string server_cert; std::string server_prikey; std::string slave_cert; std::string slave_prikey; std::string cuk; // after v1.0.71 hostport_list_t endpoints; // after v1.0.71 hostport_list_t ctlendpoints; // after v1.0.71 hostport_list_t forward_peers; // after v1.0.71 hostport_list_t reverse_peers; // after v1.0.71 std::string custom_seed; // after v1.0.71 chm_node_cfg_info() : name(""), port(0), ctlport(0), is_ssl(false), verify_peer(false), is_ca_file(false), capath(""), server_cert(""), server_prikey(""), slave_cert(""), slave_prikey(""), cuk(""), // after v1.0.71 custom_seed("") // after v1.0.71 {} explicit chm_node_cfg_info(const struct chm_node_cfg_info& other) : name(other.name), port(other.port), ctlport(other.ctlport), is_ssl(other.is_ssl), verify_peer(other.verify_peer), is_ca_file(other.is_ca_file), capath(other.capath), server_cert(other.server_cert), server_prikey(other.server_prikey), slave_cert(other.slave_cert), slave_prikey(other.slave_prikey), cuk(other.cuk), // after v1.0.71 endpoints(other.endpoints), // after v1.0.71 ctlendpoints(other.ctlendpoints), // after v1.0.71 forward_peers(other.forward_peers), // after v1.0.71 reverse_peers(other.reverse_peers), // after v1.0.71 custom_seed(other.custom_seed) // after v1.0.71 {} bool compare(const struct chm_node_cfg_info& other) const { if( name == other.name && port == other.port && ctlport == other.ctlport && is_ssl == other.is_ssl && verify_peer == other.verify_peer && is_ca_file == other.is_ca_file && capath == other.capath && server_cert == other.server_cert && server_prikey == other.server_prikey && slave_cert == other.slave_cert && slave_prikey == other.slave_prikey && cuk == other.cuk && // after v1.0.71 endpoints == other.endpoints && // after v1.0.71 ctlendpoints == other.ctlendpoints && // after v1.0.71 forward_peers == other.forward_peers && // after v1.0.71 reverse_peers == other.reverse_peers && // after v1.0.71 custom_seed == other.custom_seed ) // after v1.0.71 { return true; } return false; } struct chm_node_cfg_info& operator=(const struct chm_node_cfg_info& other) { name = other.name; port = other.port; ctlport = other.ctlport; is_ssl = other.is_ssl; verify_peer = other.verify_peer; is_ca_file = other.is_ca_file; capath = other.capath; server_cert = other.server_cert; server_prikey = other.server_prikey; slave_cert = other.slave_cert; slave_prikey = other.slave_prikey; cuk = other.cuk; // after v1.0.71 endpoints = other.endpoints; // after v1.0.71 ctlendpoints = other.ctlendpoints; // after v1.0.71 forward_peers = other.forward_peers; // after v1.0.71 reverse_peers = other.reverse_peers; // after v1.0.71 custom_seed = other.custom_seed; // after v1.0.71 return *this; } bool operator==(const struct chm_node_cfg_info& other) const { return compare(other); } bool operator!=(const struct chm_node_cfg_info& other) const { return !compare(other); } }CHMNODE_CFGINFO, *PCHMNODE_CFGINFO; typedef std::list<CHMNODE_CFGINFO> chmnode_cfginfos_t; struct chm_node_cfg_info_sort { bool operator()(const CHMNODE_CFGINFO& lchmnodecfginfo, const CHMNODE_CFGINFO& rchmnodecfginfo) const { if(lchmnodecfginfo.name == rchmnodecfginfo.name){ if(lchmnodecfginfo.port == rchmnodecfginfo.port){ if(lchmnodecfginfo.ctlport == rchmnodecfginfo.ctlport){ return lchmnodecfginfo.cuk < rchmnodecfginfo.cuk; }else{ return lchmnodecfginfo.ctlport < rchmnodecfginfo.ctlport; } }else{ return lchmnodecfginfo.port < rchmnodecfginfo.port; } }else{ return lchmnodecfginfo.name < rchmnodecfginfo.name; } } }; struct chm_node_cfg_info_same_name { bool operator()(const CHMNODE_CFGINFO& lchmnodecfginfo, const CHMNODE_CFGINFO& rchmnodecfginfo) const { return lchmnodecfginfo.name == rchmnodecfginfo.name; } }; struct chm_node_cfg_info_same_name_other { bool operator()(const CHMNODE_CFGINFO& lchmnodecfginfo, const CHMNODE_CFGINFO& rchmnodecfginfo) const { return (lchmnodecfginfo.name == rchmnodecfginfo.name && lchmnodecfginfo.ctlport == rchmnodecfginfo.ctlport && lchmnodecfginfo.cuk == rchmnodecfginfo.cuk); } }; struct chm_node_cfg_info_same_eps { bool operator()(const CHMNODE_CFGINFO& lchmnodecfginfo, const CHMNODE_CFGINFO& rchmnodecfginfo) const { return (lchmnodecfginfo.endpoints == rchmnodecfginfo.endpoints && lchmnodecfginfo.ctlendpoints == rchmnodecfginfo.ctlendpoints); } }; struct chm_node_cfg_info_same_eps_peers { bool operator()(const CHMNODE_CFGINFO& lchmnodecfginfo, const CHMNODE_CFGINFO& rchmnodecfginfo) const { return (lchmnodecfginfo.endpoints == rchmnodecfginfo.endpoints && lchmnodecfginfo.ctlendpoints == rchmnodecfginfo.ctlendpoints && lchmnodecfginfo.forward_peers == rchmnodecfginfo.forward_peers && lchmnodecfginfo.reverse_peers == rchmnodecfginfo.reverse_peers); } }; // // configuration information for all // typedef struct chm_cfg_info{ std::string groupname; long revision; bool is_server_mode; bool is_random_mode; short self_ctlport; std::string self_cuk; // after v1.0.71 CHMPXID_SEED_TYPE chmpxid_type; // after v1.0.71 long max_chmpx_count; long replica_count; long max_server_mq_cnt; // MQ count for server/slave node long max_client_mq_cnt; // MQ count for client process long mqcnt_per_attach; // MQ count at each attaching from each client process long max_q_per_servermq; // Queue count in one MQ on server/slave node long max_q_per_clientmq; // Queue count in one MQ on client process long max_mq_per_client; // max MQ count for one client process long max_histlog_count; int retrycnt; int mq_retrycnt; bool mq_ack; int timeout_wait_socket; int timeout_wait_connect; int timeout_wait_mq; bool is_auto_merge; bool is_do_merge; time_t timeout_merge; int sock_thread_cnt; int mq_thread_cnt; int max_sock_pool; time_t sock_pool_timeout; bool k2h_fullmap; int k2h_mask_bitcnt; int k2h_cmask_bitcnt; int k2h_max_element; time_t date; chmss_ver_t ssl_min_ver; // SSL/TLS minimum version std::string nssdb_dir; // NSSDB directory path like "SSL_DIR" environment for NSS chmnode_cfginfos_t servers; chmnode_cfginfos_t slaves; chm_cfg_info() : groupname(""), revision(UNINITIALIZE_REVISION), is_server_mode(false), is_random_mode(false), self_ctlport(CHM_INVALID_PORT), self_cuk(""), // after v1.0.71 chmpxid_type(CHMPXID_SEED_NAME), max_chmpx_count(0L), replica_count(0L), max_server_mq_cnt(0L), max_client_mq_cnt(0L), mqcnt_per_attach(0L), max_q_per_servermq(0L), max_q_per_clientmq(0L), max_mq_per_client(0L), max_histlog_count(0L), retrycnt(-1), mq_retrycnt(-1), mq_ack(true), timeout_wait_socket(-1), timeout_wait_connect(-1), timeout_wait_mq(-1), is_auto_merge(false), is_do_merge(false), timeout_merge(0), sock_thread_cnt(0), mq_thread_cnt(0), max_sock_pool(1), sock_pool_timeout(0), k2h_fullmap(true), k2h_mask_bitcnt(K2HShm::DEFAULT_MASK_BITCOUNT), k2h_cmask_bitcnt(K2HShm::DEFAULT_COLLISION_MASK_BITCOUNT), k2h_max_element(K2HShm::DEFAULT_MAX_ELEMENT_CNT), date(0L), ssl_min_ver(CHM_SSLTLS_VER_DEFAULT), nssdb_dir("") {} explicit chm_cfg_info(const struct chm_cfg_info& other) : groupname(other.groupname), revision(other.revision), is_server_mode(other.is_server_mode), is_random_mode(other.is_random_mode), self_ctlport(other.self_ctlport), self_cuk(other.self_cuk), // after v1.0.71 chmpxid_type(other.chmpxid_type), // after v1.0.71 max_chmpx_count(other.max_chmpx_count), replica_count(other.replica_count), max_server_mq_cnt(other.max_server_mq_cnt), max_client_mq_cnt(other.max_client_mq_cnt), mqcnt_per_attach(other.mqcnt_per_attach), max_q_per_servermq(other.max_q_per_servermq), max_q_per_clientmq(other.max_q_per_clientmq), max_mq_per_client(other.max_mq_per_client), max_histlog_count(other.max_histlog_count), retrycnt(other.retrycnt), mq_retrycnt(other.mq_retrycnt), mq_ack(other.mq_ack), timeout_wait_socket(other.timeout_wait_socket), timeout_wait_connect(other.timeout_wait_connect), timeout_wait_mq(other.timeout_wait_mq), is_auto_merge(other.is_auto_merge), is_do_merge(other.is_do_merge), timeout_merge(other.timeout_merge), sock_thread_cnt(other.sock_thread_cnt), mq_thread_cnt(other.mq_thread_cnt), max_sock_pool(other.max_sock_pool), sock_pool_timeout(other.sock_pool_timeout), k2h_fullmap(other.k2h_fullmap), k2h_mask_bitcnt(other.k2h_mask_bitcnt), k2h_cmask_bitcnt(other.k2h_cmask_bitcnt), k2h_max_element(other.k2h_max_element), date(other.date), ssl_min_ver(other.ssl_min_ver), nssdb_dir(other.nssdb_dir) { chmnode_cfginfos_t::const_iterator iter; for(iter = other.servers.begin(); other.servers.end() != iter; ++iter){ servers.push_back(*iter); } for(iter = other.slaves.begin(); other.slaves.end() != iter; ++iter){ slaves.push_back(*iter); } } bool compare(const struct chm_cfg_info& other) const { if( groupname == other.groupname && revision == other.revision && is_server_mode == other.is_server_mode && is_random_mode == other.is_random_mode && self_ctlport == other.self_ctlport && chmpxid_type == other.chmpxid_type && // after v1.0.71 max_chmpx_count == other.max_chmpx_count && replica_count == other.replica_count && max_server_mq_cnt == other.max_server_mq_cnt && max_client_mq_cnt == other.max_client_mq_cnt && mqcnt_per_attach == other.mqcnt_per_attach && max_q_per_servermq == other.max_q_per_servermq && max_q_per_clientmq == other.max_q_per_clientmq && max_mq_per_client == other.max_mq_per_client && max_histlog_count == other.max_histlog_count && retrycnt == other.retrycnt && mq_retrycnt == other.mq_retrycnt && mq_ack == other.mq_ack && timeout_wait_socket == other.timeout_wait_socket && timeout_wait_connect== other.timeout_wait_connect && timeout_wait_mq == other.timeout_wait_mq && is_auto_merge == other.is_auto_merge && is_do_merge == other.is_do_merge && timeout_merge == other.timeout_merge && sock_thread_cnt == other.sock_thread_cnt && mq_thread_cnt == other.mq_thread_cnt && max_sock_pool == other.max_sock_pool && sock_pool_timeout == other.sock_pool_timeout && //k2h_fullmap == other.k2h_fullmap && // [NOTICE] k2hash parameter is not compared //k2h_mask_bitcnt == other.k2h_mask_bitcnt && //k2h_cmask_bitcnt == other.k2h_cmask_bitcnt && //k2h_max_element == other.k2h_max_element && //date == other.date && // [NOTICE] date is not compared ssl_min_ver == other.ssl_min_ver && nssdb_dir == other.nssdb_dir && servers == other.servers && slaves == other.slaves ) { return true; } return false; } struct chm_cfg_info& operator=(const struct chm_cfg_info& other) { groupname = other.groupname; revision = other.revision; is_server_mode = other.is_server_mode; is_random_mode = other.is_random_mode; self_ctlport = other.self_ctlport; self_cuk = other.self_cuk; chmpxid_type = other.chmpxid_type; max_chmpx_count = other.max_chmpx_count; replica_count = other.replica_count; max_server_mq_cnt = other.max_server_mq_cnt; max_client_mq_cnt = other.max_client_mq_cnt; mqcnt_per_attach = other.mqcnt_per_attach; max_q_per_servermq = other.max_q_per_servermq; max_q_per_clientmq = other.max_q_per_clientmq; max_mq_per_client = other.max_mq_per_client; max_histlog_count = other.max_histlog_count; retrycnt = other.retrycnt; mq_retrycnt = other.mq_retrycnt; mq_ack = other.mq_ack; timeout_wait_socket = other.timeout_wait_socket; timeout_wait_connect = other.timeout_wait_connect; timeout_wait_mq = other.timeout_wait_mq; is_auto_merge = other.is_auto_merge; is_do_merge = other.is_do_merge; timeout_merge = other.timeout_merge; sock_thread_cnt = other.sock_thread_cnt; mq_thread_cnt = other.mq_thread_cnt; max_sock_pool = other.max_sock_pool; sock_pool_timeout = other.sock_pool_timeout; k2h_fullmap = other.k2h_fullmap; k2h_mask_bitcnt = other.k2h_mask_bitcnt; k2h_cmask_bitcnt = other.k2h_cmask_bitcnt; k2h_max_element = other.k2h_max_element; date = other.date; ssl_min_ver = other.ssl_min_ver; nssdb_dir = other.nssdb_dir; chmnode_cfginfos_t::const_iterator iter; for(iter = other.servers.begin(); other.servers.end() != iter; ++iter){ servers.push_back(*iter); } for(iter = other.slaves.begin(); other.slaves.end() != iter; ++iter){ slaves.push_back(*iter); } return *this; } bool operator==(const struct chm_cfg_info& other) const { return compare(other); } bool operator!=(const struct chm_cfg_info& other) const { return !compare(other); } }CHMCFGINFO, *PCHMCFGINFO; // raw all configuration typedef struct cfg_raw{ strmap_t global; strmaparr_t server_nodes; strmaparr_t slave_nodes; }CFGRAW, *PCFGRAW; // For using temporary carry common values for loading // typedef struct chm_conf_common_carry_value{ short port; short ctlport; bool server_mode; bool is_ssl; bool verify_peer; bool is_ca_file; std::string capath; std::string server_cert; std::string server_prikey; std::string slave_cert; std::string slave_prikey; bool server_mode_by_comp; // for check server/slave mode by checking control port and cuk and server name. bool found_ssl; bool found_ssl_verify_peer; chm_conf_common_carry_value() : port(CHM_INVALID_PORT), ctlport(CHM_INVALID_PORT), server_mode(false), is_ssl(false), verify_peer(false), is_ca_file(false), capath(""), server_cert(""), server_prikey(""), slave_cert(""), slave_prikey(""), server_mode_by_comp(false), found_ssl(false), found_ssl_verify_peer(false) {} }CHMCONF_CCV, *PCHMCONF_CCV; //--------------------------------------------------------- // Class CHMConf //--------------------------------------------------------- class CHMConf : public ChmEventBase { public: enum ConfType{ CONF_UNKNOWN = 0, CONF_INI, CONF_JSON, CONF_JSON_STR, // JSON string type(not file), On this case, this class does not use inotify. CONF_YAML }; protected: static int lockval; // like mutex std::string cfgfile; std::string strjson; short ctlport_param; std::string cuk_param; CHMConf::ConfType type; int inotifyfd; int watchfd; PCHMCFGINFO pchmcfginfo; protected: CHMConf(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL, const char* file = NULL, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL, const char* pJson = NULL); virtual bool LoadConfiguration(CHMCFGINFO& chmcfginfo) const = 0; const CHMCFGINFO* GetConfiguration(bool is_check_update = false); // thread unsafe bool RawCheckContainsNodeInfoList(const char* hostname, const short* pctlport, const char* cuk, bool with_forward, chmnode_cfginfos_t* pnodeinfos, strlst_t* pnormnames, bool is_server, bool is_check_update = false); bool CheckContainsServerInfoList(const char* hostname, chmnode_cfginfos_t* pnodeinfos, strlst_t* pnormnames, bool is_check_update = false); bool CheckContainsSlaveInfoList(const char* hostname, chmnode_cfginfos_t* pnodeinfos, strlst_t* pnormnames, bool is_check_update = false); bool RawCheckContainsNodeInfo(const char* hostname, const CHMNODE_CFGINFO& nodeinfos, std::string& normalizedname, bool is_server, bool with_forward); bool GetServerInfo(const char* hostname, short ctlport, const char* cuk, CHMNODE_CFGINFO& svrnodeinfo, std::string& normalizedname, bool is_check_update = false); bool GetSelfServerInfo(CHMNODE_CFGINFO& svrnodeinfo, std::string& normalizedname, bool is_check_update = false); bool GetSlaveInfo(const char* hostname, short ctlport, const char* cuk, CHMNODE_CFGINFO& slvnodeinfo, std::string& normalizedname, bool is_check_update = false); bool GetSelfSlaveInfo(CHMNODE_CFGINFO& slvnodeinfo, std::string& normalizedname, bool is_check_update = false); bool GetSelfReversePeer(hostport_list_t& reverse_peers, bool& is_server); bool IsWatching(void) const { return (CHM_INVALID_HANDLE != watchfd); } uint CheckNotifyEvent(void); bool ResetEventQueue(void); bool IsFileType(void) const { return (CONF_INI == type || CONF_YAML == type || CONF_JSON == type); } bool IsJsonStringType(void) const { return (CONF_JSON_STR == type); } public: static CHMConf* GetCHMConf(int eventqfd, ChmCntrl* pcntrl, const char* config, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL, bool is_check_env = true, std::string* normalize_config = NULL); // Class Factory static std::string GetChmpxidTypeString(CHMPXID_SEED_TYPE type); static std::string GetSslVersionString(chmss_ver_t version); virtual ~CHMConf(); virtual bool Clean(void); virtual bool GetEventQueueFds(event_fds_t& fds); virtual bool SetEventQueue(void); virtual bool UnsetEventQueue(void); virtual bool IsEventQueueFd(int fd); virtual bool Send(PCOMPKT pComPkt, const unsigned char* pbody, size_t blength); virtual bool Receive(int fd); virtual bool NotifyHup(int fd); virtual bool Processing(PCOMPKT pComPkt); bool CheckConfFile(void) const; bool CheckUpdate(void); bool GetConfiguration(CHMCFGINFO& config, bool is_check_update = false); bool CheckContainsNodeInfoList(const char* hostname, chmnode_cfginfos_t* pnodeinfos, strlst_t* pnormnames, bool is_check_update = false); bool GetNodeInfo(const char* hostname, short ctlport, const char* cuk, CHMNODE_CFGINFO& nodeinfo, std::string& normalizedname, bool is_only_server, bool is_check_update = false); bool GetSelfNodeInfo(CHMNODE_CFGINFO& nodeinfo, std::string& normalizedname, bool is_check_update = false); bool IsSelfReversePeer(const char* hostname); bool SearchContainsNodeInfoList(short ctlport, const char* cuk, CHMNODE_CFGINFO& nodeinfo, std::string& normalizedname, bool is_server, bool is_check_update = false); bool GetServerList(strlst_t& server_list); bool IsServerList(const char* hostname, std::string& fqdn); bool IsServerList(std::string& fqdn); bool GetSlaveList(strlst_t& slave_list); bool IsSlaveList(const char* hostname, std::string& fqdn); bool IsSlaveList(std::string& fqdn); bool IsSsl(void) const; }; //--------------------------------------------------------- // Class CHMIniConf //--------------------------------------------------------- class CHMIniConf : public CHMConf { friend class CHMConf; protected: CHMIniConf(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL, const char* file = NULL, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL); virtual bool LoadConfiguration(CHMCFGINFO& chmcfginfo) const; bool LoadConfigurationRaw(CFGRAW& chmcfgraw) const; bool ReadFileContents(const std::string& filename, strlst_t& linelst, strlst_t& allfiles) const; public: virtual ~CHMIniConf(); }; //--------------------------------------------------------- // Class CHMYamlBaseConf //--------------------------------------------------------- class CHMYamlBaseConf : public CHMConf { friend class CHMConf; protected: CHMYamlBaseConf(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL, const char* file = NULL, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL, const char* pJson = NULL); virtual bool LoadConfiguration(CHMCFGINFO& chmcfginfo) const; public: virtual ~CHMYamlBaseConf(); }; //--------------------------------------------------------- // Class CHMJsonConf //--------------------------------------------------------- class CHMJsonConf : public CHMYamlBaseConf { friend class CHMConf; protected: CHMJsonConf(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL, const char* file = NULL, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL); public: virtual ~CHMJsonConf(); }; //--------------------------------------------------------- // Class CHMJsonStringConf //--------------------------------------------------------- class CHMJsonStringConf : public CHMYamlBaseConf { friend class CHMConf; protected: CHMJsonStringConf(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL, const char* pJson = NULL, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL); public: virtual ~CHMJsonStringConf(); }; //--------------------------------------------------------- // Class CHMYamlConf //--------------------------------------------------------- class CHMYamlConf : public CHMYamlBaseConf { friend class CHMConf; protected: CHMYamlConf(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL, const char* file = NULL, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL); public: virtual ~CHMYamlConf(); }; #endif // CHMCONF_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmdbg.h
<reponame>ggtakec/chmpx /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMDBG_H #define CHMDBG_H #include "chmcommon.h" DECL_EXTERN_C_START //--------------------------------------------------------- // Debug //--------------------------------------------------------- typedef enum chm_dbg_mode{ CHMDBG_SILENT = 0, CHMDBG_ERR = 1, CHMDBG_WARN = 3, CHMDBG_MSG = 7, CHMDBG_DUMP = 15 }ChmDbgMode; extern ChmDbgMode chm_debug_mode; // Do not use directly this variable. extern FILE* chm_dbg_fp; ChmDbgMode SetChmDbgMode(ChmDbgMode mode); ChmDbgMode BumpupChmDbgMode(void); ChmDbgMode GetChmDbgMode(void); bool LoadChmDbgEnv(void); bool SetChmDbgFile(const char* filepath); bool UnsetChmDbgFile(void); //--------------------------------------------------------- // Debugging Macros //--------------------------------------------------------- #define ChmDbgMode_STR(mode) CHMDBG_SILENT == mode ? "SLT" : \ CHMDBG_ERR == mode ? "ERR" : \ CHMDBG_WARN == mode ? "WAN" : \ CHMDBG_MSG == mode ? "MSG" : \ CHMDBG_DUMP == mode ? "DMP" : "" #define LOW_CHMPRINT(mode, fmt, ...) \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), "[CHMPX-%s] %s(%d) : " fmt "%s\n", ChmDbgMode_STR(mode), __func__, __LINE__, __VA_ARGS__); #define CHMPRINT(mode, ...) \ if((chm_debug_mode & mode) == mode){ \ LOW_CHMPRINT(mode, __VA_ARGS__); \ } #define SLT_CHMPRN(...) CHMPRINT(CHMDBG_SILENT, ##__VA_ARGS__, "") // This means nothing... #define ERR_CHMPRN(...) CHMPRINT(CHMDBG_ERR, ##__VA_ARGS__, "") #define WAN_CHMPRN(...) CHMPRINT(CHMDBG_WARN, ##__VA_ARGS__, "") #define MSG_CHMPRN(...) CHMPRINT(CHMDBG_MSG, ##__VA_ARGS__, "") #define DMP_CHMPRN(...) CHMPRINT(CHMDBG_DUMP, ##__VA_ARGS__, "") // // If using following macro, need to specify include time.h. // #define CLOCKTIME_CHMPRN(phead) \ if((chm_debug_mode & CHMDBG_DUMP) == CHMDBG_DUMP){ \ struct timespec reqtime; \ if(-1 == clock_gettime(CLOCK_REALTIME_COARSE, &reqtime)){ \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), "[CHMPX-TIME-%s] ---s ---ms ---us ---ns\n", (phead ? phead : "DBG")); \ }else{ \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), "[CHMPX-TIME-%s] %03jds %03ldms %03ldus %03ldns\n", (phead ? phead : "DBG"), static_cast<intmax_t>(reqtime.tv_sec), (reqtime.tv_nsec / (1000 * 1000)), ((reqtime.tv_nsec % (1000 * 1000)) / 1000), (reqtime.tv_nsec % 1000)); \ } \ } DECL_EXTERN_C_END #endif // CHMDBG_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmcomstructure.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMCOMSTRUCTURE_H #define CHMCOMSTRUCTURE_H #include "chmcommon.h" #include "chmstructure.h" #include "chmdbg.h" //--------------------------------------------------------- // Symbols //--------------------------------------------------------- #define MAX_K2HASH_MQ_KEY_LENGTH 128 // (uint64_t(32) + '-' + uint64_t(32) + '-' + uint64_t(32) + suffix(5) + null) + some bytes. #define MQ_PRIORITY_NOTICE 10 // COM_PX2C, COM_C2PX #define MQ_PRIORITY_MSG 10 // COM_C2C // // The two higher bits in serial number is for the ACK on MQ. // #define MQ_ACK_TYPE_MASK (static_cast<serial_t>(0x80000000) & MASK64_LOWBIT) #define MQ_ACK_CODE_MASK (static_cast<serial_t>(0x40000000) & MASK64_LOWBIT) #define MQ_ACK_MASK (MQ_ACK_TYPE_MASK | MQ_ACK_CODE_MASK) #define MQ_ACK_SUCCESS (MQ_ACK_TYPE_MASK) #define MQ_ACK_FAILURE (MQ_ACK_TYPE_MASK | MQ_ACK_CODE_MASK) #define MIN_MQ_SERIAL_NUMBER (0L) #define MAX_MQ_SERIAL_NUMBER (static_cast<serial_t>(0x3FFFFFFF) & MASK64_LOWBIT) #define IS_MQ_ACK(val) (MQ_ACK_TYPE_MASK == (((val) & MASK64_LOWBIT) & MQ_ACK_TYPE_MASK)) #define IS_MQ_ACK_SUCCESS(val) (MQ_ACK_SUCCESS == (((val) & MASK64_LOWBIT) & MQ_ACK_MASK)) #define IS_MQ_ACK_FAILURE(val) (MQ_ACK_FAILURE == (((val) & MASK64_LOWBIT) & MQ_ACK_MASK)) #define GET_MQ_SERIAL_NUMBER(val) (((val) & MASK64_LOWBIT) & ~MQ_ACK_MASK) //--------------------------------------------------------- // Common structure //--------------------------------------------------------- typedef struct chmpx_common_merge_param{ chmpxid_t chmpxid; // requester chmpx struct timespec startts; // start time for update datas chmhash_t max_pending_hash; // max pending hash value chmhash_t pending_hash; // new(pending) hash value chmhash_t max_base_hash; // max base hash value chmhash_t base_hash; // base hash value long replica_count; // replica count bool is_expire_check; // whether checking expire time }CHMPX_ATTR_PACKED PXCOMMON_MERGE_PARAM, *PPXCOMMON_MERGE_PARAM; #define COPY_COMMON_MERGE_PARAM(pdest, psrc) \ { \ (pdest)->chmpxid = (psrc)->chmpxid; \ (pdest)->startts.tv_sec = (psrc)->startts.tv_sec; \ (pdest)->startts.tv_nsec = (psrc)->startts.tv_nsec; \ (pdest)->max_pending_hash = (psrc)->max_pending_hash; \ (pdest)->pending_hash = (psrc)->pending_hash; \ (pdest)->max_base_hash = (psrc)->max_base_hash; \ (pdest)->base_hash = (psrc)->base_hash; \ (pdest)->replica_count = (psrc)->replica_count; \ (pdest)->is_expire_check = (psrc)->is_expire_check; \ } //--------------------------------------------------------- // COM_C2C: Communication Packets //--------------------------------------------------------- // This type does not have structure. so data is binary. // //--------------------------------------------------------- // COM_C2PX, COM_PX2C: Communication Packets //--------------------------------------------------------- // These packets are used for communicating on MQ. // So do not change bit order. // typedef uint64_t pxclttype_t; // type for packet typedef uint64_t reqidmapflag_t; // flag type for request update status for each chmpxid // Type for COM_C2PX, COM_PX2C #define CHMPX_CLT_UNKNOWN 0 // Unknown #define CHMPX_CLT_CLOSE_NOTIFY 1 // Notification of closing MQ #define CHMPX_CLT_JOIN_NOTIFY 2 // Notification of joining MQ from client to chmpx #define CHMPX_CLT_MERGE_GETLASTTS 3 // Command for getting lastest update time(chmpx server node to server client) #define CHMPX_CLT_MERGE_RESLASTTS 4 // Response for getting lastest update time(server client to chmpx server node) #define CHMPX_CLT_REQ_UPDATEDATA 5 // Command for request update datas(chmpx server node to server client) #define CHMPX_CLT_RES_UPDATEDATA 6 // Response for request update datas(server client to chmpx server node) #define CHMPX_CLT_SET_UPDATEDATA 7 // Command for set update datas(chmpx server node to server client) #define CHMPX_CLT_RESULT_UPDATEDATA 8 // Response for result of update data(server client to chmpx server node) #define CHMPX_CLT_ABORT_UPDATEDATA 9 // Command for abort update data(chmpx server node to server client) #define STRPXCLTTYPE(type) ( CHMPX_CLT_UNKNOWN == type ? "CHMPX_CLT_UNKNOWN" : \ CHMPX_CLT_CLOSE_NOTIFY == type ? "CHMPX_CLT_CLOSE_NOTIFY" : \ CHMPX_CLT_JOIN_NOTIFY == type ? "CHMPX_CLT_JOIN_NOTIFY" : \ CHMPX_CLT_MERGE_GETLASTTS == type ? "CHMPX_CLT_MERGE_GETLASTTS" : \ CHMPX_CLT_MERGE_RESLASTTS == type ? "CHMPX_CLT_MERGE_RESLASTTS" : \ CHMPX_CLT_REQ_UPDATEDATA == type ? "CHMPX_CLT_REQ_UPDATEDATA" : \ CHMPX_CLT_RES_UPDATEDATA == type ? "CHMPX_CLT_RES_UPDATEDATA" : \ CHMPX_CLT_SET_UPDATEDATA == type ? "CHMPX_CLT_SET_UPDATEDATA" : \ CHMPX_CLT_RESULT_UPDATEDATA == type ? "CHMPX_CLT_RESULT_UPDATEDATA" : \ CHMPX_CLT_ABORT_UPDATEDATA == type ? "CHMPX_CLT_ABORT_UPDATEDATA" : \ "NOT_DEFINED_TYPE" ) //------------------------------- // Structures // typedef struct chmpx_client_head{ pxclttype_t type; // Command type size_t length; // Length for this packet }CHMPX_ATTR_PACKED PXCLT_HEAD, *PPXCLT_HEAD; typedef struct chmpx_client_close_notify{ PXCLT_HEAD head; long count; msgid_t* pmsgids; // out of this structure area. }CHMPX_ATTR_PACKED PXCLT_CLOSE_NOTIFY, *PPXCLT_CLOSE_NOTIFY; typedef struct chmpx_client_join_notify{ PXCLT_HEAD head; pid_t pid; // client pid }CHMPX_ATTR_PACKED PXCLT_JOIN_NOTIFY, *PPXCLT_JOIN_NOTIFY; typedef struct chmpx_client_merge_getlastts{ PXCLT_HEAD head; }CHMPX_ATTR_PACKED PXCLT_MERGE_GETLASTTS, *PPXCLT_MERGE_GETLASTTS; typedef struct chmpx_client_merge_reslastts{ PXCLT_HEAD head; struct timespec lastupdatets; // using by only response }CHMPX_ATTR_PACKED PXCLT_MERGE_RESLASTTS, *PPXCLT_MERGE_RESLASTTS; typedef struct chmpx_client_req_updatedata{ PXCLT_HEAD head; PXCOMMON_MERGE_PARAM merge_param; }CHMPX_ATTR_PACKED PXCLT_REQ_UPDATEDATA, *PPXCLT_REQ_UPDATEDATA; typedef struct chmpx_client_res_updatedata{ PXCLT_HEAD head; chmpxid_t chmpxid; // requester chmpx struct timespec ts; // updated time is also in this time at least size_t length; unsigned char* byptr; // out of this structure area. }CHMPX_ATTR_PACKED PXCLT_RES_UPDATEDATA, *PPXCLT_RES_UPDATEDATA; typedef struct chmpx_client_set_updatedata{ PXCLT_HEAD head; struct timespec ts; // updated time is also in this time at least size_t length; unsigned char* byptr; // out of this structure area. }CHMPX_ATTR_PACKED PXCLT_SET_UPDATEDATA, *PPXCLT_SET_UPDATEDATA; typedef struct chmpx_client_result_updatedata{ PXCLT_HEAD head; chmpxid_t chmpxid; reqidmapflag_t result; // result }CHMPX_ATTR_PACKED PXCLT_RESULT_UPDATEDATA, *PPXCLT_RESULT_UPDATEDATA; typedef struct chmpx_client_abort_updatedata{ PXCLT_HEAD head; }CHMPX_ATTR_PACKED PXCLT_ABORT_UPDATEDATA, *PPXCLT_ABORT_UPDATEDATA; typedef union chmpx_clt_all{ PXCLT_HEAD val_head; PXCLT_CLOSE_NOTIFY val_close_notify; PXCLT_JOIN_NOTIFY val_join_notify; PXCLT_MERGE_GETLASTTS val_merge_getlastts; PXCLT_MERGE_RESLASTTS val_merge_reslastts; PXCLT_REQ_UPDATEDATA val_req_updatedata; PXCLT_RES_UPDATEDATA val_res_updatedata; PXCLT_SET_UPDATEDATA val_set_updatedata; PXCLT_RESULT_UPDATEDATA val_result_updatedata; PXCLT_ABORT_UPDATEDATA val_abort_updatedata; }CHMPX_ATTR_PACKED PXCLT_ALL, *PPXCLT_ALL; //------------ // Utility Macros //------------ #define CVT_CLTPTR_CLOSE_NOTIFY(pCltAll) &((pCltAll)->val_close_notify) #define CVT_CLTPTR_JOIN_NOTIFY(pCltAll) &((pCltAll)->val_join_notify) #define CVT_CLTPTR_MERGE_GETLASTTS(pCltAll) &((pCltAll)->val_merge_getlastts) #define CVT_CLTPTR_MERGE_RESLASTTS(pCltAll) &((pCltAll)->val_merge_reslastts) #define CVT_CLTPTR_REQ_UPDATEDATA(pCltAll) &((pCltAll)->val_req_updatedata) #define CVT_CLTPTR_RES_UPDATEDATA(pCltAll) &((pCltAll)->val_res_updatedata) #define CVT_CLTPTR_SET_UPDATEDATA(pCltAll) &((pCltAll)->val_set_updatedata) #define CVT_CLTPTR_RESULT_UPDATEDATA(pCltAll) &((pCltAll)->val_result_updatedata) #define CVT_CLTPTR_ABORT_UPDATEDATA(pCltAll) &((pCltAll)->val_abort_updatedata) #define CVT_CLT_ALL_PTR_PXCOMPKT(pComPkt) ( CHM_OFFSET((pComPkt), sizeof(COMPKT), PPXCLT_ALL) ) #define SIZEOF_CHMPX_CLT(type) ( CHMPX_CLT_CLOSE_NOTIFY == type ? sizeof(PXCLT_CLOSE_NOTIFY) : \ CHMPX_CLT_JOIN_NOTIFY == type ? sizeof(PXCLT_JOIN_NOTIFY) : \ CHMPX_CLT_MERGE_GETLASTTS == type ? sizeof(PXCLT_MERGE_GETLASTTS) : \ CHMPX_CLT_MERGE_RESLASTTS == type ? sizeof(PXCLT_MERGE_RESLASTTS) : \ CHMPX_CLT_REQ_UPDATEDATA == type ? sizeof(PXCLT_REQ_UPDATEDATA) : \ CHMPX_CLT_RES_UPDATEDATA == type ? sizeof(PXCLT_RES_UPDATEDATA) : \ CHMPX_CLT_SET_UPDATEDATA == type ? sizeof(PXCLT_SET_UPDATEDATA) : \ CHMPX_CLT_RESULT_UPDATEDATA == type ? sizeof(PXCLT_RESULT_UPDATEDATA) : \ CHMPX_CLT_ABORT_UPDATEDATA == type ? sizeof(PXCLT_ABORT_UPDATEDATA) : \ 0L) #define IS_PXCLT_TYPE(pCltAll, clttype) ( pCltAll && pCltAll->val_head.type == clttype ) #define SET_PXCLTPKT(pComPkt, is_chmpx_proc, clttype, dept_msgid, term_msgid, serial_num, extlength) \ { \ (pComPkt)->length = sizeof(COMPKT) + SIZEOF_CHMPX_CLT(clttype) + extlength; \ (pComPkt)->offset = sizeof(COMPKT); \ (pComPkt)->head.version = COM_VERSION_1; \ (pComPkt)->head.type = is_chmpx_proc ? COM_PX2C : COM_C2PX; \ (pComPkt)->head.c2ctype = COM_C2C_IGNORE; \ (pComPkt)->head.dept_ids.chmpxid= CHM_INVALID_CHMPXID; \ (pComPkt)->head.dept_ids.msgid = dept_msgid; \ (pComPkt)->head.term_ids.chmpxid= CHM_INVALID_CHMPXID; \ (pComPkt)->head.term_ids.msgid = term_msgid; \ (pComPkt)->head.peer_dept_msgid = dept_msgid; \ (pComPkt)->head.peer_term_msgid = term_msgid; \ (pComPkt)->head.mq_serial_num = serial_num; \ (pComPkt)->head.hash = CHM_INVALID_HASHVAL; \ if(!RT_TIMESPEC(&((pComPkt)->head.reqtime))){ \ WAN_CHMPRN("Could not get timespec(errno=%d), but continue...", errno); \ INIT_TIMESPEC(&((pComPkt)->head.reqtime)); \ } \ } //--------------------------------------------------------- // COM_S2PX: Communication Packets //--------------------------------------------------------- typedef struct chmpx_signal_com{ int signalno; }CHMPX_ATTR_PACKED PXSIG_COM, *PPXSIG_COM; //--------------------------------------------------------- // COM_F2PX: Communication Packets //--------------------------------------------------------- typedef struct chmpx_inotify_com{ int wfd; uint32_t mask; }CHMPX_ATTR_PACKED PXFILE_COM, *PPXFILE_COM; //--------------------------------------------------------- // COM_PX2PX: Communication Packets //--------------------------------------------------------- // Following pxcomtype_t is long(64) instead of enum because // PXCOM_HEAD should be alignment for datas after it. // typedef uint64_t pxcomtype_t; // type for packet typedef uint64_t pxcomres_t; // result code for PXCOM_XXX typedef uint64_t comver_t; // Protocol version // [NOTICE] // CHMPX_COM_N2_STATUS_REQ & CHMPX_COM_N2_STATUS_RES is pull-type for status and server information updating. // CHMPX_COM_N2_STATUS_UPDATE is push to all server for updating by sending server's all status. // So CHMPX_COM_N2_STATUS_UPDATE is not used now because of taking very careful(no recovering if failed). // // [NOTE] - [DEPRECATED 1.0.71] // Communication protocols with this mark have been deprecated since v1.0.71. // v1.0.71 or later uses version 2 of the communication protocol.(version 1 is // before v1.0.71.) // CHMPX determines the communication protocol and automatically switches the // version. Set "CHMPX_COM_PROTO_VER=1" to forcibly use communication protocol // version 1. Since the communication protocol version of the server node that // is started first takes precedence, connecting a version 1 node to a version // 2 server node RING may cause problems. // If CHMPX v1.0.71 or earlier is running and you force to use communicate with // version 1, you can set the environment variable "CHMPX_COM_PROTO_VER=1". // If you are using a version of CHMPX that can only use version 1 of the // communication protocol, you must upgrade all CHMPX versions. To upgrade a // mixed version environment safely, first set the environment variable // "CHMPX_COM_PROTO_VER=1" and restart CHMPX. And upgrade all CHMPX. When the // upgrade is complete, restart without environment variables. // (Specify the protocol version in the environment variable CHMPX_COM_PROTO_VER. // Currently, it is "1" before v1.0.71 and "2" after v1.0.71.) // #define CHMPX_COM_UNKNOWN 0 // Unknown #define CHMPX_COM_STATUS_REQ 1 // [DEPRECATED 1.0.71] Get server nodes status -> Use CHMPX_COM_N2_STATUS_REQ #define CHMPX_COM_STATUS_RES 2 // [DEPRECATED 1.0.71] Result(Response) server nodes status -> Use CHMPX_COM_N2_STATUS_RES #define CHMPX_COM_CONINIT_REQ 3 // [DEPRECATED 1.0.71] Send initial connect information -> Use CHMPX_COM_N2_CONINIT_REQ #define CHMPX_COM_CONINIT_RES 4 // [DEPRECATED 1.0.71] Result(Response) initial connect information -> Use CHMPX_COM_N2_CONINIT_RES #define CHMPX_COM_JOIN_RING 5 // [DEPRECATED 1.0.71] [loop in RING] server up & join ring -> Use CHMPX_COM_N2_JOIN_RING #define CHMPX_COM_STATUS_UPDATE 6 // [DEPRECATED 1.0.71] [loop in RING] status update -> Use CHMPX_COM_N2_STATUS_UPDATE #define CHMPX_COM_STATUS_CONFIRM 7 // [DEPRECATED 1.0.71] [loop in RING] status confirm -> Use CHMPX_COM_N2_STATUS_CONFIRM #define CHMPX_COM_STATUS_CHANGE 8 // [DEPRECATED 1.0.71] [loop in RING] status change(notice) -> Use CHMPX_COM_N2_STATUS_CHANGE #define CHMPX_COM_MERGE_START 9 // [loop in RING] start merging #define CHMPX_COM_MERGE_ABORT 10 // [loop in RING] abort merging #define CHMPX_COM_MERGE_COMPLETE 11 // [loop in RING] complete merging #define CHMPX_COM_SERVER_DOWN 12 // [loop in RING] notify server down #define CHMPX_COM_REQ_UPDATEDATA 13 // [loop in RING] request update datas #define CHMPX_COM_RES_UPDATEDATA 14 // Result(Response) request update datas #define CHMPX_COM_RESULT_UPDATEDATA 15 // Result(Response) request update datas #define CHMPX_COM_MERGE_SUSPEND 16 // [loop in RING] suspend auto merging(v1.0.54) #define CHMPX_COM_MERGE_NOSUSPEND 17 // [loop in RING] reset(nosuspend) auto merging(v1.0.54) #define CHMPX_COM_MERGE_SUSPEND_GET 18 // Request suspend merging suspend at initializing(v1.0.57) #define CHMPX_COM_MERGE_SUSPEND_RES 19 // Response suspend merging status at initializing(v1.0.57) #define CHMPX_COM_VERSION_REQ 20 // Get communication protocol version and other version(after v1.0.71) #define CHMPX_COM_VERSION_RES 21 // Result(Response) communication protocol version and other version(after v1.0.71) #define CHMPX_COM_N2_STATUS_REQ 22 // Get server nodes status(after v1.0.71) #define CHMPX_COM_N2_STATUS_RES 23 // Result(Response) server nodes status(after v1.0.71) #define CHMPX_COM_N2_CONINIT_REQ 24 // Send initial connect information(after v1.0.71) #define CHMPX_COM_N2_CONINIT_RES 25 // Result(Response) initial connect information(after v1.0.71) #define CHMPX_COM_N2_JOIN_RING 26 // [loop in RING] server up & join ring(after v1.0.71) #define CHMPX_COM_N2_STATUS_UPDATE 27 // [loop in RING] status update(after v1.0.71) #define CHMPX_COM_N2_STATUS_CONFIRM 28 // [loop in RING] status confirm(after v1.0.71) #define CHMPX_COM_N2_STATUS_CHANGE 29 // [loop in RING] status change/notice(after v1.0.71) // [NOTE] // The STRPXCOMTYPE() macro has been moved to the chmeventsock.cc file. // See comments in chmeventsock.cc for details. // #define CHMPX_COM_RES_SUCCESS 0 // no error #define CHMPX_COM_RES_ERROR 1 // error //------------------------------- // status for each chmpxid in CHMPX_COM_REQ_UPDATEDATA // #define CHMPX_COM_REQ_UPDATE_INIVAL 0 // initial value #define CHMPX_COM_REQ_UPDATE_DO 1 // target can run to update data #define CHMPX_COM_REQ_UPDATE_NOACT 2 // target can not run to update data #define CHMPX_COM_REQ_UPDATE_SUCCESS 3 // succeed to update data #define CHMPX_COM_REQ_UPDATE_FAIL 4 // failed to update data #define IS_PXCOM_REQ_UPDATE_RESULT(res) ((CHMPX_COM_REQ_UPDATE_NOACT == res) || (CHMPX_COM_REQ_UPDATE_SUCCESS == res) || (CHMPX_COM_REQ_UPDATE_FAIL == res)) #define STRPXCOM_REQ_UPDATEDATA(res) ( CHMPX_COM_REQ_UPDATE_INIVAL == res ? "INIVAL" : \ CHMPX_COM_REQ_UPDATE_DO == res ? "DO" : \ CHMPX_COM_REQ_UPDATE_NOACT == res ? "NOACT" : \ CHMPX_COM_REQ_UPDATE_SUCCESS == res ? "SUCCESS" : \ CHMPX_COM_REQ_UPDATE_FAIL == res ? "FAIL" : \ "UNKNOWN" ) //------------------------------- // Structures // typedef struct chmpx_com_head{ pxcomtype_t type; // Command type pxcomres_t result; // Command result size_t length; // Length for this packet }CHMPX_ATTR_PACKED PXCOM_HEAD, *PPXCOM_HEAD; // [DEPRECATED 1.0.71] typedef struct chmpx_com_status_req{ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_STATUS_REQ, *PPXCOM_STATUS_REQ; // [DEPRECATED 1.0.71] typedef struct chmpx_com_status_res{ PXCOM_HEAD head; long count; off_t pchmpxsvr_offset; }CHMPX_ATTR_PACKED PXCOM_STATUS_RES, *PPXCOM_STATUS_RES; // [DEPRECATED 1.0.71] typedef struct chmpx_com_coninit_req{ PXCOM_HEAD head; chmpxid_t chmpxid; short ctlport; }CHMPX_ATTR_PACKED PXCOM_CONINIT_REQ, *PPXCOM_CONINIT_REQ; // [DEPRECATED 1.0.71] typedef struct chmpx_com_coninit_res{ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_CONINIT_RES, *PPXCOM_CONINIT_RES; // [DEPRECATED 1.0.71] typedef struct chmpx_com_join_ring{ PXCOM_HEAD head; CHMPXSVRV1 server; }CHMPX_ATTR_PACKED PXCOM_JOIN_RING, *PPXCOM_JOIN_RING; // [DEPRECATED 1.0.71] typedef struct chmpx_com_status_update{ // same as STATUS_RES PXCOM_HEAD head; long count; off_t pchmpxsvr_offset; }CHMPX_ATTR_PACKED PXCOM_STATUS_UPDATE, *PPXCOM_STATUS_UPDATE; // [DEPRECATED 1.0.71] typedef struct chmpx_com_status_confirm{ // same as STATUS_RES PXCOM_HEAD head; long count; off_t pchmpxsvr_offset; }CHMPX_ATTR_PACKED PXCOM_STATUS_CONFIRM, *PPXCOM_STATUS_CONFIRM; // [DEPRECATED 1.0.71] typedef struct chmpx_com_status_change{ // same as JOIN_RING PXCOM_HEAD head; CHMPXSVRV1 server; }CHMPX_ATTR_PACKED PXCOM_STATUS_CHANGE, *PPXCOM_STATUS_CHANGE; typedef struct chmpx_com_merge_start{ // same as STATUS_REQ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_MERGE_START, *PPXCOM_MERGE_START; typedef struct chmpx_com_merge_abort{ // same as STATUS_REQ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_MERGE_ABORT, *PPXCOM_MERGE_ABORT; typedef struct chmpx_com_merge_complete{ // same as STATUS_REQ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_MERGE_COMPLETE, *PPXCOM_MERGE_COMPLETE; typedef struct chmpx_com_server_down{ PXCOM_HEAD head; chmpxid_t chmpxid; }CHMPX_ATTR_PACKED PXCOM_SERVER_DOWN, *PPXCOM_SERVER_DOWN; typedef struct chmpx_com_req_idmap{ chmpxid_t chmpxid; reqidmapflag_t req_status; }CHMPX_ATTR_PACKED PXCOM_REQ_IDMAP, *PPXCOM_REQ_IDMAP; typedef struct chmpx_com_req_updatedata{ PXCOM_HEAD head; PXCOMMON_MERGE_PARAM merge_param; // common parameter for update data long count; // extended data count off_t plist_offset; // offset for PPXCOM_REQ_IDMAP }CHMPX_ATTR_PACKED PXCOM_REQ_UPDATEDATA, *PPXCOM_REQ_UPDATEDATA; typedef struct chmpx_com_res_updatedata{ PXCOM_HEAD head; struct timespec ts; // updated time is also in this time at least size_t length; off_t pdata_offset; // offset for binary data }CHMPX_ATTR_PACKED PXCOM_RES_UPDATEDATA, *PPXCOM_RES_UPDATEDATA; typedef struct chmpx_com_result_updatedata{ PXCOM_HEAD head; chmpxid_t chmpxid; reqidmapflag_t result; // result }CHMPX_ATTR_PACKED PXCOM_RESULT_UPDATEDATA, *PPXCOM_RESULT_UPDATEDATA; typedef struct chmpx_com_merge_suspend{ // same as STATUS_REQ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_MERGE_SUSPEND, *PPXCOM_MERGE_SUSPEND; typedef struct chmpx_com_merge_nosuspend{ // same as STATUS_REQ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_MERGE_NOSUSPEND, *PPXCOM_MERGE_NOSUSPEND; typedef struct chmpx_com_merge_suspend_get{ // same as STATUS_REQ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_MERGE_SUSPEND_GET, *PPXCOM_MERGE_SUSPEND_GET; typedef struct chmpx_com_merge_suspend_res{ PXCOM_HEAD head; bool is_suspend; }CHMPX_ATTR_PACKED PXCOM_MERGE_SUSPEND_RES, *PPXCOM_MERGE_SUSPEND_RES; typedef struct chmpx_com_version_req{ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_VERSION_REQ, *PPXCOM_VERSION_REQ; typedef struct chmpx_com_version_res{ PXCOM_HEAD head; comver_t chmpx_com_version; // maximum version of communication that chmpx can use comver_t chmpx_cur_version; // communication version used in the current RING uint64_t chmpx_bin_version; // chmpx binary version value char chmpx_str_version[CHMPX_VERSION_MAX]; // chmpx binary version string char commit_hash[COMMIT_HASH_MAX]; // chmpx binary commit hash value }CHMPX_ATTR_PACKED PXCOM_VERSION_RES, *PPXCOM_VERSION_RES; typedef struct chmpx_com_n2_status_req{ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_N2_STATUS_REQ, *PPXCOM_N2_STATUS_REQ; typedef struct chmpx_com_n2_status_res{ PXCOM_HEAD head; long count; off_t pchmpxsvr_offset; }CHMPX_ATTR_PACKED PXCOM_N2_STATUS_RES, *PPXCOM_N2_STATUS_RES; typedef struct chmpx_com_n2_coninit_req{ PXCOM_HEAD head; char name[NI_MAXHOST]; // = 1025 for getnameinfo() chmpxid_t chmpxid; short ctlport; char cuk[CUK_MAX]; char custom_seed[CUSTOM_ID_SEED_MAX]; CHMPXHP_RAWPAIR endpoints[EXTERNAL_EP_MAX]; CHMPXHP_RAWPAIR ctlendpoints[EXTERNAL_EP_MAX]; CHMPXHP_RAWPAIR forward_peers[FORWARD_PEER_MAX]; CHMPXHP_RAWPAIR reverse_peers[REVERSE_PEER_MAX]; }CHMPX_ATTR_PACKED PXCOM_N2_CONINIT_REQ, *PPXCOM_N2_CONINIT_REQ; typedef struct chmpx_com_n2_coninit_res{ PXCOM_HEAD head; }CHMPX_ATTR_PACKED PXCOM_N2_CONINIT_RES, *PPXCOM_N2_CONINIT_RES; typedef struct chmpx_com_n2_join_ring{ PXCOM_HEAD head; CHMPXSVR server; }CHMPX_ATTR_PACKED PXCOM_N2_JOIN_RING, *PPXCOM_N2_JOIN_RING; typedef struct chmpx_com_n2_status_update{ // same as STATUS_RES PXCOM_HEAD head; long count; off_t pchmpxsvr_offset; }CHMPX_ATTR_PACKED PXCOM_N2_STATUS_UPDATE, *PPXCOM_N2_STATUS_UPDATE; typedef struct chmpx_com_n2_status_confirm{ // same as STATUS_RES PXCOM_HEAD head; long count; off_t pchmpxsvr_offset; }CHMPX_ATTR_PACKED PXCOM_N2_STATUS_CONFIRM, *PPXCOM_N2_STATUS_CONFIRM; typedef struct chmpx_com_n2_status_change{ // same as JOIN_RING PXCOM_HEAD head; CHMPXSVR server; }CHMPX_ATTR_PACKED PXCOM_N2_STATUS_CHANGE, *PPXCOM_N2_STATUS_CHANGE; typedef union chmpx_com_all{ PXCOM_HEAD val_head; PXCOM_STATUS_REQ val_status_req; PXCOM_STATUS_RES val_status_res; PXCOM_CONINIT_REQ val_coninit_req; PXCOM_CONINIT_RES val_coninit_res; PXCOM_JOIN_RING val_join_ring; PXCOM_STATUS_UPDATE val_status_update; PXCOM_STATUS_CONFIRM val_status_confirm; PXCOM_STATUS_CHANGE val_status_change; PXCOM_MERGE_START val_merge_start; PXCOM_MERGE_ABORT val_merge_abort; PXCOM_MERGE_COMPLETE val_merge_complete; PXCOM_SERVER_DOWN val_server_down; PXCOM_REQ_UPDATEDATA val_req_updatedata; PXCOM_RES_UPDATEDATA val_res_updatedata; PXCOM_RESULT_UPDATEDATA val_result_updatedata; PXCOM_MERGE_SUSPEND val_merge_suspend; PXCOM_MERGE_NOSUSPEND val_merge_nosuspend; PXCOM_MERGE_SUSPEND_GET val_merge_suspend_get; PXCOM_MERGE_SUSPEND_RES val_merge_suspend_res; PXCOM_VERSION_REQ val_version_req; PXCOM_VERSION_RES val_version_res; PXCOM_N2_STATUS_REQ val_n2_status_req; PXCOM_N2_STATUS_RES val_n2_status_res; PXCOM_N2_CONINIT_REQ val_n2_coninit_req; PXCOM_N2_CONINIT_RES val_n2_coninit_res; PXCOM_N2_JOIN_RING val_n2_join_ring; PXCOM_N2_STATUS_UPDATE val_n2_status_update; PXCOM_N2_STATUS_CONFIRM val_n2_status_confirm; PXCOM_N2_STATUS_CHANGE val_n2_status_change; }CHMPX_ATTR_PACKED PXCOM_ALL, *PPXCOM_ALL; //------------ // Converter //------------ #define HTON_PPXCOM_HEAD(pdata) \ { \ (pdata)->type = htobe64((pdata)->type); \ (pdata)->result = htobe64((pdata)->result); \ (pdata)->length = htobe64((pdata)->length); \ } #define NTOH_PPXCOM_HEAD(pdata) \ { \ (pdata)->type = be64toh((pdata)->type); \ (pdata)->result = be64toh((pdata)->result); \ (pdata)->length = be64toh((pdata)->length); \ } #define HTON_PPXCOM_STATUS_REQ(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_STATUS_REQ(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_STATUS_RES(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = htobe64((pdata)->count); \ (pdata)->pchmpxsvr_offset = htobe64((pdata)->pchmpxsvr_offset); \ } #define NTOH_PPXCOM_STATUS_RES(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = be64toh((pdata)->count); \ (pdata)->pchmpxsvr_offset = be64toh((pdata)->pchmpxsvr_offset); \ } #define HTON_PPXCOM_CONINIT_REQ(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpxid = htobe64((pdata)->chmpxid); \ (pdata)->ctlport = htobe16((pdata)->ctlport); \ } #define NTOH_PPXCOM_CONINIT_REQ(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpxid = be64toh((pdata)->chmpxid); \ (pdata)->ctlport = be16toh((pdata)->ctlport); \ } #define HTON_PPXCOM_CONINIT_RES(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_CONINIT_RES(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_JOIN_RING(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ HTON_PCHMPXSVRV1(&((pdata)->server)); \ } #define NTOH_PPXCOM_JOIN_RING(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ NTOH_PCHMPXSVRV1(&((pdata)->server)); \ } #define HTON_PPXCOM_STATUS_UPDATE(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = htobe64((pdata)->count); \ (pdata)->pchmpxsvr_offset = htobe64((pdata)->pchmpxsvr_offset); \ } #define NTOH_PPXCOM_STATUS_UPDATE(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = be64toh((pdata)->count); \ (pdata)->pchmpxsvr_offset = be64toh((pdata)->pchmpxsvr_offset); \ } #define HTON_PPXCOM_STATUS_CONFIRM(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = htobe64((pdata)->count); \ (pdata)->pchmpxsvr_offset = htobe64((pdata)->pchmpxsvr_offset); \ } #define NTOH_PPXCOM_STATUS_CONFIRM(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = be64toh((pdata)->count); \ (pdata)->pchmpxsvr_offset = be64toh((pdata)->pchmpxsvr_offset); \ } #define HTON_PPXCOM_STATUS_CHANGE(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ HTON_PCHMPXSVRV1(&((pdata)->server)); \ } #define NTOH_PPXCOM_STATUS_CHANGE(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ NTOH_PCHMPXSVRV1(&((pdata)->server)); \ } #define HTON_PPXCOM_MERGE_START(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_MERGE_START(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_MERGE_ABORT(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_MERGE_ABORT(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_MERGE_COMPLETE(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_MERGE_COMPLETE(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_SERVER_DOWN(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpxid = htobe64((pdata)->chmpxid); \ } #define NTOH_PPXCOM_SERVER_DOWN(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpxid = be64toh((pdata)->chmpxid); \ } #define HTON_PPXCOM_REQ_IDMAP(pdata) \ { \ (pdata)->chmpxid = htobe64((pdata)->chmpxid); \ (pdata)->req_status = htobe64((pdata)->req_status); \ } #define NTOH_PPXCOM_REQ_IDMAP(pdata) \ { \ (pdata)->chmpxid = be64toh((pdata)->chmpxid); \ (pdata)->req_status = be64toh((pdata)->req_status); \ } #define HTON_PXCOMMON_MERGE_PARAM(pdata) \ { \ (pdata)->chmpxid = htobe64((pdata)->chmpxid); \ HTON_TIMESPEC(&((pdata)->startts)); \ (pdata)->max_pending_hash = htobe64((pdata)->max_pending_hash); \ (pdata)->pending_hash = htobe64((pdata)->pending_hash); \ (pdata)->max_base_hash = htobe64((pdata)->max_base_hash); \ (pdata)->base_hash = htobe64((pdata)->base_hash); \ (pdata)->replica_count = htobe64((pdata)->replica_count); \ } #define NTOH_PXCOMMON_MERGE_PARAM(pdata) \ { \ (pdata)->chmpxid = be64toh((pdata)->chmpxid); \ NTOH_TIMESPEC(&((pdata)->startts)); \ (pdata)->max_pending_hash = be64toh((pdata)->max_pending_hash); \ (pdata)->pending_hash = be64toh((pdata)->pending_hash); \ (pdata)->max_base_hash = be64toh((pdata)->max_base_hash); \ (pdata)->base_hash = be64toh((pdata)->base_hash); \ (pdata)->replica_count = be64toh((pdata)->replica_count); \ } #define HTON_PPXCOM_REQ_UPDATEDATA(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ HTON_PXCOMMON_MERGE_PARAM(&((pdata)->merge_param)); \ (pdata)->count = htobe64((pdata)->count); \ (pdata)->plist_offset = htobe64((pdata)->plist_offset); \ } #define NTOH_PPXCOM_REQ_UPDATEDATA(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ NTOH_PXCOMMON_MERGE_PARAM(&((pdata)->merge_param)); \ (pdata)->count = be64toh((pdata)->count); \ (pdata)->plist_offset = be64toh((pdata)->plist_offset); \ } #define HTON_PPXCOM_RES_UPDATEDATA(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ HTON_TIMESPEC(&((pdata)->ts)); \ (pdata)->length = htobe64((pdata)->length); \ (pdata)->pdata_offset = htobe64((pdata)->pdata_offset); \ } #define NTOH_PPXCOM_RES_UPDATEDATA(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ NTOH_TIMESPEC(&((pdata)->ts)); \ (pdata)->length = be64toh((pdata)->length); \ (pdata)->pdata_offset = be64toh((pdata)->pdata_offset); \ } #define HTON_PPXCOM_RESULT_UPDATEDATA(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpxid = htobe64((pdata)->chmpxid); \ (pdata)->result = htobe64((pdata)->result); \ } #define NTOH_PPXCOM_RESULT_UPDATEDATA(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpxid = be64toh((pdata)->chmpxid); \ (pdata)->result = be64toh((pdata)->result); \ } #define HTON_PPXCOM_MERGE_SUSPEND(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_MERGE_SUSPEND(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_MERGE_NOSUSPEND(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_MERGE_NOSUSPEND(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_MERGE_SUSPEND_GET(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_MERGE_SUSPEND_GET(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } // is_suspend is bool(8bit) which is not needed to change byte order #define HTON_PPXCOM_MERGE_SUSPEND_RES(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } // is_suspend is bool(8bit) which is not needed to change byte order #define NTOH_PPXCOM_MERGE_SUSPEND_RES(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_VERSION_REQ(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_VERSION_REQ(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_VERSION_RES(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpx_com_version = htobe64((pdata)->chmpx_com_version); \ (pdata)->chmpx_cur_version = htobe64((pdata)->chmpx_cur_version); \ (pdata)->chmpx_bin_version = htobe64((pdata)->chmpx_bin_version); \ } #define NTOH_PPXCOM_VERSION_RES(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpx_com_version = be64toh((pdata)->chmpx_com_version); \ (pdata)->chmpx_cur_version = be64toh((pdata)->chmpx_cur_version); \ (pdata)->chmpx_bin_version = be64toh((pdata)->chmpx_bin_version); \ } #define HTON_PPXCOM_N2_STATUS_REQ(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_N2_STATUS_REQ(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_N2_STATUS_RES(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = htobe64((pdata)->count); \ (pdata)->pchmpxsvr_offset = htobe64((pdata)->pchmpxsvr_offset); \ } #define NTOH_PPXCOM_N2_STATUS_RES(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = be64toh((pdata)->count); \ (pdata)->pchmpxsvr_offset = be64toh((pdata)->pchmpxsvr_offset); \ } #define HTON_PPXCOM_N2_CONINIT_REQ(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpxid = htobe64((pdata)->chmpxid); \ (pdata)->ctlport = htobe16((pdata)->ctlport); \ { \ int _hton_hostport_pair_cnt; \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->endpoints[_hton_hostport_pair_cnt].port = htobe16((pdata)->endpoints[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->ctlendpoints[_hton_hostport_pair_cnt].port = htobe16((pdata)->ctlendpoints[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < FORWARD_PEER_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->forward_peers[_hton_hostport_pair_cnt].port = htobe16((pdata)->forward_peers[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < REVERSE_PEER_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->reverse_peers[_hton_hostport_pair_cnt].port = htobe16((pdata)->reverse_peers[_hton_hostport_pair_cnt].port); \ } \ } \ } #define NTOH_PPXCOM_N2_CONINIT_REQ(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->chmpxid = be64toh((pdata)->chmpxid); \ (pdata)->ctlport = be16toh((pdata)->ctlport); \ { \ int _hton_hostport_pair_cnt; \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->endpoints[_hton_hostport_pair_cnt].port = be64toh((pdata)->endpoints[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < EXTERNAL_EP_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->ctlendpoints[_hton_hostport_pair_cnt].port = be64toh((pdata)->ctlendpoints[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < FORWARD_PEER_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->forward_peers[_hton_hostport_pair_cnt].port = be64toh((pdata)->forward_peers[_hton_hostport_pair_cnt].port); \ } \ for(_hton_hostport_pair_cnt = 0; _hton_hostport_pair_cnt < REVERSE_PEER_MAX; ++_hton_hostport_pair_cnt){ \ (pdata)->reverse_peers[_hton_hostport_pair_cnt].port = be64toh((pdata)->reverse_peers[_hton_hostport_pair_cnt].port); \ } \ } \ } #define HTON_PPXCOM_N2_CONINIT_RES(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ } #define NTOH_PPXCOM_N2_CONINIT_RES(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ } #define HTON_PPXCOM_N2_JOIN_RING(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ HTON_PCHMPXSVR(&((pdata)->server)); \ } #define NTOH_PPXCOM_N2_JOIN_RING(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ NTOH_PCHMPXSVR(&((pdata)->server)); \ } #define HTON_PPXCOM_N2_STATUS_UPDATE(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = htobe64((pdata)->count); \ (pdata)->pchmpxsvr_offset = htobe64((pdata)->pchmpxsvr_offset); \ } #define NTOH_PPXCOM_N2_STATUS_UPDATE(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = be64toh((pdata)->count); \ (pdata)->pchmpxsvr_offset = be64toh((pdata)->pchmpxsvr_offset); \ } #define HTON_PPXCOM_N2_STATUS_CONFIRM(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = htobe64((pdata)->count); \ (pdata)->pchmpxsvr_offset = htobe64((pdata)->pchmpxsvr_offset); \ } #define NTOH_PPXCOM_N2_STATUS_CONFIRM(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ (pdata)->count = be64toh((pdata)->count); \ (pdata)->pchmpxsvr_offset = be64toh((pdata)->pchmpxsvr_offset); \ } #define HTON_PPXCOM_N2_STATUS_CHANGE(pdata) \ { \ HTON_PPXCOM_HEAD(&((pdata)->head)); \ HTON_PCHMPXSVR(&((pdata)->server)); \ } #define NTOH_PPXCOM_N2_STATUS_CHANGE(pdata) \ { \ NTOH_PPXCOM_HEAD(&((pdata)->head)); \ NTOH_PCHMPXSVR(&((pdata)->server)); \ } //--------------------------------------------------------- // Communication Packets //--------------------------------------------------------- // Following pxcomtype_t is long(64) instead of enum because // PXCOM_HEAD should be alignment for datas after it. // typedef uint64_t comtype_t; // type for packet typedef uint64_t c2ctype_t; // COM_C2C type for duplication // Version #define COM_VERSION_UNINIT 0L // version 1(older than v1.0.70) #define COM_VERSION_1 1L // version 1(older than v1.0.70) #define COM_VERSION_2 2L // version 2 // [NOTE] // If it is not initialized, it is judged as current because // it is not connected to RING. #define IS_COM_CURRENT_VERSION(version) (COM_VERSION_2 == version || COM_VERSION_UNINIT == version) // Type for packet #define COM_UNKNOWN 0 // Unknown #define COM_C2C 1 // Client Process to Client Process #define COM_PX2PX 2 // CHMPX to CHMPX(Internal communication) #define COM_S2PX 3 // Signal to CHMPX #define COM_F2PX 4 // Inotify to CHMPX #define COM_C2PX 5 // Client Process to CHMPX(Notification from Client process) #define COM_PX2C 6 // CHMPX to Client Process(Notification from CHMPX) #define STRCOMTYPE(type) ( COM_UNKNOWN == type ? "COM_UNKNOWN" : \ COM_C2C == type ? "COM_C2C" : \ COM_PX2PX == type ? "COM_PX2PX" : \ COM_S2PX == type ? "COM_S2PX" : \ COM_F2PX == type ? "COM_F2PX" : \ COM_C2PX == type ? "COM_C2PX" : \ COM_PX2C == type ? "COM_PX2C" : "NOT_DEFINED_TYPE" ) // COM_C2C Type for duplication #define COM_C2C_IGNORE 0x0 // ignore(not COM_C2C packet) #define COM_C2C_NORMAL 0x1 // send to single routing #define COM_C2C_ROUTING 0x2 // send to duplicated routing #define COM_C2C_BROADCAST 0x3 // send broadcast #define COM_C2C_RBROADCAST 0x4 // send broadcast to duplicate in routing #define COM_C2C_MODE_MASK 0x7 // mask for C2C TYPE #define COM_C2C_NOT_SELF 0x10 // flag for excepting self #define GET_C2CTYPE(type) (COM_C2C_MODE_MASK & type) #define SET_C2CTYPE_SELF(type) (type = GET_C2CTYPE(type)) #define SET_C2CTYPE_NOT_SELF(type) (type = GET_C2CTYPE(type) | COM_C2C_NOT_SELF) #define IS_C2CTYPE_IGNORE(type) (COM_C2C_IGNORE == GET_C2CTYPE(type)) #define IS_C2CTYPE_NORMAL(type) (COM_C2C_NORMAL == GET_C2CTYPE(type)) #define IS_C2CTYPE_ROUTING(type) (COM_C2C_ROUTING == GET_C2CTYPE(type)) #define IS_C2CTYPE_BROADCAST(type) (COM_C2C_BROADCAST == GET_C2CTYPE(type)) #define IS_C2CTYPE_RBROADCAST(type) (COM_C2C_RBROADCAST == GET_C2CTYPE(type)) #define IS_C2CTYPE_SELF(type) (COM_C2C_NOT_SELF != (COM_C2C_NOT_SELF & type)) #define IS_C2CTYPE_NOT_SELF(type) (COM_C2C_NOT_SELF == (COM_C2C_NOT_SELF & type)) #define STRCOMC2CTYPE(type) ( IS_C2CTYPE_IGNORE(type) ? "COM_C2C_IGNORE" : \ IS_C2CTYPE_NORMAL(type) ? ((IS_C2CTYPE_SELF(type) ? "COM_C2C_NORMAL" : "COM_C2C_NORMAL_NOT_SELF")) : \ IS_C2CTYPE_ROUTING(type) ? ((IS_C2CTYPE_SELF(type) ? "COM_C2C_ROUTING" : "COM_C2C_ROUTING_NOT_SELF")) : \ IS_C2CTYPE_BROADCAST(type) ? ((IS_C2CTYPE_SELF(type) ? "COM_C2C_BROADCAST" : "COM_C2C_BROADCAST_NOT_SELF")) : \ IS_C2CTYPE_RBROADCAST(type) ? ((IS_C2CTYPE_SELF(type) ? "COM_C2C_RBROADCAST": "COM_C2C_RBROADCAST_NOT_SELF")) : "NOT_DEFINED_TYPE" ) typedef struct packed_ids{ chmpxid_t chmpxid; msgid_t msgid; }CHMPX_ATTR_PACKED PCKID, *PPCKID; typedef struct com_head{ comver_t version; // version comtype_t type; c2ctype_t c2ctype; PCKID dept_ids; // "From" of End to end(departure) PCKID term_ids; // "To" of End to end(terminus) msgid_t peer_dept_msgid; // "From" of Peer to Peer msgid_t peer_term_msgid; // "To" of Peer to Peer serial_t mq_serial_num; // serial number on MQ chmhash_t hash; struct timespec reqtime; }CHMPX_ATTR_PACKED COMHEAD, *PCOMHEAD; typedef struct com_packet{ COMHEAD head; size_t length; // this structure length and detail data length after this structure off_t offset; // offset for detail data after this structure from this structure top }CHMPX_ATTR_PACKED COMPKT, *PCOMPKT; //------------ // Macros //------------ #define COPY_PKID(pdest, psrc) \ { \ (pdest)->chmpxid = (psrc)->chmpxid; \ (pdest)->msgid = (psrc)->msgid; \ } #define COPY_COMHEAD(pdest, psrc) \ { \ COPY_PKID(&((pdest)->dept_ids), &((psrc)->dept_ids)); \ COPY_PKID(&((pdest)->term_ids), &((psrc)->term_ids)); \ (pdest)->version = (psrc)->version; \ (pdest)->type = (psrc)->type; \ (pdest)->c2ctype = (psrc)->c2ctype; \ (pdest)->peer_dept_msgid = (psrc)->peer_dept_msgid; \ (pdest)->peer_term_msgid = (psrc)->peer_term_msgid; \ (pdest)->mq_serial_num = (psrc)->mq_serial_num; \ (pdest)->hash = (psrc)->hash; \ COPY_TIMESPEC(&((pdest)->reqtime), &((psrc)->reqtime)); \ } #define COPY_COMPKT(pdest, psrc) \ { \ COPY_COMHEAD(&((pdest)->head), &((psrc)->head)); \ (pdest)->length = (psrc)->length; \ (pdest)->offset = (psrc)->offset; \ } //------------ // Converter //------------ #define HTON_PPCKID(pdata) \ { \ (pdata)->chmpxid = htobe64((pdata)->chmpxid); \ (pdata)->msgid = htobe64((pdata)->msgid); \ } #define NTOH_PPCKID(pdata) \ { \ (pdata)->chmpxid = be64toh((pdata)->chmpxid); \ (pdata)->msgid = be64toh((pdata)->msgid); \ } #define HTON_TIMESPEC(ptr) \ { \ (ptr)->tv_sec = htobe64((ptr)->tv_sec); \ (ptr)->tv_nsec = htobe64((ptr)->tv_nsec); \ } \ #define NTOH_TIMESPEC(ptr) \ { \ (ptr)->tv_sec = be64toh((ptr)->tv_sec); \ (ptr)->tv_nsec = be64toh((ptr)->tv_nsec); \ } \ #define HTON_PCOMHEAD(pdata) \ { \ HTON_PPCKID(&((pdata)->dept_ids)); \ HTON_PPCKID(&((pdata)->term_ids)); \ (pdata)->version = htobe64((pdata)->version); \ (pdata)->type = htobe64((pdata)->type); \ (pdata)->c2ctype = htobe64((pdata)->c2ctype); \ (pdata)->peer_dept_msgid = htobe64((pdata)->peer_dept_msgid); \ (pdata)->peer_term_msgid = htobe64((pdata)->peer_term_msgid); \ (pdata)->mq_serial_num = htobe64((pdata)->mq_serial_num); \ (pdata)->hash = htobe64((pdata)->hash); \ HTON_TIMESPEC(&((pdata)->reqtime)); \ } #define NTOH_PCOMHEAD(pdata) \ { \ NTOH_PPCKID(&((pdata)->dept_ids)); \ NTOH_PPCKID(&((pdata)->term_ids)); \ (pdata)->version = be64toh((pdata)->version); \ (pdata)->type = be64toh((pdata)->type); \ (pdata)->c2ctype = be64toh((pdata)->c2ctype); \ (pdata)->peer_dept_msgid = be64toh((pdata)->peer_dept_msgid); \ (pdata)->peer_term_msgid = be64toh((pdata)->peer_term_msgid); \ (pdata)->mq_serial_num = be64toh((pdata)->mq_serial_num); \ (pdata)->hash = be64toh((pdata)->hash); \ NTOH_TIMESPEC(&((pdata)->reqtime)); \ } #define HTON_PCOMPKT(pdata) \ { \ HTON_PCOMHEAD(&((pdata)->head)); \ (pdata)->length = htobe64((pdata)->length); \ (pdata)->offset = htobe64((pdata)->offset); \ } #define NTOH_PCOMPKT(pdata) \ { \ NTOH_PCOMHEAD(&((pdata)->head)); \ (pdata)->length = be64toh((pdata)->length); \ (pdata)->offset = be64toh((pdata)->offset); \ } //------------ // Utility Macros //------------ #define CVT_COMPTR_HEAD(pComAll) &((pComAll)->val_head) #define CVT_COMPTR_STATUS_REQ(pComAll) &((pComAll)->val_status_req) #define CVT_COMPTR_STATUS_RES(pComAll) &((pComAll)->val_status_res) #define CVT_COMPTR_CONINIT_REQ(pComAll) &((pComAll)->val_coninit_req) #define CVT_COMPTR_CONINIT_RES(pComAll) &((pComAll)->val_coninit_res) #define CVT_COMPTR_JOIN_RING(pComAll) &((pComAll)->val_join_ring) #define CVT_COMPTR_STATUS_UPDATE(pComAll) &((pComAll)->val_status_update) #define CVT_COMPTR_STATUS_CONFIRM(pComAll) &((pComAll)->val_status_confirm) #define CVT_COMPTR_STATUS_CHANGE(pComAll) &((pComAll)->val_status_change) #define CVT_COMPTR_MERGE_START(pComAll) &((pComAll)->val_merge_start) #define CVT_COMPTR_MERGE_ABORT(pComAll) &((pComAll)->val_merge_abort) #define CVT_COMPTR_MERGE_COMPLETE(pComAll) &((pComAll)->val_merge_complete) #define CVT_COMPTR_SERVER_DOWN(pComAll) &((pComAll)->val_server_down) #define CVT_COMPTR_REQ_UPDATEDATA(pComAll) &((pComAll)->val_req_updatedata) #define CVT_COMPTR_RES_UPDATEDATA(pComAll) &((pComAll)->val_res_updatedata) #define CVT_COMPTR_RESULT_UPDATEDATA(pComAll) &((pComAll)->val_result_updatedata) #define CVT_COMPTR_MERGE_SUSPEND(pComAll) &((pComAll)->val_merge_suspend) #define CVT_COMPTR_MERGE_NOSUSPEND(pComAll) &((pComAll)->val_merge_nosuspend) #define CVT_COMPTR_MERGE_SUSPEND_GET(pComAll) &((pComAll)->val_merge_suspend_get) #define CVT_COMPTR_MERGE_SUSPEND_RES(pComAll) &((pComAll)->val_merge_suspend_res) #define CVT_COMPTR_VERSION_REQ(pComAll) &((pComAll)->val_version_req) #define CVT_COMPTR_VERSION_RES(pComAll) &((pComAll)->val_version_res) #define CVT_COMPTR_N2_STATUS_REQ(pComAll) &((pComAll)->val_n2_status_req) #define CVT_COMPTR_N2_STATUS_RES(pComAll) &((pComAll)->val_n2_status_res) #define CVT_COMPTR_N2_CONINIT_REQ(pComAll) &((pComAll)->val_n2_coninit_req) #define CVT_COMPTR_N2_CONINIT_RES(pComAll) &((pComAll)->val_n2_coninit_res) #define CVT_COMPTR_N2_JOIN_RING(pComAll) &((pComAll)->val_n2_join_ring) #define CVT_COMPTR_N2_STATUS_UPDATE(pComAll) &((pComAll)->val_n2_status_update) #define CVT_COMPTR_N2_STATUS_CONFIRM(pComAll) &((pComAll)->val_n2_status_confirm) #define CVT_COMPTR_N2_STATUS_CHANGE(pComAll) &((pComAll)->val_n2_status_change) #define SIZEOF_CHMPX_COM(type) ( CHMPX_COM_STATUS_REQ == type ? sizeof(PXCOM_STATUS_REQ) : \ CHMPX_COM_STATUS_RES == type ? sizeof(PXCOM_STATUS_RES) : \ CHMPX_COM_CONINIT_REQ == type ? sizeof(PXCOM_CONINIT_REQ) : \ CHMPX_COM_CONINIT_RES == type ? sizeof(PXCOM_CONINIT_RES) : \ CHMPX_COM_JOIN_RING == type ? sizeof(PXCOM_JOIN_RING) : \ CHMPX_COM_STATUS_UPDATE == type ? sizeof(PXCOM_STATUS_UPDATE) : \ CHMPX_COM_STATUS_CONFIRM == type ? sizeof(PXCOM_STATUS_CONFIRM) : \ CHMPX_COM_STATUS_CHANGE == type ? sizeof(PXCOM_STATUS_CHANGE) : \ CHMPX_COM_MERGE_START == type ? sizeof(PXCOM_MERGE_START) : \ CHMPX_COM_MERGE_ABORT == type ? sizeof(PXCOM_MERGE_ABORT) : \ CHMPX_COM_MERGE_COMPLETE == type ? sizeof(PXCOM_MERGE_COMPLETE) : \ CHMPX_COM_SERVER_DOWN == type ? sizeof(PXCOM_SERVER_DOWN) : \ CHMPX_COM_REQ_UPDATEDATA == type ? sizeof(PXCOM_REQ_UPDATEDATA) : \ CHMPX_COM_RES_UPDATEDATA == type ? sizeof(PXCOM_RES_UPDATEDATA) : \ CHMPX_COM_RESULT_UPDATEDATA == type ? sizeof(PXCOM_RESULT_UPDATEDATA) : \ CHMPX_COM_MERGE_SUSPEND == type ? sizeof(PXCOM_MERGE_SUSPEND) : \ CHMPX_COM_MERGE_NOSUSPEND == type ? sizeof(PXCOM_MERGE_NOSUSPEND) : \ CHMPX_COM_MERGE_SUSPEND_GET == type ? sizeof(PXCOM_MERGE_SUSPEND_GET) : \ CHMPX_COM_MERGE_SUSPEND_RES == type ? sizeof(PXCOM_MERGE_SUSPEND_RES) : \ CHMPX_COM_VERSION_REQ == type ? sizeof(PXCOM_VERSION_REQ) : \ CHMPX_COM_VERSION_RES == type ? sizeof(PXCOM_VERSION_RES) : \ CHMPX_COM_N2_STATUS_REQ == type ? sizeof(PXCOM_N2_STATUS_REQ) : \ CHMPX_COM_N2_STATUS_RES == type ? sizeof(PXCOM_N2_STATUS_RES) : \ CHMPX_COM_N2_CONINIT_REQ == type ? sizeof(PXCOM_N2_CONINIT_REQ) : \ CHMPX_COM_N2_CONINIT_RES == type ? sizeof(PXCOM_N2_CONINIT_RES) : \ CHMPX_COM_N2_JOIN_RING == type ? sizeof(PXCOM_N2_JOIN_RING) : \ CHMPX_COM_N2_STATUS_UPDATE == type ? sizeof(PXCOM_N2_STATUS_UPDATE) : \ CHMPX_COM_N2_STATUS_CONFIRM == type ? sizeof(PXCOM_N2_STATUS_CONFIRM) : \ CHMPX_COM_N2_STATUS_CHANGE == type ? sizeof(PXCOM_N2_STATUS_CHANGE) : \ 0L) #define CVT_COM_ALL_PTR_PXCOMPKT(pComPkt) ( CHM_OFFSET((pComPkt), sizeof(COMPKT), PPXCOM_ALL) ) #define SET_PXCOMPKT(pComPkt, comver, comtype, dept_chmpxid, term_chmpxid, is_timespec, extlength) \ { \ (pComPkt)->length = sizeof(COMPKT) + SIZEOF_CHMPX_COM(comtype) + extlength; \ (pComPkt)->offset = sizeof(COMPKT); \ (pComPkt)->head.version = (COM_VERSION_2 == comver ? COM_VERSION_2 : COM_VERSION_1); \ (pComPkt)->head.type = COM_PX2PX; \ (pComPkt)->head.c2ctype = COM_C2C_IGNORE; \ (pComPkt)->head.dept_ids.chmpxid= dept_chmpxid; \ (pComPkt)->head.dept_ids.msgid = CHM_INVALID_MSGID; \ (pComPkt)->head.term_ids.chmpxid= term_chmpxid; \ (pComPkt)->head.term_ids.msgid = CHM_INVALID_MSGID; \ (pComPkt)->head.peer_dept_msgid = CHM_INVALID_MSGID; \ (pComPkt)->head.peer_term_msgid = CHM_INVALID_MSGID; \ (pComPkt)->head.mq_serial_num = MIN_MQ_SERIAL_NUMBER; \ (pComPkt)->head.hash = CHM_INVALID_HASHVAL; \ if(is_timespec){ \ if(!RT_TIMESPEC(&((pComPkt)->head.reqtime))){ \ WAN_CHMPRN("Could not get timespec(errno=%d), but continue...", errno); \ INIT_TIMESPEC(&((pComPkt)->head.reqtime)); \ } \ }else{ \ INIT_TIMESPEC(&((pComPkt)->head.reqtime)); \ } \ } //------------ // Debug Macros //------------ // [NOTE] // The DUMPCOM_COMPKT_TYPE() macro has been moved to the chmeventsock.cc file. // See comments in chmeventsock.cc for details. // #define DUMPCOM_COMPKT(headmsg, pComPkt) \ if(chm_debug_mode >= CHMDBG_DUMP){ \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), "DUMP COMPKT(%s) = {\n", (CHMEMPTYSTR(headmsg) ? "notag" : headmsg)); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " head = {\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " version = 0x%016" PRIx64 "\n", (pComPkt)->head.version); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " type = 0x%016" PRIx64 "\n", (pComPkt)->head.type); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " c2ctype = 0x%016" PRIx64 "\n", (pComPkt)->head.c2ctype); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " dept_ids = {\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " chmpxid = 0x%016" PRIx64 "\n", (pComPkt)->head.dept_ids.chmpxid); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " msgid = 0x%016" PRIx64 "\n", (pComPkt)->head.dept_ids.msgid); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " }\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " term_ids = {\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " chmpxid = 0x%016" PRIx64 "\n", (pComPkt)->head.term_ids.chmpxid); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " msgid = 0x%016" PRIx64 "\n", (pComPkt)->head.term_ids.msgid); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " }\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " peer_dept_msgid = 0x%016" PRIx64 "\n", (pComPkt)->head.peer_dept_msgid); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " peer_term_msgid = 0x%016" PRIx64 "\n", (pComPkt)->head.peer_term_msgid); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " mq_serial_num = 0x%016" PRIx64 "\n", (pComPkt)->head.mq_serial_num); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " hash = 0x%016" PRIx64 "\n", (pComPkt)->head.hash); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " reqtime = {\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " tv_sec = %jd\n", static_cast<intmax_t>((pComPkt)->head.reqtime.tv_sec)); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " tv_nsec = %ld\n", (pComPkt)->head.reqtime.tv_nsec); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " }\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " }\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " length = %zu\n", (pComPkt)->length); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " offset = %jd\n", static_cast<intmax_t>((pComPkt)->offset)); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), "}\n"); \ } #define DUMPCOM_PXCLT(headmsg, pCltAll) \ if(chm_debug_mode >= CHMDBG_DUMP){ \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), "DUMP PXCTL(%s) = {\n", (CHMEMPTYSTR(headmsg) ? "notag" : headmsg)); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " val_head = {\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " type = 0x%016" PRIx64 "\n", (pCltAll)->val_head.type); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " length = 0x%016" PRIx64 "\n", (pCltAll)->val_head.length); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), " }\n"); \ fprintf((chm_dbg_fp ? chm_dbg_fp : stderr), "}\n"); \ } #endif // CHMCOMSTRUCTURE_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmcntrl.h
<reponame>ggtakec/chmpx /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMCNTRL_H #define CHMCNTRL_H #include <signal.h> #include <map> #include "chmconf.h" #include "chmimdata.h" #include "chmeventmq.h" #include "chmeventsock.h" #include "chmeventshm.h" //--------------------------------------------------------- // ChmCntrl Class //--------------------------------------------------------- class ChmCntrl { friend class ChmEventBase; friend class CHMConf; friend class ChmEventMq; friend class ChmEventSock; friend class ChmEventShm; protected: typedef enum _chmcntrl_type{ CHMCHNTL_TYPE_CHMPXPROC, CHMCHNTL_TYPE_CLIENT_ONSERVER, CHMCHNTL_TYPE_CLIENT_ONSLAVE }CHMCNTRLTYPE; typedef enum _evobj_type{ EVOBJ_TYPE_CONF, EVOBJ_TYPE_EVSOCK, EVOBJ_TYPE_EVMQ, EVOBJ_TYPE_EVSHM }EVOBJTYPE; typedef std::map<int, ChmEventBase*> evobj_map_t; // Key is number which is kind of event object. static const int DEFAULT_MAX_EVENT_CNT = 32; // receive max event at once for CHMCHNTL_TYPE_CHMPXPROC static const int DEFAULT_EVENT_TIMEOUT = 100; // timeout for epoll wait(100ms) for CHMCHNTL_TYPE_CHMPXPROC static const int EVENT_NOWAIT = 0; // no wait for epoll static volatile bool DoLoop; // Break loop flag CHMCNTRLTYPE chmcntrltype; // process type int eqfd; // event queue fd ChmIMData ImData; // CHMConf* pConfObj; // ChmEventMq* pEventMq; // ChmEventSock* pEventSock; // [NOTICE] chmpx only has this value. ChmEventShm* pEventShm; // [NOTICE] chmpx only has this value. bool auto_rejoin; // retry to join if chmpx process is down. std::string bup_cfg; // backup for configuration file path or json string. evobj_map_t evobjmap; // Object mapping volatile bool is_close_notify; // client closing notify flag protected: ChmEventBase* GetEventBaseObj(EVOBJTYPE type); ChmEventBase* FindEventBaseObj(int fd); bool GetEventBaseObjType(const ChmEventBase* pEvObj, EVOBJTYPE& type); ChmIMData* GetImDataObj(void) { return (ImData.IsInitialized() ? &ImData : NULL); } CHMConf* GetConfObj(void) { return pConfObj; } ChmEventMq* GetEventMqObj(void) { return pEventMq; } ChmEventSock* GetEventSockObj(void) { return pEventSock; } ChmEventShm* GetEventShmObj(void) { return pEventShm; } bool Initialize(const char* cfgfile, CHMCNTRLTYPE type, bool is_auto_rejoin = false, chm_merge_get_cb getfp = NULL, chm_merge_set_cb setfp = NULL, chm_merge_lastts_cb lastupdatefp = NULL, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL); bool ReInitialize(long waitms = 0L, int trycnt = 1); bool IsInitialized(void) const; bool InitializeEventFd(void); bool ConfigurationUpdateNotify(void); bool Processing(PCOMPKT pComPkt, EVOBJTYPE call_ev_type); long PlaningReceiverCount(chmhash_t hash, c2ctype_t c2ctype); bool RawSendOnSlave(msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt, c2ctype_t c2ctype); bool RawSendOnServer(const unsigned char* pbody, size_t blength, chmhash_t hash, c2ctype_t c2ctype, bool without_self); bool RawSend(msgid_t msgid, PCOMPKT pComPkt, const unsigned char* pbody, size_t blength, chmhash_t hash, c2ctype_t c2ctype); // For merging bool MergeGetLastTime(struct timespec& lastts); bool MergeRequestUpdateData(const PPXCOMMON_MERGE_PARAM pmerge_param); bool MergeResponseUpdateData(chmpxid_t chmpxid, size_t length, const unsigned char* pdata, const struct timespec* pts); bool MergeSetUpdateData(size_t length, const unsigned char* pdata, const struct timespec* pts); bool MergeResultUpdateData(chmpxid_t chmpxid, reqidmapflag_t result_updatedata); bool MergeAbortUpdateData(void); public: static void LoopBreakHandler(int signum); static void FreeDupAllChmInfo(PCHMINFOEX ptr); // for free memory allocated by DupAllChmInfo() static void FreeDupSelfChmpxInfo(PCHMPX ptr); // for free memory allocated by DupSelfChmpxInfo() ChmCntrl(void); virtual ~ChmCntrl(); bool Clean(bool is_clean_bup = true); // For chmpx process bool InitializeOnChmpx(const char* cfgfile, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL) { return Initialize(cfgfile, CHMCHNTL_TYPE_CHMPXPROC, false, NULL, NULL, NULL, ctlport, cuk); } // For server process on library bool InitializeOnServer(const char* cfgfile, bool is_auto_rejoin = false, chm_merge_get_cb getfp = NULL, chm_merge_set_cb setfp = NULL, chm_merge_lastts_cb lastupdatefp = NULL, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL) { return Initialize(cfgfile, CHMCHNTL_TYPE_CLIENT_ONSERVER, is_auto_rejoin, getfp, setfp, lastupdatefp, ctlport, cuk); } // For client process on library bool InitializeOnSlave(const char* cfgfile, bool is_auto_rejoin = false, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL) { return Initialize(cfgfile, CHMCHNTL_TYPE_CLIENT_ONSLAVE, is_auto_rejoin, NULL, NULL, NULL, ctlport, cuk); } bool OnlyAttachInitialize(const char* cfgfile, short ctlport = CHM_INVALID_PORT, const char* cuk = NULL); void AllowSelfCert(void); // For only debugging // where process running on bool IsChmpxType(void) const { return (CHMCHNTL_TYPE_CHMPXPROC == chmcntrltype); } bool IsClientOnSvrType(void) const { return (CHMCHNTL_TYPE_CLIENT_ONSERVER == chmcntrltype); } bool IsClientOnSlvType(void) const { return (CHMCHNTL_TYPE_CLIENT_ONSLAVE == chmcntrltype); } // Receive for chmpx process bool EventLoop(void); // Receive/Send for client on server chmpx process bool Receive(PCOMPKT* ppComPkt, unsigned char** ppbody = NULL, size_t* plength = NULL, int timeout_ms = ChmCntrl::EVENT_NOWAIT, bool no_giveup_rejoin = false); bool Send(const unsigned char* pbody, size_t blength, chmhash_t hash, bool is_routing = true, bool without_self = false) { return RawSendOnServer(pbody, blength, hash, is_routing ? COM_C2C_ROUTING : COM_C2C_NORMAL, without_self); } bool Broadcast(const unsigned char* pbody, size_t blength, chmhash_t hash, bool without_self = false) { return RawSendOnServer(pbody, blength, hash, COM_C2C_BROADCAST, without_self); } bool Replicate(const unsigned char* pbody, size_t blength, chmhash_t hash, bool without_self = true) { return RawSendOnServer(pbody, blength, hash, COM_C2C_RBROADCAST, without_self); } // Open/Close/Receive/Send for client on slave chmpx process msgid_t Open(bool no_giveup_rejoin = false); bool Close(msgid_t msgid); bool Receive(msgid_t msgid, PCOMPKT* ppComPkt, unsigned char** ppbody, size_t* plength, int timeout_ms = 0); // 0 is no wait bool Send(msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt = NULL, bool is_routing = true) { return RawSendOnSlave(msgid, pbody, blength, hash, preceivercnt, is_routing ? COM_C2C_ROUTING : COM_C2C_NORMAL); } bool Broadcast(msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt = NULL) { return RawSendOnSlave(msgid, pbody, blength, hash, preceivercnt, COM_C2C_BROADCAST); } bool Replicate(msgid_t msgid, const unsigned char* pbody, size_t blength, chmhash_t hash, long* preceivercnt = NULL) { return RawSendOnSlave(msgid, pbody, blength, hash, preceivercnt, COM_C2C_RBROADCAST); } // Reply for all client bool Send(PCOMPKT pComPkt, const unsigned char* pbody, size_t blength); bool Reply(PCOMPKT pComPkt, const unsigned char* pbody, size_t blength) { return Send(pComPkt, pbody, blength); } // Check error type as Chmpx process exiting bool IsChmpxExit(void); // Utility for manual replication bool GetAllReplicateChmHashs(chmhash_t hash, chmhashlist_t& basehashs, bool with_pending = true, bool without_down = true, bool without_suspend = true); // Dump/Get internal information bool DumpSelfChmpxSvr(std::stringstream& sstream) const; PCHMINFOEX DupAllChmInfo(void); PCHMPX DupSelfChmpxInfo(void); }; #endif // CHMCNTRL_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmssnss.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Mon May 13 2018 * REVISION: * */ #ifndef CHMSSOPENSSL_H #define CHMSSOPENSSL_H #include <nss.h> #include <pk11pub.h> #include <map> #include <string> #include "chmeventsock.h" //--------------------------------------------------------- // Common type for ChmEventSock //--------------------------------------------------------- typedef struct chm_nss_ss_context* ChmSSCtx; // this type is opaque //--------------------------------------------------------- // Internal structure and map //--------------------------------------------------------- typedef struct chm_nss_cert* ChmSSCert; typedef std::map<std::string, ChmSSCert> chmsscertmap_t; typedef std::list<PK11GenericObject*> chmpk11list_t; //--------------------------------------------------------- // ChmSecureSock Class for OpenSSL //--------------------------------------------------------- class ChmSecureSock { protected: static bool is_self_sigined; // For DEBUG(but we do not use this for NSS) static int pr_init_count; // flag for NSPR initialization static int nss_init_count; // flag for NSS initialization static bool is_verify_peer; // Verify Peer mode on server static chmss_ver_t ssl_min_ver; // SSL/TLS minimum version static SECMODModule* PKCS11_LoadedModule; // loaded module for PKCS11 static SECMODModule* PEM_LoadedModule; // loaded module for PEM static PRLock* FindSlotLock; // Lock object(by PR) for slot static PRLock* CertMapLock; // Lock object(by PR) for Cert map protected: NSSInitContext* nss_ctx; // NSS context for both server/slave protected: static bool InitLibrary(NSSInitContext** ctx, const char* CApath, const char* CAfile, bool is_verify_peer); static bool FreeLibrary(NSSInitContext* ctx); static bool InitLoadExtModule(void); static std::string& GetCAPath(void); // CA directory path if exists static std::string& GetCAFile(void); // CA file path if exists static std::string& GetNssdbDir(void); // NSSDB directory path in configuration like SSL_DIR environment static chmsscertmap_t& GetCertMap(void); // Cert etc map static bool SetCA(const char* CApath, const char* CAfile); static bool SetMinVersion(PRFileDesc* model); static std::string GetSessionInfo(PRFileDesc* session); static bool LoadCACerts(chmpk11list_t& pk11objlist); static bool MakeNickname(const char* pCertFile, std::string& strNickname); static bool CheckCertNicknameType(const char* pCertFile, const char* pPrivateKeyFile, std::string& strNickname, std::string& strCertKey, bool& isExistFile); static PK11GenericObject* GeneratePK11GenericObject(const char* filename, bool is_private_key); static bool LoadCertPrivateKey(const char* pCertFile, const char* pPrivateKeyFile, PK11GenericObject** ppk11CertObj, PK11GenericObject** ppk11PKeyObj, CERTCertificate** ppCert, SECKEYPrivateKey** ppPrivateKey); static bool SetBlockingMode(PRFileDesc* SSSession, bool is_blocking); static SECStatus AuthCertificateCallback(void* arg, PRFileDesc* fd, PRBool checksig, PRBool isServer); static SECStatus ClientAuthDataHookCallback(void* arg, PRFileDesc* sock, struct CERTDistNamesStr* caNames, struct CERTCertificateStr** pRetCert, struct SECKEYPrivateKeyStr** pRetKey); static SECStatus BadCertCallback(void* arg, PRFileDesc* fd); static PRFileDesc* GetModelDescriptor(bool is_server, bool is_verify_peer); static bool IsSafeSSLContextEx(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); static ChmSSCtx GetSSLContextEx(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); static void FreeSSLContextEx(ChmSSCtx ctx); static void FreeSSLSessionEx(ChmSSSession sslsession); public: static void AllowSelfSignedCert(void); // For only debugging static void DenySelfSignedCert(void); static const char* LibraryName(void); static bool IsCAPathAllowFile(void); static bool IsCertAllowName(void); static bool SetSslMinVersion(chmss_ver_t ssver); static bool SetExtValue(const char* key, const char* value); static bool CheckResultSSL(int sock, ChmSSSession sslsession, long action_result, int type, bool& is_retry, bool& is_close, int retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static ChmSSSession AcceptSSL(ChmSSCtx ctx, int sock, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static ChmSSSession ConnectSSL(ChmSSCtx ctx, int sock, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool ShutdownSSL(int sock, ChmSSSession sslsession, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static int Read(ChmSSSession sslsession, void* pbuf, int length); static int Write(ChmSSSession sslsession, const void* pbuf, int length); ChmSecureSock(const char* CApath = NULL, const char* CAfile = NULL, bool is_verify_peer = false); virtual ~ChmSecureSock(); bool Clean(void); bool IsSafeSSLContext(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); ChmSSCtx GetSSLContext(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); void FreeSSLContext(ChmSSCtx ctx); }; #endif // CHMSSOPENSSL_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmssgnutls.h
<gh_stars>10-100 /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Fri Jun 16 2018 * REVISION: * */ #ifndef CHMSSGNUTLS_H #define CHMSSGNUTLS_H #include <gnutls/gnutls.h> #include "chmeventsock.h" //--------------------------------------------------------- // Common type for ChmEventSock //--------------------------------------------------------- typedef struct chm_gnutls_ss_context* ChmSSCtx; // this type is opaque //--------------------------------------------------------- // ChmSecureSock Class for OpenSSL //--------------------------------------------------------- class ChmSecureSock { protected: static bool is_self_sigined; // For DEBUG(but we do not use this for GnuTLS) static int init_count; // flag for initialization static bool is_verify_peer; // Verify Peer mode on server static chmss_ver_t ssl_min_ver; // SSL/TLS minimum version protected: static bool InitLibrary(const char* CApath, const char* CAfile, bool is_verify_peer); static bool FreeLibrary(void); static std::string& GetCAPath(void); // CA directory path if exists static std::string& GetCAFile(void); // CA file path if exists static bool SetCA(const char* CApath, const char* CAfile); static bool SetMinVersion(gnutls_session_t session); static bool LoadCACerts(gnutls_certificate_credentials_t& cert_cred); static bool IsSafeSSLContextEx(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); static ChmSSCtx GetSSLContextEx(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); static void FreeSSLContextEx(ChmSSCtx ctx); public: static void AllowSelfSignedCert(void); // For only debugging(but we do not use this for GnuTLS) static void DenySelfSignedCert(void); static const char* LibraryName(void); static bool IsCAPathAllowFile(void); static bool IsCertAllowName(void); static bool SetSslMinVersion(chmss_ver_t ssver); static bool SetExtValue(const char* key, const char* value); static bool CheckResultSSL(int sock, ChmSSSession sslsession, long action_result, int type, bool& is_retry, bool& is_close, int retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static ChmSSSession AcceptSSL(ChmSSCtx ctx, int sock, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static ChmSSSession ConnectSSL(ChmSSCtx ctx, int sock, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static bool ShutdownSSL(int sock, ChmSSSession sslsession, int con_retrycnt = CHMEVENTSOCK_RETRY_DEFAULT, suseconds_t con_waittime = CHMEVENTSOCK_TIMEOUT_DEFAULT); static int Read(ChmSSSession sslsession, void* pbuf, int length); static int Write(ChmSSSession sslsession, const void* pbuf, int length); ChmSecureSock(const char* CApath = NULL, const char* CAfile = NULL, bool is_verify_peer = false); virtual ~ChmSecureSock(); bool Clean(void); bool IsSafeSSLContext(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); ChmSSCtx GetSSLContext(const char* server_cert, const char* server_prikey, const char* slave_cert, const char* slave_prikey); void FreeSSLContext(ChmSSCtx ctx); }; #endif // CHMSSGNUTLS_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmeventmq.h
/* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMEVENTMQ_H #define CHMEVENTMQ_H #include <mqueue.h> #include <map> #include "chmeventbase.h" #include "chmconf.h" #include "chmthread.h" #include "chmpx.h" #include "chmstructure.tcc" #include "chmlockmap.tcc" //--------------------------------------------------------- // ABOUT MQUEUE MESSAGING // // Sending/Receiving messages on mqueue is following rule. // * Sending data on mqueue is only sender msgid. // * Message body is stored on k2hash by keys which are // "<from msgid>-<to msgid>.XXXX". // * Message body on k2hash are two type, one is message // head(COMPKT), the other is real message body. // // Messaging on MQ is synchronous communication. This is // very important. // And create/destroy client side MQ by each communication. // It is probably not good performance, but it is not large // deteriorated. // // CHMPX side: // * Create one MQ as first msgid in base msgid in CHMSHM. // And add and wait event from epoll. // // Client side: // * Create one MQ as msgid which is not assigned yet. // It is doing by each attach request on client. // * When sending, set a message with header in K2HASH and // send msgid which means client MQ id to CHMPX MQ. // After that, wait response through client MQ from CHMPX. // After receiving, close and remove own MQ. // //--------------------------------------------------------- // Symbols //--------------------------------------------------------- #define PXCLTPKT_AUTO_LENGTH (-1) #define CHMEVENTMQ_RETRY_DEFAULT (-1) #define CHMEVENTMQ_TIMEOUT_DEFAULT (0) //--------------------------------------------------------- // Structure //--------------------------------------------------------- typedef struct chm_composed_msgid{ msgid_t msgid; serial_t number; bool is_ack; bool is_ack_success; chm_composed_msgid(void) : msgid(CHM_INVALID_MSGID), number(MIN_MQ_SERIAL_NUMBER), is_ack(false), is_ack_success(false) {} }COMPOSEDMSGID, *PCOMPOSEDMSGID; typedef struct chm_update_data_param{ chmpxid_t chmpxid; // requester chmpx struct timespec startts; // start time for update datas struct timespec endts; // end time for update datas chmhash_t max_pending_hash; // max pending hash value chmhash_t pending_hash; // new(pending) hash value chmhash_t max_base_hash; // max base hash value chmhash_t base_hash; // base hash value long replica_count; // replica count bool is_expire_check; // whether checking expire time }CHM_UPDATA_PARAM, *PCHM_UPDATA_PARAM; typedef std::vector<PCHM_UPDATA_PARAM> mqmparamlist_t; //--------------------------------------------------------- // Typedefs //--------------------------------------------------------- typedef chm_lock_map<msgid_t, mqd_t> msgid_mq_map_t; typedef chm_lock_map<mqd_t, msgid_t> mq_msgid_map_t; typedef std::vector<mqd_t> mqfd_list_t; //--------------------------------------------------------- // ChmEventMq Class //--------------------------------------------------------- class ChmEventMq : public ChmEventBase { public: static const int DEFAULT_RETRYCOUNT = 3; static const long DEFAULT_TIMEOUT_US = 10 * 1000; // 10ms static const int DEFAULT_MQ_THREAD_CNT = 0; // MQ processing thread count static const long DEFAULT_GETLTS_SLEEP = 1000; // 1us sleep time for checking the result of getting last update time static const long DEFAULT_GETLTS_LOOP = 1000 * 1000; // loop count for checking the result of getting last update time static const time_t DEFAULT_MERGE_TIMEOUT = 0; // timeout value for merging(default is no timeout) protected: msgid_mq_map_t recv_idfd_map; // map all MQ for receiving: msgid -> fd mq_msgid_map_t recv_fdid_map; // map all MQ for receiving: fd -> msgid msgid_mq_map_t reserve_idfd_map; // map disactivated MQ for receiving: msgid -> fd msgid_mq_map_t dest_idfd_map; // map cache MQ for sending: msgid -> fd mq_msgid_map_t dest_fdid_map; // map cache MQ for sending: fd -> msgid serial_t serial_num; // serial number for each mq message(using autolock) volatile int actmq_lockval; // lock variable for ActivateMQ ChmThread procthreads; // processing threads ChmThread mergethread; // merge thread chm_merge_get_cb mgetfunc; // merge callback for getting each data chm_merge_set_cb msetfunc; // merge callback for setting each data chm_merge_lastts_cb mlastfunc; // merge callback for getting lastupdate time volatile bool notify_merge_get; // flag for receiving lastest update time struct timespec* pres_lasttime; // temporary buffer for receiving lastest update time volatile int mparam_list_lockval; // lock variable for merge_param_list mqmparamlist_t merge_param_list; // update data(merge) parameter list volatile bool notify_merge_update; // flag for running thread int retry_count; // cache value for ChmIMData::GetMQRetryCnt() long timeout_us; // cache value for ChmIMData::GetMQTimeout() time_t timeout_merge; // cache value for ChmIMData::GetMergeTimeout() bool is_server_mode; // cache value for ChmIMData::IsServerMode() bool use_mq_ack; // cache value for ChmIMData::IsAckMQ() protected: static bool MakeK2hashKey(msgid_t dept_msgid, msgid_t term_msgid, serial_t serial, std::string& headkey, std::string& bodykey); // Merge static bool MergeWorkerFunc(void* common_param, chmthparam_t wp_param); // callback functions for thread class static bool ReceiveWorkerProc(void* common_param, chmthparam_t wp_param); // callback for mapping static bool RcvfdIdMapCallback(const mq_msgid_map_t::iterator& iter, void* pparam); static bool DestfdIdMapCallback(const mq_msgid_map_t::iterator& iter, void* pparam); bool RawReceive(mqd_t mqfd, const COMPOSEDMSGID& composed); serial_t GetSerialNumber(void); msgid_t ComposeSerialMsgid(const COMPOSEDMSGID& composed); msgid_t ComposeSerialMsgid(const msgid_t msgid, const serial_t serial, bool is_ack = false, bool ack_success = false); bool DecomposeSerialMsgid(const msgid_t msgid, COMPOSEDMSGID& composed); bool BuildC2CHeadEx(PCOMHEAD pComHead, PCOMHEAD pReqComHead, chmpxid_t tochmpxid, chmhash_t hash, c2ctype_t c2ctype, msgid_t frommsgid); PCOMPKT AllocatePxCltPacket(pxclttype_t type, ssize_t ext_length = PXCLTPKT_AUTO_LENGTH); bool MakeMqPath(msgid_t msgid, std::string& path); msgid_t GetAssignedMsgId(int fd = CHM_INVALID_HANDLE); bool FreeReserveMsgIds(void); bool FreeMsgIds(msgid_t msgid, mqd_t mqfd); mqd_t OpenDestMQ(msgid_t msgid); bool PxCltReceiveMergeGetLastTime(PCOMHEAD pComHead, PPXCLT_ALL pCltAll); bool PxCltSendMergeResponseLastTime(const struct timespec& lastts); bool PxCltReceiveMergeResponseLastTime(PCOMHEAD pComHead, PPXCLT_ALL pCltAll); bool PxCltReceiveRequestUpdateData(PCOMHEAD pComHead, PPXCLT_ALL pCltAll); bool PxCltSendResponseUpdateData(chmpxid_t requester_chmpxid, const PCHMBIN pbindata, const struct timespec* pts); bool PxCltReceiveResponseUpdateData(PCOMHEAD pComHead, PPXCLT_ALL pCltAll); bool PxCltReceiveSetUpdateData(PCOMHEAD pComHead, PPXCLT_ALL pCltAll); bool PxCltSendResultUpdateData(chmpxid_t chmpxid, bool result); bool PxCltReceiveResultUpdateData(PCOMHEAD pComHead, PPXCLT_ALL pCltAll); bool PxCltReceiveAbortUpdateData(PCOMHEAD pComHead, PPXCLT_ALL pCltAll); bool PxCltSendCloseNotify(msgidlist_t& msgids); bool PxCltReceiveCloseNotify(PCOMHEAD pComHead, PPXCLT_ALL pCltAll); public: static bool InitializeMaxMqSystemSize(long maxmsg); ChmEventMq(int eventqfd = CHM_INVALID_HANDLE, ChmCntrl* pcntrl = NULL, chm_merge_get_cb mgetfp = NULL, chm_merge_set_cb msetfp = NULL, chm_merge_lastts_cb mlastfp = NULL); virtual ~ChmEventMq(); virtual bool Clean(void); virtual bool UpdateInternalData(void); int GetEventQueueFd(void); virtual bool GetEventQueueFds(event_fds_t& fds); virtual bool SetEventQueue(void); // Make one MQ for receiver side and add it to event queue fd. virtual bool UnsetEventQueue(void); // Unset mqfd from event queue fd, and destroy it. virtual bool IsEventQueueFd(int fd); virtual bool Send(PCOMPKT pComPkt, const unsigned char* pbody, size_t blength); virtual bool Receive(int fd); virtual bool NotifyHup(int fd); virtual bool Processing(PCOMPKT pComPkt); bool CheckProcessing(PCOMPKT pComPkt); // for client on slave chmpx to process other than COM_C2C msgid_t ActivatedMsgId(void); // for client on slave chmpx bool DisactivatedMsgId(msgid_t msgid); // for client on slave chmpx // ack bool SendAck(const COMPOSEDMSGID& composed, bool is_success); bool ReceiveAck(msgid_t msgid); bool ReceiveComposedMsgid(int fd, COMPOSEDMSGID& composed, bool* pCanContinueWait = NULL); bool ReceiveHead(int fd, const COMPOSEDMSGID& composed, PCOMPKT* ppComPkt); bool ReceiveHeadByMsgId(msgid_t msgid, PCOMPKT* ppComPkt, bool* pCanContinueWait = NULL); bool ReceiveBody(PCOMPKT pComPkt, unsigned char** ppbody, size_t& blength, bool is_remove_body = true); PCOMPKT ReceiveBody(PCOMPKT pComPkt, bool is_remove_body); bool RemoveReceivedBody(PCOMPKT pComPkt); bool BuildC2CResponseHead(PCOMHEAD pComHead, PCOMHEAD pReqComHead); bool BuildC2CSendHead(PCOMHEAD pComHead, chmpxid_t tochmpxid, chmhash_t hash, c2ctype_t c2ctype = COM_C2C_ROUTING, msgid_t frommsgid = CHM_INVALID_MSGID); bool CloseDestMQ(msgid_t msgid); bool PxCltSendMergeGetLastTime(struct timespec& lastts); bool PxCltSendRequestUpdateData(const PPXCOMMON_MERGE_PARAM pmerge_param); bool PxCltSendSetUpdateData(size_t length, const unsigned char* pdata, const struct timespec* pts); bool PxCltSendAbortUpdateData(void); bool PxCltSendJoinNotify(pid_t pid); }; #endif // CHMEVENTMQ_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
ggtakec/chmpx
lib/chmkvp.h
<gh_stars>10-100 /* * CHMPX * * Copyright 2014 Yahoo Japan Corporation. * * CHMPX is inprocess data exchange by MQ with consistent hashing. * CHMPX is made for the purpose of the construction of * original messaging system and the offer of the client * library. * CHMPX transfers messages between the client and the server/ * slave. CHMPX based servers are dispersed by consistent * hashing and are automatically laid out. As a result, it * provides a high performance, a high scalability. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: <NAME> * CREATE: Tue July 1 2014 * REVISION: * */ #ifndef CHMKVP_H #define CHMKVP_H #include "chmpx.h" #include "chmhash.h" //--------------------------------------------------------- // ChmBinData Class //--------------------------------------------------------- class ChmKVPair; class ChmBinData { friend class ChmKVPair; protected: unsigned char* byptr; size_t length; bool is_allocate; public: ChmBinData(unsigned char* bydata = NULL, size_t bylength = 0L, bool is_duplicate = false); ChmBinData(PCHMBIN pchmbin, bool is_duplicate); virtual ~ChmBinData(); void Clear(void); bool IsEmpty(void) const { return (NULL == byptr); } const unsigned char* Get(size_t* plength) const; const char* Get(void) const; bool Set(unsigned char* bydata, size_t bylength, bool is_duplicate = false); bool Set(PCHMBIN pchmbin, bool is_duplicate = false); bool Overwrite(unsigned char* bydata, size_t bylength, off_t offset); bool Overwrite(PCHMBIN pchmbin, off_t offset); bool Append(unsigned char* bydata, size_t bylength) { return Overwrite(bydata, bylength, static_cast<off_t>(length)); } bool Append(PCHMBIN pchmbin) { return Overwrite(pchmbin, static_cast<off_t>(length)); } bool Load(unsigned char* bydata, bool is_cvt_ntoh = true, bool is_duplicate = false); bool Put(unsigned char* bydata, bool is_cvt_hton = true) const; unsigned char* Put(size_t& bylength, bool is_cvt_hton = true) const; bool Duplicate(const ChmBinData& other); bool Copy(const ChmBinData& other); chmhash_t GetHash(void) const; }; //--------------------------------------------------------- // ChmKVPair Class //--------------------------------------------------------- class ChmKVPair { protected: ChmBinData Key; ChmBinData Value; public: ChmKVPair(unsigned char* bykey = NULL, size_t keylen = 0L, unsigned char* byval = NULL, size_t vallen = 0L, bool is_duplicate = false); ChmKVPair(ChmBinData* pKey, ChmBinData* pValue, bool is_duplicate = false); ChmKVPair(PCHMKVP pkvp, bool is_duplicate); virtual ~ChmKVPair(); void Clear(void); const unsigned char* Get(size_t* plength, bool is_key) const; const char* Get(bool is_key) const; const unsigned char* GetKey(size_t* plength) const { return Get(plength, true); } const unsigned char* GetValue(size_t* plength) const { return Get(plength, false); } const char* GetKey(void) const { return Get(true); } const char* GetValue(void) const { return Get(false); } bool Set(unsigned char* bydata, size_t bylength, bool is_key, bool is_duplicate = false); bool Set(const ChmBinData& Data, bool is_key, bool is_duplicate = false); bool Set(PCHMKVP pkvp, bool is_duplicate = false); bool Overwrite(unsigned char* bydata, size_t bylength, bool is_key, off_t offset); bool Overwrite(const ChmBinData& Data, bool is_key, off_t offset); bool Append(unsigned char* bydata, size_t bylength, bool is_key) { return Overwrite(bydata, bylength, is_key, static_cast<off_t>(is_key ? Key.length : Value.length)); } bool Append(const ChmBinData& Data, bool is_key) { return Overwrite(Data, is_key, static_cast<off_t>(is_key ? Key.length : Value.length)); } bool SetKey(unsigned char* bydata, size_t bylength, bool is_duplicate = false) { return Set(bydata, bylength, true, is_duplicate); } bool SetKey(const ChmBinData& Data, bool is_duplicate = false) { return Set(Data, true, is_duplicate); } bool OverwriteKey(unsigned char* bydata, size_t bylength, off_t offset) { return Overwrite(bydata, bylength, true, offset); } bool OverwriteKey(const ChmBinData& Data, bool is_key, off_t offset) { return Overwrite(Data, true, offset); } bool AppendKey(unsigned char* bydata, size_t bylength) { return Overwrite(bydata, bylength, true, static_cast<off_t>(Key.length)); } bool AppendKey(const ChmBinData& Data) { return Overwrite(Data, true, static_cast<off_t>(Key.length)); } bool SetValue(unsigned char* bydata, size_t bylength, bool is_duplicate = false) { return Set(bydata, bylength, false, is_duplicate); } bool SetValue(const ChmBinData& Data, bool is_duplicate = false) { return Set(Data, false, is_duplicate); } bool OverwriteValue(unsigned char* bydata, size_t bylength, off_t offset) { return Overwrite(bydata, bylength, false, offset); } bool OverwriteValue(const ChmBinData& Data, bool is_key, off_t offset) { return Overwrite(Data, false, offset); } bool AppendValue(unsigned char* bydata, size_t bylength) { return Overwrite(bydata, bylength, false, static_cast<off_t>(Value.length)); } bool AppendValue(const ChmBinData& Data) { return Overwrite(Data, false, static_cast<off_t>(Value.length)); } bool Load(unsigned char* bydata, bool is_cvt_ntoh = true, bool is_duplicate = false); bool Put(unsigned char* bydata, bool is_cvt_hton = true) const; unsigned char* Put(size_t& bylength, bool is_cvt_hton = true) const; chmhash_t GetHash(void) const; }; #endif // CHMKVP_H /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */