├── IPDispatch.go ├── LICENSE ├── README.md ├── conf ├── ipz └── www.daledi.net │ ├── node.conf │ └── view.conf ├── daemon.go ├── ipzone └── ipzone.go └── rbtree └── rbtree.go /IPDispatch.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "net/http" 7 | "os" 8 | "os/user" 9 | "runtime" 10 | "strconv" 11 | "sync" 12 | "syscall" 13 | "time" 14 | 15 | "github.com/dale-di/ipdispatch/ipzone" 16 | 17 | "github.com/facebookgo/grace/gracehttp" 18 | ) 19 | 20 | type ipdAction struct { 21 | action string 22 | param map[string]string 23 | result interface{} 24 | } 25 | 26 | var ipdisp *ipzone.IPDisp 27 | var ipdActionCH = make(chan ipdAction, 1) 28 | var ipdResultCH = make(chan ipdAction, 1) 29 | var ipdCH = make(chan *ipzone.IPDisp, 1) 30 | 31 | var actionLock sync.Mutex 32 | 33 | const ( 34 | //Version 版本号 35 | Version = "1.0" 36 | //SVer 版本信息 37 | SVer = "LPD/" + Version 38 | ) 39 | 40 | var ( 41 | conf = flag.String("c", "no", "configure dir") 42 | pidfile = flag.String("p", "/tmp/IPDispatch.pid", "the pidfile's path") 43 | username = flag.String("u", "root", "assume identity of ") 44 | ncpu = flag.Int("n", 0, "number cpus") 45 | lport = flag.String("l", ":8080", "Listen addr") 46 | ) 47 | 48 | func main() { 49 | flag.Parse() 50 | var err error 51 | //fmt.Printf("start: %v\n", os.Getpid()) 52 | if *ncpu != 0 { 53 | runtime.GOMAXPROCS(*ncpu) 54 | } 55 | if *conf == "no" { 56 | fmt.Printf("No configure dir") 57 | os.Exit(1) 58 | } 59 | var nullFile *os.File 60 | var userinfo *user.User 61 | var credential *syscall.Credential 62 | if nullFile, err = os.Open(os.DevNull); err != nil { 63 | fmt.Printf("%v\n", err) 64 | os.Exit(1) 65 | } 66 | 67 | if os.Getuid() == 0 { 68 | if userinfo, err = user.Lookup(*username); err != nil { 69 | fmt.Printf("%v\n", err) 70 | os.Exit(1) 71 | } 72 | 73 | credential = new(syscall.Credential) 74 | var i int 75 | i, _ = strconv.Atoi(userinfo.Uid) 76 | credential.Uid = uint32(i) 77 | i, _ = strconv.Atoi(userinfo.Gid) 78 | credential.Gid = uint32(i) 79 | } 80 | if err = Daemon( 81 | pidfile, 82 | []*os.File{nullFile, os.Stdin, os.Stderr}, 83 | credential, 84 | ); err != nil { 85 | fmt.Printf("%v\n", err) 86 | os.Exit(1) 87 | } 88 | go func(ipdispch chan *ipzone.IPDisp, action chan ipdAction, result chan ipdAction) { 89 | var ipdispIns = ipzone.New() 90 | err = ipdispIns.Init(*conf) 91 | if err != nil { 92 | fmt.Printf("Init false: %v\n", err) 93 | os.Remove(*pidfile) 94 | os.Exit(1) 95 | } 96 | ipdispch <- ipdispIns 97 | for { 98 | select { 99 | case doAction := <-action: 100 | switch { 101 | case doAction.action == "get": 102 | pm := doAction.param 103 | doAction.result = ipdispIns.GetCount(pm["host"], pm["node"], pm["last"]) 104 | case doAction.action == "query": 105 | pm := doAction.param 106 | ip, zone, _ := ipdispIns.Query(pm["clip"], pm["host"], pm["path"]) 107 | toip := make(map[string]string) 108 | toip["ip"] = ip 109 | toip["zonename"] = zone 110 | doAction.result = toip 111 | case doAction.action == "set": 112 | pm := doAction.param 113 | vv := doAction.result.([]string) 114 | err := ipdispIns.Set(pm["host"], pm["object"], vv) 115 | doAction.result = false 116 | if err == nil { 117 | doAction.result = true 118 | } 119 | } 120 | result <- doAction 121 | } 122 | } 123 | }(ipdCH, ipdActionCH, ipdResultCH) 124 | select { 125 | case ipdisp = <-ipdCH: 126 | break 127 | case <-time.After(time.Duration(3) * time.Second): 128 | fmt.Printf("Init false.\n") 129 | } 130 | gracehttp.Serve(&http.Server{Addr: *lport, 131 | Handler: ipDisp(), 132 | ReadTimeout: 10 * time.Second, 133 | WriteTimeout: 10 * time.Second, 134 | MaxHeaderBytes: 2048}) 135 | 136 | } 137 | 138 | func ipDisp() http.Handler { 139 | mux := http.NewServeMux() 140 | mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 141 | actionLock.Lock() 142 | defer actionLock.Unlock() 143 | w.Header().Set("Server", SVer) 144 | clip := r.RemoteAddr 145 | speAddr := r.Header.Get("X-Addr") 146 | if speAddr != "" { 147 | clip = speAddr 148 | } 149 | qzone := r.Header.Get("X-Query-Zone") 150 | if qzone == "yes" { 151 | zonename := ipdisp.QueryZone(clip) 152 | w.Write([]byte(zonename)) 153 | } else { 154 | //fmt.Printf("clip: %s\n", r.Host) 155 | ipdaction := ipdAction{} 156 | ipdaction.action = "query" 157 | p := make(map[string]string) 158 | p["clip"] = clip 159 | p["host"] = r.Host 160 | p["path"] = r.URL.Path 161 | ipdaction.param = p 162 | //ip, _, _ := ipdisp.Query(clip, r.Host, r.URL.Path) 163 | ipdActionCH <- ipdaction 164 | var ip string 165 | //var zonename string 166 | select { 167 | case ipdaction = <-ipdResultCH: 168 | result := ipdaction.result.(map[string]string) 169 | ip = result["ip"] 170 | } 171 | w.Header().Set("Location", "http://"+ip+r.URL.Path) 172 | w.WriteHeader(http.StatusFound) 173 | } 174 | }) 175 | mux.HandleFunc("/ipdadmin/set", func(w http.ResponseWriter, r *http.Request) { 176 | actionLock.Lock() 177 | defer actionLock.Unlock() 178 | if err := r.ParseForm(); err != nil { 179 | w.WriteHeader(http.StatusNotFound) 180 | return 181 | } 182 | queryparam := r.PostForm 183 | w.Header().Set("Server", SVer) 184 | ipdaction := ipdAction{} 185 | ipdaction.param = map[string]string{"host": "", "object": "", "value": ""} 186 | for k := range ipdaction.param { 187 | //fmt.Printf("pp: %s %s\n", k, q) 188 | v, ok := queryparam[k] 189 | if ok { 190 | if k == "value" { 191 | ipdaction.result = v 192 | continue 193 | } 194 | ipdaction.param[k] = v[0] 195 | } 196 | } 197 | ipdaction.action = "set" 198 | ipdActionCH <- ipdaction 199 | var rst bool 200 | select { 201 | case ipdaction = <-ipdResultCH: 202 | rst = ipdaction.result.(bool) 203 | } 204 | 205 | if rst == true { 206 | w.WriteHeader(http.StatusOK) 207 | } else { 208 | w.WriteHeader(http.StatusNotFound) 209 | } 210 | }) 211 | mux.HandleFunc("/ipdadmin/get", func(w http.ResponseWriter, r *http.Request) { 212 | actionLock.Lock() 213 | defer actionLock.Unlock() 214 | w.Header().Set("Server", SVer) 215 | queryparam := r.URL.Query() 216 | ipdaction := ipdAction{} 217 | ipdaction.param = map[string]string{"host": "", "node": "", "last": ""} 218 | for k := range ipdaction.param { 219 | //fmt.Printf("pp: %s %s\n", k, q) 220 | v, ok := queryparam[k] 221 | if ok { 222 | ipdaction.param[k] = v[0] 223 | } 224 | } 225 | ipdaction.action = "get" 226 | ipdActionCH <- ipdaction 227 | var count uint64 228 | select { 229 | case ipdaction = <-ipdResultCH: 230 | count = ipdaction.result.(uint64) 231 | } 232 | w.Write([]byte(strconv.FormatUint(count, 32))) 233 | }) 234 | return mux 235 | } 236 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # IPDispatch 2 | 根据用户端IP进行访问调度。就是通常说的302调度。 3 | 4 | ## 功能: 5 | 1. 调度方式:基于一致性哈希的调度,轮询,权重。 6 | 2. 通过流量调度,实现节点过载保护。当节点流量达到峰值时,将一部分流量调度给其他节点或第三方CDN。 7 | 3. 调度系统的过载保护。(未开发) 8 | 4. 提供API,获取或变更配置与状态。 9 | 5. 支持多域名配置,每个域名不同的调度策略。支持别名。 10 | 6. 支持gracfuldown。支持不中断服务的情况下升级程序(二进制包).类似于nginx的Upgrading To a New Binary On The Fly. 11 | 12 | 主配置项为:IPDisp-path。设定配置目录(绝对路径)。 13 | ./IPDispatch -c IPDisp-path 14 | 15 | ## 配置目录格式: 16 | 1. $IPDisp-path/ipz:IP地址库。 17 | 2. $IPDisp-path/hostname/view.conf:区域+运营商与节点的对应关系,也就是调度策略。 18 | 3. $IPDisp-path/hostname/node.conf:调度配置信息。
19 | [conf]
20 | alias=abc.test.com
21 | [node-name]
22 | server=ip,id,weight,status
23 | server=ip1,id1,weight,status
24 | \#weight:必须是百分制,所有server的weight相加等于100。
25 | bw=当前使用带宽(MB)
26 | maxbw=节点带宽(MB)
27 | freebw=剩余带宽(MB)。小于此值时,将会向overflow2node切流量
28 | overflow2node=node-name
29 | status=up|down
30 | balance=h|r|A。h:一致性哈希调度;r:轮训;A:随机数调度。
31 | 32 | ## 接口: 33 | 1. 设置节点或服务器相关设置。
34 | \# 地址:/ipdadmin/set
35 | \# 请求方式:POST
36 | \# 参数:
37 | \# host:指定需要操作的域名
38 | \# object:设置需要操作的对象,有两种值:node或server。
39 | \# value:需要设置的值。对于节点可以设置:bw和status;对于服务器可以设置weight和status。value参数可以有多个。
40 | \# 响应结果:返回状态码为200代表成功,其他为设置失败 41 | -------------------------------------------------------------------------------- /conf/ipz: -------------------------------------------------------------------------------- 1 | 1.0.0.0/8;zone1|cp1 2 | 2.0.0.0/8;zone2|cp2 3 | 3.0.0.0/8;zone3|cp3 4 | 4.0.0.0/8;zone4|cp4 5 | 5.0.0.0/8;zone5|cp5 6 | 6.0.0.0/8;zone6|cp6 7 | 7.0.0.0/8;zone7|cp7 8 | 8.0.0.0/8;zone8|cp8 9 | 9.0.0.0/8;zone9|cp9 10 | 10.0.0.0/8;zone10|cp10 11 | 11.0.0.0/8;zone11|cp11 12 | 12.0.0.0/8;zone12|cp12 13 | 13.0.0.0/8;zone13|cp13 14 | 14.0.0.0/8;zone14|cp14 15 | 15.0.0.0/8;zone15|cp15 16 | 16.0.0.0/8;zone16|cp16 17 | 17.0.0.0/8;zone17|cp17 18 | 18.0.0.0/8;zone18|cp18 19 | 19.0.0.0/8;zone19|cp19 20 | 20.0.0.0/8;zone20|cp20 21 | 21.0.0.0/8;zone21|cp21 22 | 22.0.0.0/8;zone22|cp22 23 | 23.0.0.0/8;zone23|cp23 24 | 24.0.0.0/8;zone24|cp24 25 | 25.0.0.0/8;zone25|cp25 26 | 26.0.0.0/8;zone26|cp26 27 | 27.0.0.0/8;zone27|cp27 28 | 28.0.0.0/8;zone28|cp28 29 | 29.0.0.0/8;zone29|cp29 30 | 30.0.0.0/8;zone30|cp30 31 | 31.0.0.0/8;zone31|cp31 32 | 32.0.0.0/8;zone32|cp32 33 | 33.0.0.0/8;zone33|cp33 34 | 34.0.0.0/8;zone34|cp34 35 | 35.0.0.0/8;zone35|cp35 36 | 36.0.0.0/8;zone36|cp36 37 | 37.0.0.0/8;zone37|cp37 38 | 38.0.0.0/8;zone38|cp38 39 | 39.0.0.0/8;zone39|cp39 40 | 40.0.0.0/8;zone40|cp40 41 | 41.0.0.0/8;zone41|cp41 42 | 42.0.0.0/8;zone42|cp42 43 | 43.0.0.0/8;zone43|cp43 44 | 44.0.0.0/8;zone44|cp44 45 | 45.0.0.0/8;zone45|cp45 46 | 46.0.0.0/8;zone46|cp46 47 | 47.0.0.0/8;zone47|cp47 48 | 48.0.0.0/8;zone48|cp48 49 | 49.0.0.0/8;zone49|cp49 50 | 50.0.0.0/8;zone50|cp50 51 | 51.0.0.0/8;zone51|cp51 52 | 52.0.0.0/8;zone52|cp52 53 | 53.0.0.0/8;zone53|cp53 54 | 54.0.0.0/8;zone54|cp54 55 | 55.0.0.0/8;zone55|cp55 56 | 56.0.0.0/8;zone56|cp56 57 | 57.0.0.0/8;zone57|cp57 58 | 58.0.0.0/8;zone58|cp58 59 | 59.0.0.0/8;zone59|cp59 60 | 60.0.0.0/8;zone60|cp60 61 | 61.0.0.0/8;zone61|cp61 62 | 62.0.0.0/8;zone62|cp62 63 | 63.0.0.0/8;zone63|cp63 64 | 64.0.0.0/8;zone64|cp64 65 | 65.0.0.0/8;zone65|cp65 66 | 66.0.0.0/8;zone66|cp66 67 | 67.0.0.0/8;zone67|cp67 68 | 68.0.0.0/8;zone68|cp68 69 | 69.0.0.0/8;zone69|cp69 70 | 70.0.0.0/8;zone70|cp70 71 | 71.0.0.0/8;zone71|cp71 72 | 72.0.0.0/8;zone72|cp72 73 | 73.0.0.0/8;zone73|cp73 74 | 74.0.0.0/8;zone74|cp74 75 | 75.0.0.0/8;zone75|cp75 76 | 76.0.0.0/8;zone76|cp76 77 | 77.0.0.0/8;zone77|cp77 78 | 78.0.0.0/8;zone78|cp78 79 | 79.0.0.0/8;zone79|cp79 80 | 80.0.0.0/8;zone80|cp80 81 | 81.0.0.0/8;zone81|cp81 82 | 82.0.0.0/8;zone82|cp82 83 | 83.0.0.0/8;zone83|cp83 84 | 84.0.0.0/8;zone84|cp84 85 | 85.0.0.0/8;zone85|cp85 86 | 86.0.0.0/8;zone86|cp86 87 | 87.0.0.0/8;zone87|cp87 88 | 88.0.0.0/8;zone88|cp88 89 | 89.0.0.0/8;zone89|cp89 90 | 90.0.0.0/8;zone90|cp90 91 | 91.0.0.0/8;zone91|cp91 92 | 92.0.0.0/8;zone92|cp92 93 | 93.0.0.0/8;zone93|cp93 94 | 94.0.0.0/8;zone94|cp94 95 | 95.0.0.0/8;zone95|cp95 96 | 96.0.0.0/8;zone96|cp96 97 | 97.0.0.0/8;zone97|cp97 98 | 98.0.0.0/8;zone98|cp98 99 | 99.0.0.0/8;zone99|cp99 100 | 100.0.0.0/8;zone100|cp100 101 | 101.0.0.0/8;zone101|cp101 102 | 102.0.0.0/8;zone102|cp102 103 | 103.0.0.0/8;zone103|cp103 104 | 104.0.0.0/8;zone104|cp104 105 | 105.0.0.0/8;zone105|cp105 106 | 106.0.0.0/8;zone106|cp106 107 | 107.0.0.0/8;zone107|cp107 108 | 108.0.0.0/8;zone108|cp108 109 | 109.0.0.0/8;zone109|cp109 110 | 110.0.0.0/8;zone110|cp110 111 | 111.0.0.0/8;zone111|cp111 112 | 112.0.0.0/8;zone112|cp112 113 | 113.0.0.0/8;zone113|cp113 114 | 114.0.0.0/8;zone114|cp114 115 | 115.0.0.0/8;zone115|cp115 116 | 116.0.0.0/8;zone116|cp116 117 | 117.0.0.0/8;zone117|cp117 118 | 118.0.0.0/8;zone118|cp118 119 | 119.0.0.0/8;zone119|cp119 120 | 120.0.0.0/8;zone120|cp120 121 | 121.0.0.0/8;zone121|cp121 122 | 122.0.0.0/8;zone122|cp122 123 | 123.0.0.0/8;zone123|cp123 124 | 124.0.0.0/8;zone124|cp124 125 | 125.0.0.0/8;zone125|cp125 126 | 126.0.0.0/8;zone126|cp126 127 | 127.0.0.0/8;zone127|cp127 128 | 128.0.0.0/8;zone128|cp128 129 | 129.0.0.0/8;zone129|cp129 130 | 130.0.0.0/8;zone130|cp130 131 | 131.0.0.0/8;zone131|cp131 132 | 132.0.0.0/8;zone132|cp132 133 | 133.0.0.0/8;zone133|cp133 134 | 134.0.0.0/8;zone134|cp134 135 | 135.0.0.0/8;zone135|cp135 136 | 136.0.0.0/8;zone136|cp136 137 | 137.0.0.0/8;zone137|cp137 138 | 138.0.0.0/8;zone138|cp138 139 | 139.0.0.0/8;zone139|cp139 140 | 140.0.0.0/8;zone140|cp140 141 | 141.0.0.0/8;zone141|cp141 142 | 142.0.0.0/8;zone142|cp142 143 | 143.0.0.0/8;zone143|cp143 144 | 144.0.0.0/8;zone144|cp144 145 | 145.0.0.0/8;zone145|cp145 146 | 146.0.0.0/8;zone146|cp146 147 | 147.0.0.0/8;zone147|cp147 148 | 148.0.0.0/8;zone148|cp148 149 | 149.0.0.0/8;zone149|cp149 150 | 150.0.0.0/8;zone150|cp150 151 | 151.0.0.0/8;zone151|cp151 152 | 152.0.0.0/8;zone152|cp152 153 | 153.0.0.0/8;zone153|cp153 154 | 154.0.0.0/8;zone154|cp154 155 | 155.0.0.0/8;zone155|cp155 156 | 156.0.0.0/8;zone156|cp156 157 | 157.0.0.0/8;zone157|cp157 158 | 158.0.0.0/8;zone158|cp158 159 | 159.0.0.0/8;zone159|cp159 160 | 160.0.0.0/8;zone160|cp160 161 | 161.0.0.0/8;zone161|cp161 162 | 162.0.0.0/8;zone162|cp162 163 | 163.0.0.0/8;zone163|cp163 164 | 164.0.0.0/8;zone164|cp164 165 | 165.0.0.0/8;zone165|cp165 166 | 166.0.0.0/8;zone166|cp166 167 | 167.0.0.0/8;zone167|cp167 168 | 168.0.0.0/8;zone168|cp168 169 | 169.0.0.0/8;zone169|cp169 170 | 170.0.0.0/8;zone170|cp170 171 | 171.0.0.0/8;zone171|cp171 172 | 172.0.0.0/8;zone172|cp172 173 | 173.0.0.0/8;zone173|cp173 174 | 174.0.0.0/8;zone174|cp174 175 | 175.0.0.0/8;zone175|cp175 176 | 176.0.0.0/8;zone176|cp176 177 | 177.0.0.0/8;zone177|cp177 178 | 178.0.0.0/8;zone178|cp178 179 | 179.0.0.0/8;zone179|cp179 180 | 180.0.0.0/8;zone180|cp180 181 | 181.0.0.0/8;zone181|cp181 182 | 182.0.0.0/8;zone182|cp182 183 | 183.0.0.0/8;zone183|cp183 184 | 184.0.0.0/8;zone184|cp184 185 | 185.0.0.0/8;zone185|cp185 186 | 186.0.0.0/8;zone186|cp186 187 | 187.0.0.0/8;zone187|cp187 188 | 188.0.0.0/8;zone188|cp188 189 | 189.0.0.0/8;zone189|cp189 190 | 190.0.0.0/8;zone190|cp190 191 | 191.0.0.0/8;zone191|cp191 192 | 192.0.0.0/8;zone192|cp192 193 | 193.0.0.0/8;zone193|cp193 194 | 194.0.0.0/8;zone194|cp194 195 | 195.0.0.0/8;zone195|cp195 196 | 196.0.0.0/8;zone196|cp196 197 | 197.0.0.0/8;zone197|cp197 198 | 198.0.0.0/8;zone198|cp198 199 | 199.0.0.0/8;zone199|cp199 200 | 200.0.0.0/8;zone200|cp200 201 | 201.0.0.0/8;zone201|cp201 202 | 202.0.0.0/8;zone202|cp202 203 | 203.0.0.0/8;zone203|cp203 204 | 204.0.0.0/8;zone204|cp204 205 | 205.0.0.0/8;zone205|cp205 206 | 206.0.0.0/8;zone206|cp206 207 | 207.0.0.0/8;zone207|cp207 208 | 208.0.0.0/8;zone208|cp208 209 | 209.0.0.0/8;zone209|cp209 210 | 210.0.0.0/8;zone210|cp210 211 | 211.0.0.0/8;zone211|cp211 212 | 212.0.0.0/8;zone212|cp212 213 | 213.0.0.0/8;zone213|cp213 214 | 214.0.0.0/8;zone214|cp214 215 | 215.0.0.0/8;zone215|cp215 216 | 216.0.0.0/8;zone216|cp216 217 | 217.0.0.0/8;zone217|cp217 218 | 218.0.0.0/8;zone218|cp218 219 | 219.0.0.0/8;zone219|cp219 220 | 220.0.0.0/8;zone220|cp220 221 | 221.0.0.0/8;zone221|cp221 222 | 222.0.0.0/8;zone222|cp222 223 | 223.0.0.0/8;zone223|cp223 224 | 224.0.0.0/8;zone224|cp224 225 | 225.0.0.0/8;zone225|cp225 226 | 226.0.0.0/8;zone226|cp226 227 | 227.0.0.0/8;zone227|cp227 228 | 228.0.0.0/8;zone228|cp228 229 | 229.0.0.0/8;zone229|cp229 230 | 230.0.0.0/8;zone230|cp230 231 | 231.0.0.0/8;zone231|cp231 232 | 232.0.0.0/8;zone232|cp232 233 | 233.0.0.0/8;zone233|cp233 234 | 234.0.0.0/8;zone234|cp234 235 | 235.0.0.0/8;zone235|cp235 236 | 236.0.0.0/8;zone236|cp236 237 | 237.0.0.0/8;zone237|cp237 238 | 238.0.0.0/8;zone238|cp238 239 | 239.0.0.0/8;zone239|cp239 240 | 240.0.0.0/8;zone240|cp240 241 | 241.0.0.0/8;zone241|cp241 242 | 242.0.0.0/8;zone242|cp242 243 | 243.0.0.0/8;zone243|cp243 244 | 244.0.0.0/8;zone244|cp244 245 | 245.0.0.0/8;zone245|cp245 246 | 246.0.0.0/8;zone246|cp246 247 | 247.0.0.0/8;zone247|cp247 248 | 248.0.0.0/8;zone248|cp248 249 | 249.0.0.0/8;zone249|cp249 250 | 250.0.0.0/8;zone250|cp250 251 | 251.0.0.0/8;zone251|cp251 252 | 252.0.0.0/8;zone252|cp252 253 | 253.0.0.0/8;zone253|cp253 254 | 254.0.0.0/8;zone254|cp254 255 | -------------------------------------------------------------------------------- /conf/www.daledi.net/node.conf: -------------------------------------------------------------------------------- 1 | [dale] 2 | server=192.168.1.10 0 20 3 | server=192.168.1.11 1 30 4 | server=192.168.1.12 2 15 5 | server=192.168.1.13 3 10 6 | server=192.168.1.14 4 25 7 | balance=h 8 | 9 | -------------------------------------------------------------------------------- /conf/www.daledi.net/view.conf: -------------------------------------------------------------------------------- 1 | zone1|cp1;dale 2 | zone2|cp2;dale 3 | zone3|cp3;dale 4 | zone4|cp4;dale 5 | zone5|cp5;dale 6 | zone6|cp6;dale 7 | zone7|cp7;dale 8 | zone8|cp8;dale 9 | zone9|cp9;dale 10 | zone10|cp10;dale 11 | zone11|cp11;dale 12 | zone12|cp12;dale 13 | zone13|cp13;dale 14 | zone14|cp14;dale 15 | zone15|cp15;dale 16 | zone16|cp16;dale 17 | zone17|cp17;dale 18 | zone18|cp18;dale 19 | zone19|cp19;dale 20 | zone20|cp20;dale 21 | zone21|cp21;dale 22 | zone22|cp22;dale 23 | zone23|cp23;dale 24 | zone24|cp24;dale 25 | zone25|cp25;dale 26 | zone26|cp26;dale 27 | zone27|cp27;dale 28 | zone28|cp28;dale 29 | zone29|cp29;dale 30 | zone30|cp30;dale 31 | zone31|cp31;dale 32 | zone32|cp32;dale 33 | zone33|cp33;dale 34 | zone34|cp34;dale 35 | zone35|cp35;dale 36 | zone36|cp36;dale 37 | zone37|cp37;dale 38 | zone38|cp38;dale 39 | zone39|cp39;dale 40 | zone40|cp40;dale 41 | zone41|cp41;dale 42 | zone42|cp42;dale 43 | zone43|cp43;dale 44 | zone44|cp44;dale 45 | zone45|cp45;dale 46 | zone46|cp46;dale 47 | zone47|cp47;dale 48 | zone48|cp48;dale 49 | zone49|cp49;dale 50 | zone50|cp50;dale 51 | zone51|cp51;dale 52 | zone52|cp52;dale 53 | zone53|cp53;dale 54 | zone54|cp54;dale 55 | zone55|cp55;dale 56 | zone56|cp56;dale 57 | zone57|cp57;dale 58 | zone58|cp58;dale 59 | zone59|cp59;dale 60 | zone60|cp60;dale 61 | zone61|cp61;dale 62 | zone62|cp62;dale 63 | zone63|cp63;dale 64 | zone64|cp64;dale 65 | zone65|cp65;dale 66 | zone66|cp66;dale 67 | zone67|cp67;dale 68 | zone68|cp68;dale 69 | zone69|cp69;dale 70 | zone70|cp70;dale 71 | zone71|cp71;dale 72 | zone72|cp72;dale 73 | zone73|cp73;dale 74 | zone74|cp74;dale 75 | zone75|cp75;dale 76 | zone76|cp76;dale 77 | zone77|cp77;dale 78 | zone78|cp78;dale 79 | zone79|cp79;dale 80 | zone80|cp80;dale 81 | zone81|cp81;dale 82 | zone82|cp82;dale 83 | zone83|cp83;dale 84 | zone84|cp84;dale 85 | zone85|cp85;dale 86 | zone86|cp86;dale 87 | zone87|cp87;dale 88 | zone88|cp88;dale 89 | zone89|cp89;dale 90 | zone90|cp90;dale 91 | zone91|cp91;dale 92 | zone92|cp92;dale 93 | zone93|cp93;dale 94 | zone94|cp94;dale 95 | zone95|cp95;dale 96 | zone96|cp96;dale 97 | zone97|cp97;dale 98 | zone98|cp98;dale 99 | zone99|cp99;dale 100 | zone100|cp100;dale 101 | zone101|cp101;dale 102 | zone102|cp102;dale 103 | zone103|cp103;dale 104 | zone104|cp104;dale 105 | zone105|cp105;dale 106 | zone106|cp106;dale 107 | zone107|cp107;dale 108 | zone108|cp108;dale 109 | zone109|cp109;dale 110 | zone110|cp110;dale 111 | zone111|cp111;dale 112 | zone112|cp112;dale 113 | zone113|cp113;dale 114 | zone114|cp114;dale 115 | zone115|cp115;dale 116 | zone116|cp116;dale 117 | zone117|cp117;dale 118 | zone118|cp118;dale 119 | zone119|cp119;dale 120 | zone120|cp120;dale 121 | zone121|cp121;dale 122 | zone122|cp122;dale 123 | zone123|cp123;dale 124 | zone124|cp124;dale 125 | zone125|cp125;dale 126 | zone126|cp126;dale 127 | zone127|cp127;dale 128 | zone128|cp128;dale 129 | zone129|cp129;dale 130 | zone130|cp130;dale 131 | zone131|cp131;dale 132 | zone132|cp132;dale 133 | zone133|cp133;dale 134 | zone134|cp134;dale 135 | zone135|cp135;dale 136 | zone136|cp136;dale 137 | zone137|cp137;dale 138 | zone138|cp138;dale 139 | zone139|cp139;dale 140 | zone140|cp140;dale 141 | zone141|cp141;dale 142 | zone142|cp142;dale 143 | zone143|cp143;dale 144 | zone144|cp144;dale 145 | zone145|cp145;dale 146 | zone146|cp146;dale 147 | zone147|cp147;dale 148 | zone148|cp148;dale 149 | zone149|cp149;dale 150 | zone150|cp150;dale 151 | zone151|cp151;dale 152 | zone152|cp152;dale 153 | zone153|cp153;dale 154 | zone154|cp154;dale 155 | zone155|cp155;dale 156 | zone156|cp156;dale 157 | zone157|cp157;dale 158 | zone158|cp158;dale 159 | zone159|cp159;dale 160 | zone160|cp160;dale 161 | zone161|cp161;dale 162 | zone162|cp162;dale 163 | zone163|cp163;dale 164 | zone164|cp164;dale 165 | zone165|cp165;dale 166 | zone166|cp166;dale 167 | zone167|cp167;dale 168 | zone168|cp168;dale 169 | zone169|cp169;dale 170 | zone170|cp170;dale 171 | zone171|cp171;dale 172 | zone172|cp172;dale 173 | zone173|cp173;dale 174 | zone174|cp174;dale 175 | zone175|cp175;dale 176 | zone176|cp176;dale 177 | zone177|cp177;dale 178 | zone178|cp178;dale 179 | zone179|cp179;dale 180 | zone180|cp180;dale 181 | zone181|cp181;dale 182 | zone182|cp182;dale 183 | zone183|cp183;dale 184 | zone184|cp184;dale 185 | zone185|cp185;dale 186 | zone186|cp186;dale 187 | zone187|cp187;dale 188 | zone188|cp188;dale 189 | zone189|cp189;dale 190 | zone190|cp190;dale 191 | zone191|cp191;dale 192 | zone192|cp192;dale 193 | zone193|cp193;dale 194 | zone194|cp194;dale 195 | zone195|cp195;dale 196 | zone196|cp196;dale 197 | zone197|cp197;dale 198 | zone198|cp198;dale 199 | zone199|cp199;dale 200 | zone200|cp200;dale 201 | zone201|cp201;dale 202 | zone202|cp202;dale 203 | zone203|cp203;dale 204 | zone204|cp204;dale 205 | zone205|cp205;dale 206 | zone206|cp206;dale 207 | zone207|cp207;dale 208 | zone208|cp208;dale 209 | zone209|cp209;dale 210 | zone210|cp210;dale 211 | zone211|cp211;dale 212 | zone212|cp212;dale 213 | zone213|cp213;dale 214 | zone214|cp214;dale 215 | zone215|cp215;dale 216 | zone216|cp216;dale 217 | zone217|cp217;dale 218 | zone218|cp218;dale 219 | zone219|cp219;dale 220 | zone220|cp220;dale 221 | zone221|cp221;dale 222 | zone222|cp222;dale 223 | zone223|cp223;dale 224 | zone224|cp224;dale 225 | zone225|cp225;dale 226 | zone226|cp226;dale 227 | zone227|cp227;dale 228 | zone228|cp228;dale 229 | zone229|cp229;dale 230 | zone230|cp230;dale 231 | zone231|cp231;dale 232 | zone232|cp232;dale 233 | zone233|cp233;dale 234 | zone234|cp234;dale 235 | zone235|cp235;dale 236 | zone236|cp236;dale 237 | zone237|cp237;dale 238 | zone238|cp238;dale 239 | zone239|cp239;dale 240 | zone240|cp240;dale 241 | zone241|cp241;dale 242 | zone242|cp242;dale 243 | zone243|cp243;dale 244 | zone244|cp244;dale 245 | zone245|cp245;dale 246 | zone246|cp246;dale 247 | zone247|cp247;dale 248 | zone248|cp248;dale 249 | zone249|cp249;dale 250 | zone250|cp250;dale 251 | zone251|cp251;dale 252 | zone252|cp252;dale 253 | zone253|cp253;dale 254 | zone254|cp254;dale 255 | -------------------------------------------------------------------------------- /daemon.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "path/filepath" 7 | "syscall" 8 | ) 9 | 10 | const ( 11 | //DAEMONKEY 环境变量 12 | DAEMONKEY = "IPDispatch" 13 | // DAEMONVALUE 环境变量-值 14 | DAEMONVALUE = "1" 15 | ) 16 | 17 | // Daemon 启动后台进程 18 | func Daemon(pidfile *string, ifile []*os.File, credential *syscall.Credential) (err error) { 19 | if os.Getenv("LISTEN_FDS") != "" { 20 | pidFile(pidfile) 21 | return 22 | } 23 | if os.Getenv(DAEMONKEY) == DAEMONVALUE { 24 | pidFile(pidfile) 25 | return 26 | } 27 | var originalWD, _ = os.Getwd() 28 | attr := &os.ProcAttr{ 29 | Dir: originalWD, 30 | Env: []string{DAEMONKEY + "=" + DAEMONVALUE}, 31 | Files: ifile, 32 | Sys: &syscall.SysProcAttr{ 33 | //Chroot: d.Chroot, 34 | Credential: credential, 35 | //Setsid: true, 36 | }, 37 | } 38 | var abspath string 39 | var child *os.Process 40 | if abspath, err = filepath.Abs(os.Args[0]); err != nil { 41 | return 42 | } 43 | if child, err = os.StartProcess(abspath, os.Args, attr); err != nil { 44 | return 45 | } 46 | // ppid := os.Getppid() 47 | // if os.Getenv("LISTEN_FDS") != "" { 48 | // if err := syscall.Kill(ppid, syscall.SIGTERM); err != nil { 49 | // return fmt.Errorf("failed to close parent: %s", err) 50 | // } 51 | // } 52 | if child != nil && os.Getenv("LISTEN_FDS") == "" { 53 | os.Exit(0) 54 | } 55 | return 56 | } 57 | 58 | func pidFile(pidfile *string) (err error) { 59 | if err = os.MkdirAll(filepath.Dir(*pidfile), os.FileMode(0755)); err != nil { 60 | return 61 | } 62 | var f *os.File 63 | if f, err = os.OpenFile(*pidfile, os.O_RDWR|os.O_CREATE, 0600); err != nil { 64 | return 65 | } 66 | _, err = fmt.Fprintf(f, "%d", os.Getpid()) //os.Getpid() 67 | if err != nil { 68 | return 69 | } 70 | err = f.Close() 71 | if err != nil { 72 | return 73 | } 74 | return 75 | } 76 | -------------------------------------------------------------------------------- /ipzone/ipzone.go: -------------------------------------------------------------------------------- 1 | package ipzone 2 | 3 | import ( 4 | "bufio" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "math/rand" 10 | "net" 11 | "os" 12 | "sort" 13 | "strconv" 14 | "strings" 15 | "sync" 16 | "time" 17 | 18 | "github.com/dale-di/ipdispatch/rbtree" 19 | ) 20 | 21 | // Zone 是IP段与地域运营商的对应关系 22 | type Zone struct { 23 | ipmin uint32 24 | ipmax uint32 25 | name string 26 | id int 27 | } 28 | 29 | // Node 节点信息 30 | type Node struct { 31 | servers []*Server 32 | serverID map[string]int 33 | curserver *Server 34 | servercount int 35 | balance byte 36 | bw int 37 | maxbw int 38 | freebw int 39 | name string 40 | id int 41 | vhost string 42 | status int 43 | overflow2node string 44 | overflow2nodeid int 45 | swtree *rbtree.Tree 46 | sw []int 47 | reqlastmin uint64 //上一分钟请求数 48 | reqmin uint64 49 | reqcount uint64 //分配到此节点的请求计数 50 | } 51 | 52 | //Server 服务器信息 53 | type Server struct { 54 | next *Server 55 | ip string 56 | weight int 57 | weightstr string 58 | id int 59 | status int 60 | } 61 | 62 | //ServerWeight 服务器权重信息 63 | type ServerWeight struct { 64 | server *Server 65 | keymin uint32 66 | keymax uint32 67 | key uint32 68 | } 69 | 70 | //Vhost 虚拟主机的配置信息 71 | type Vhost struct { 72 | id int 73 | name string 74 | zone2node [1000]int 75 | nodes []*Node 76 | nodeID map[string]int 77 | defaultNode int 78 | reqcount uint64 79 | } 80 | 81 | //IPDisp IP调度配置入口 82 | type IPDisp struct { 83 | zoneID map[string]int 84 | zoneMax int 85 | vhosts map[string]*Vhost 86 | rbtree *rbtree.Tree 87 | mutex sync.Mutex 88 | reqcount uint64 89 | othercount uint64 90 | } 91 | 92 | const ( 93 | //swMAX 设置权重最大值 94 | swMAX = 10000 95 | ) 96 | 97 | var serverstat = map[string]int{"up": 0, "down": 2, "backup": 4} 98 | 99 | //New 初始化IPDisp 100 | func New() *IPDisp { 101 | ipdisp := &IPDisp{} 102 | ipdisp.zoneID = make(map[string]int) 103 | ipdisp.vhosts = make(map[string]*Vhost) 104 | ipdisp.reqcount = 0 105 | ipdisp.othercount = 0 106 | return ipdisp 107 | } 108 | 109 | //Name 返回zone的名称 110 | func (zone *Zone) Name() (name string) { 111 | return zone.name 112 | } 113 | 114 | //GetCount 获取统计信息 115 | func (ipdisp *IPDisp) GetCount(host string, node string, last string) (count uint64) { 116 | count = 0 117 | //fmt.Printf("IPDispF: %v\n", *ipdisp) 118 | switch node { 119 | case "none": 120 | vhost, ok := ipdisp.vhosts[host] 121 | if ok == true { 122 | count = vhost.reqcount 123 | } 124 | case "all": 125 | count = ipdisp.reqcount 126 | case "other": 127 | count = ipdisp.othercount 128 | default: 129 | vhost, ok := ipdisp.vhosts[host] 130 | if ok == true { 131 | nid, ok1 := vhost.nodeID[node] 132 | if ok1 == true { 133 | //fmt.Printf("%v\n", vhost.nodes[nid].swtree.String()) 134 | if last != "" { 135 | count = vhost.nodes[nid].reqlastmin 136 | } else { 137 | count = vhost.nodes[nid].reqcount 138 | } 139 | } 140 | } 141 | } 142 | return 143 | } 144 | 145 | //Set 动态变更节点带宽,节点状态,服务器权重,服务器状态 146 | func (ipdisp *IPDisp) Set(host string, object string, values []string) (err error) { 147 | ipdisp.mutex.Lock() 148 | defer ipdisp.mutex.Unlock() 149 | vhost, ok := ipdisp.vhosts[host] 150 | if ok != true { 151 | err = errors.New("Not found " + host) 152 | return 153 | } 154 | err = errors.New("Value is invalid") 155 | switch object { 156 | case "node": 157 | for _, v := range values { 158 | items := strings.Split(v, ":") 159 | if len(items) != 3 { 160 | return 161 | } 162 | // node key value 163 | nid := vhost.nodeID[items[0]] 164 | node := vhost.nodes[nid] 165 | switch items[1] { 166 | case "bw": 167 | bw, ok := strconv.Atoi(items[2]) 168 | if ok != nil { 169 | return 170 | } 171 | node.bw = bw 172 | case "status": 173 | status, ok := serverstat[items[2]] 174 | if ok == false { 175 | return 176 | } 177 | node.status = status 178 | } 179 | } 180 | case "server": 181 | for _, v := range values { 182 | items := strings.Split(v, ":") 183 | if len(items) != 4 { 184 | return 185 | } 186 | nid := vhost.nodeID[items[0]] 187 | node := vhost.nodes[nid] 188 | sid := node.serverID[items[1]] 189 | svr := node.servers[sid] 190 | switch items[2] { 191 | case "weight": 192 | svr.weightstr = items[3] 193 | case "status": 194 | status, ok := serverstat[items[3]] 195 | if ok == false { 196 | return 197 | } 198 | svr.status = status 199 | } 200 | } 201 | } 202 | 203 | return nil 204 | } 205 | 206 | //InetNetwork 将字符串形式的IP转换为无符号整数 207 | func InetNetwork(ipstr string) (ipuint uint32) { 208 | ipuint = 0 209 | ip := net.ParseIP(ipstr) 210 | if ip == nil { 211 | return 212 | } 213 | ipuint += uint32(ip[12]) << 24 214 | ipuint += uint32(ip[13]) << 16 215 | ipuint += uint32(ip[14]) << 8 216 | ipuint += uint32(ip[15]) 217 | return 218 | } 219 | 220 | //Comparator 在红黑树中,用于选择节点的比较方法 221 | func Comparator(a, b interface{}) int { 222 | switch b.(type) { 223 | case Zone: 224 | bZone := b.(Zone) 225 | switch a.(type) { 226 | case uint32: 227 | aIP := a.(uint32) 228 | switch { 229 | case aIP < bZone.ipmin: 230 | return -1 231 | case aIP > bZone.ipmax: 232 | return 1 233 | default: 234 | return 0 235 | } 236 | case Zone: 237 | aZone := a.(Zone) 238 | switch { 239 | case aZone.ipmin > bZone.ipmin: 240 | return 1 241 | case aZone.ipmin < bZone.ipmin: 242 | return -1 243 | default: 244 | return 0 245 | } 246 | default: 247 | return 0 248 | } 249 | case ServerWeight: 250 | bb := b.(ServerWeight) 251 | switch a.(type) { 252 | case uint32: 253 | aa := a.(uint32) 254 | switch { 255 | case aa < bb.keymin: 256 | return -1 257 | case aa > bb.keymax: 258 | return 1 259 | default: 260 | return 0 261 | } 262 | case ServerWeight: 263 | aa := a.(ServerWeight) 264 | switch { 265 | case aa.keymin > bb.keymin: 266 | return 1 267 | case aa.keymin < bb.keymin: 268 | return -1 269 | default: 270 | return 0 271 | } 272 | default: 273 | return 0 274 | } 275 | default: 276 | return 0 277 | } 278 | } 279 | 280 | //file2string 将文件读取到字符串数组 281 | func file2string(fname string) (flines []string, err error) { 282 | cf, err := os.Open(fname) 283 | if err != nil { 284 | return 285 | } 286 | defer cf.Close() 287 | r := bufio.NewReader(cf) 288 | for { 289 | buf, err := r.ReadSlice('\n') 290 | if err == io.EOF { 291 | err = nil 292 | break 293 | } 294 | flines = append(flines, string(buf[0:len(buf)-1])) 295 | } 296 | return 297 | } 298 | 299 | //LoadNode 加载每个host的node配置 300 | func (ipdisp *IPDisp) LoadNode(conf string, vhostname string) (err error) { 301 | var flines []string 302 | flines, err = file2string(conf) 303 | if err != nil { 304 | return 305 | } 306 | 307 | ipdisp.vhosts[vhostname] = &Vhost{} 308 | vhost := ipdisp.vhosts[vhostname] 309 | vhost.nodeID = make(map[string]int) 310 | vhost.defaultNode = 0 311 | vhost.reqcount = 0 312 | nodeid := -1 313 | var cnode *Node 314 | for _, fline := range flines { 315 | flen := len(fline) 316 | if flen < 3 || fline[0] == '#' { 317 | continue 318 | } 319 | if fline[0] == '[' && fline[flen-1] == ']' { 320 | //获取节点名称,初始化节点配置 321 | //if nodeID > -1 { 322 | // cnode.servers[cnode.servercount-1].next = cnode.servers[0] 323 | //} 324 | nodename := string(fline[1 : flen-1]) 325 | cnode = &Node{} 326 | cnode.name = nodename 327 | cnode.status = 0 328 | cnode.servercount = 0 329 | cnode.balance = 'r' 330 | cnode.id = nodeid + 1 331 | cnode.reqmin = 0 332 | cnode.reqlastmin = 0 333 | cnode.reqcount = 0 334 | cnode.freebw = 20 335 | cnode.sw = make([]int, swMAX) 336 | cnode.serverID = make(map[string]int) 337 | cnode.swtree = rbtree.NewWith(Comparator) 338 | vhost.nodes = append(vhost.nodes, cnode) 339 | nodeid++ 340 | vhost.nodeID[nodename] = nodeid 341 | } else { 342 | if nodeid == -1 { 343 | continue 344 | } 345 | cfline := string(fline) 346 | cf := strings.Split(cfline, "=") 347 | if len(cf) != 2 { 348 | continue 349 | } 350 | switch cf[0] { 351 | case "server": 352 | server := &Server{} 353 | server.status = 0 354 | server.weight = 0 355 | server.id = 0 356 | sinfo := strings.Split(cf[1], " ") 357 | server.ip = sinfo[0] 358 | sinfolen := len(sinfo) 359 | switch sinfolen { 360 | case 2: 361 | server.id, err = strconv.Atoi(sinfo[1]) 362 | case 3: 363 | server.id, err = strconv.Atoi(sinfo[1]) 364 | server.weightstr = sinfo[2] 365 | case 4: 366 | server.id, err = strconv.Atoi(sinfo[1]) 367 | server.weightstr = sinfo[2] 368 | server.status = serverstat[sinfo[3]] 369 | } 370 | /* 371 | swcount = swcount + server.weight 372 | */ 373 | cnode.servers = append(cnode.servers, server) 374 | if cnode.servercount == 0 { 375 | cnode.curserver = server 376 | } else { 377 | cnode.servers[cnode.servercount-1].next = server 378 | } 379 | cnode.serverID[server.ip] = server.id 380 | cnode.servercount++ 381 | case "bw": 382 | cnode.bw, err = strconv.Atoi(cf[1]) 383 | case "maxbw": 384 | cnode.maxbw, err = strconv.Atoi(cf[1]) 385 | case "freebw": 386 | cnode.freebw, err = strconv.Atoi(cf[1]) 387 | case "overflow2node": 388 | cnode.overflow2node = cf[1] 389 | case "status": 390 | cnode.status = serverstat[cf[1]] 391 | case "default": 392 | vhost.defaultNode = nodeid 393 | case "balance": 394 | switch cf[1][0] { 395 | case 'h': 396 | cnode.balance = cf[1][0] 397 | case 'r': 398 | cnode.balance = cf[1][0] 399 | case 'w': 400 | cnode.balance = cf[1][0] 401 | case 'A': 402 | cnode.balance = cf[1][0] 403 | case 'a': 404 | cnode.balance = cf[1][0] 405 | default: 406 | err = errors.New(cnode.name + ": balance config is invalid") 407 | return 408 | } 409 | } 410 | } 411 | } 412 | for _, node := range vhost.nodes { 413 | var ok bool 414 | node.overflow2nodeid, ok = vhost.nodeID[node.overflow2node] 415 | if ok == false { 416 | node.overflow2nodeid = -1 417 | } 418 | //使server数组中,server.next首尾相接 419 | node.servers[node.servercount-1].next = node.servers[0] 420 | //添加特定均衡方式:o(only one),代表只有一个server 421 | if len(node.servers) == 1 { 422 | node.balance = 'o' 423 | } 424 | err = node.initbalance() 425 | } 426 | 427 | return 428 | } 429 | 430 | //initbalance 根据服务器配置信息,计算权重分配方式 431 | func (node *Node) initbalance() (err error) { 432 | switch node.balance { 433 | case 'h': 434 | k := 0 435 | swcount := 0 436 | swarray := make([]float64, swMAX) 437 | swmap := make(map[uint32]int) 438 | for id, svr := range node.servers { 439 | for _, swrange := range strings.Split(svr.weightstr, ",") { 440 | swr := strings.Split(swrange, "-") 441 | swrLen := len(swr) 442 | swmin := k + 1 443 | swmax, _ := strconv.Atoi(swr[0]) 444 | swmax = swmax*100 + k 445 | if swrLen == 2 { 446 | swmin = swmax 447 | swmax, _ = strconv.Atoi(swr[1]) 448 | swmax = swmax * 100 449 | } 450 | for i := swmin; i <= swmax; i++ { 451 | hash := Chash(uint32((id+1)*256*32 + (i+1)*563217)) 452 | if swcount > swMAX { 453 | fmt.Fprintf(os.Stderr, node.name+": the total weight too max.") 454 | break 455 | } 456 | svr.weight++ 457 | swarray[i-1] = float64(hash) 458 | swmap[hash] = id 459 | swcount++ 460 | } 461 | k = swmax 462 | } 463 | } 464 | if swcount != swMAX { 465 | err = errors.New("Total weight is not swmax: " + string(swcount)) 466 | return 467 | } 468 | sort.Float64s(swarray) 469 | var kk uint32 470 | kk = 0 471 | for _, v := range swarray { 472 | fv := uint32(v) 473 | swnode := ServerWeight{} 474 | swnode.keymin = kk 475 | swnode.keymax = fv 476 | sid := swmap[fv] 477 | swnode.server = node.servers[sid] 478 | //fmt.Printf("Hash: %v %v %v\n", kk, fv, swnode.server.ip) 479 | node.swtree.Put(swnode) 480 | kk = fv + 1 481 | } 482 | 483 | case 'A': 484 | 485 | for id, svr := range node.servers { 486 | w, _ := strconv.Atoi(svr.weightstr) 487 | svr.weight = w * 100 488 | for i := 0; i < svr.weight; i++ { 489 | r := rand.New(rand.NewSource(time.Now().UnixNano())) 490 | rn := r.Intn(swMAX) 491 | for node.sw[rn] > 0 { 492 | rn = r.Intn(swMAX) 493 | } 494 | node.sw[rn] = id 495 | } 496 | } 497 | case 'a': 498 | swnum := make([]int, node.servercount) 499 | for i := 0; i < node.servercount; i++ { 500 | swnum[i] = 0 501 | } 502 | tt := int(swMAX / node.servercount) 503 | gg := int(tt / 3) 504 | for i := 0; i < swMAX; i++ { 505 | sgn := int(i / (node.servercount * 3)) 506 | sg := i % (node.servercount * 3) 507 | sid := int(sg / 3) 508 | ssw := node.servers[sid].weight 509 | if ssw <= swnum[sid] || swnum[sid] >= tt { 510 | continue 511 | } 512 | swnum[sid]++ 513 | node.sw[i] = sid 514 | if ssw < tt { 515 | cc := tt - ssw 516 | switch { 517 | case (gg-cc < sgn || gg-cc < 0) && sg%3 == 1: 518 | if swnum[sid] > ssw { 519 | swnum[sid]-- 520 | } 521 | case (gg < cc && cc <= gg*2) && gg*2-cc < sgn && sg%3 == 2: 522 | if swnum[sid] > ssw { 523 | swnum[sid]-- 524 | } 525 | case cc > gg*2 && (tt-cc) < sgn && sg%3 == 0: 526 | if swnum[sid] > ssw { 527 | swnum[sid]-- 528 | } 529 | } 530 | } 531 | } 532 | for i := 0; i < swMAX; i++ { 533 | sg := i % (node.servercount * 3) 534 | sgn := int(i / (node.servercount * 3)) 535 | sid := int(sg / 3) 536 | ssw := node.servers[sid].weight 537 | if ssw < tt { 538 | cc := tt - ssw 539 | 540 | switch { 541 | case (gg-cc <= sgn || gg-cc < 0) && sg%3 == 1: 542 | goto BLSW 543 | case (gg < cc && cc <= gg*2) && gg*2-cc <= sgn && sg%3 == 2: 544 | goto BLSW 545 | case cc > gg*2 && (tt-cc) <= sg && sg%3 == 0: 546 | goto BLSW 547 | default: 548 | continue 549 | } 550 | BLSW: 551 | for { 552 | if node.curserver.weight > tt && node.curserver.weight > swnum[node.curserver.id] { 553 | sid = node.curserver.id 554 | node.curserver = node.curserver.next 555 | break 556 | } 557 | node.curserver = node.curserver.next 558 | } 559 | node.sw[i] = sid 560 | swnum[sid]++ 561 | } 562 | } 563 | } 564 | return nil 565 | } 566 | 567 | //LoadView 加载每个host的view配置 568 | func (ipdisp *IPDisp) LoadView(conf string, vhostname string) (err error) { 569 | var flines []string 570 | flines, err = file2string(conf) 571 | if err != nil { 572 | return 573 | } 574 | vhost := ipdisp.vhosts[vhostname] 575 | for _, fline := range flines { 576 | sline := strings.Split(fline, ";") 577 | if len(sline) != 2 { 578 | continue 579 | } 580 | v1, ok1 := ipdisp.zoneID[sline[0]] 581 | v2, ok2 := vhost.nodeID[sline[1]] 582 | if ok1 { 583 | if ok2 { 584 | vhost.zone2node[v1] = v2 585 | } else { 586 | err = errors.New(conf + " not valid node: " + sline[1]) 587 | } 588 | } else { 589 | err = errors.New(conf + " not valid zone: " + sline[0]) 590 | } 591 | } 592 | return 593 | } 594 | 595 | //LoadZone 读取ip地址段,并保存到rbtree中 596 | func (ipdisp *IPDisp) LoadZone(conf string) (err error) { 597 | ipdisp.rbtree = rbtree.NewWith(Comparator) 598 | var flines []string 599 | flines, err = file2string(conf) 600 | if err != nil { 601 | return 602 | } 603 | zoneids := ipdisp.zoneID 604 | ipdisp.zoneMax = 1 605 | for _, fline := range flines { 606 | zone := Zone{} 607 | ipinfo := strings.Split(fline, ";") 608 | if len(ipinfo) != 2 { 609 | continue 610 | } 611 | zone.name = ipinfo[1] 612 | ips := strings.Split(ipinfo[0], "/") 613 | if len(ips) != 2 { 614 | continue 615 | } 616 | m, err := strconv.Atoi(ips[1]) 617 | if err != nil { 618 | continue 619 | } 620 | zone.ipmin = InetNetwork(ips[0]) 621 | mask := (1 << (32 - uint32(m))) - 1 622 | zone.ipmax = zone.ipmin | uint32(mask) 623 | if v, ok := zoneids[zone.name]; ok == true { 624 | zone.id = v 625 | } else { 626 | zoneids[zone.name] = ipdisp.zoneMax 627 | zone.id = ipdisp.zoneMax 628 | ipdisp.zoneMax++ 629 | } 630 | ipdisp.rbtree.Put(zone) 631 | //fmt.Printf("%v %v %v\n",ipzone.ipmin,ipzone.ipmax,ipzone.Zone) 632 | } 633 | return 634 | } 635 | 636 | //Init 读取配置文件,并加载到IPDisp 637 | func (ipdisp *IPDisp) Init(cfpath string) (err error) { 638 | err = ipdisp.LoadZone(cfpath + "/ipz") 639 | if err != nil { 640 | fmt.Printf("error: %v\n", err) 641 | return 642 | } 643 | var dirs []os.FileInfo 644 | dirs, err = ioutil.ReadDir(cfpath) 645 | if err != nil { 646 | return 647 | } 648 | for _, dir := range dirs { 649 | if dir.IsDir() { 650 | //fmt.Printf("%s/%s\n", cfpath, dir.Name()) 651 | err = ipdisp.LoadNode(cfpath+"/"+dir.Name()+"/node.conf", dir.Name()) 652 | if err != nil { 653 | return err 654 | } 655 | err = ipdisp.LoadView(cfpath+"/"+dir.Name()+"/view.conf", dir.Name()) 656 | if err != nil { 657 | return err 658 | } 659 | } 660 | } 661 | return nil 662 | } 663 | 664 | //Chash 一致性哈希算法 665 | func Chash(a uint32) uint32 { 666 | a = (a + 0x7ed55d16) + (a << 12) 667 | a = (a ^ 0xc761c23c) ^ (a >> 19) 668 | a = (a + 0x165667b5) + (a << 5) 669 | a = (a + 0xd3a2646c) ^ (a << 9) 670 | a = (a + 0xfd7046c5) + (a << 3) 671 | a = (a ^ 0xb55a4f09) ^ (a >> 16) 672 | return a * 3221225474 673 | } 674 | 675 | //HashStr 将字符串转换为无符号整数 676 | func HashStr(hashstr string) uint32 { 677 | strlen := len(hashstr) 678 | var hash uint32 679 | for i := 0; i < strlen; i++ { 680 | hash = uint32(hashstr[i]) + (hash << 6) + (hash << 16) - hash 681 | } 682 | return Chash(hash) 683 | } 684 | 685 | //QueryZone 查找IP所在的区域 686 | func (ipdisp *IPDisp) QueryZone(clip string) string { 687 | ip := InetNetwork(clip) 688 | rbnode, ok := ipdisp.rbtree.Get(ip) 689 | if ok == true { 690 | ipz := rbnode.(Zone) 691 | return ipz.name 692 | } 693 | return "" 694 | } 695 | 696 | //Query 根据客户端IP,host,调度字符串(通常可以用url)计算调度目标 697 | func (ipdisp *IPDisp) Query(clip string, host string, hashstr string) (string, string, error) { 698 | //fmt.Printf("IPDisp: %v\n", *ipdisp) 699 | ipdisp.reqcount++ 700 | var err error 701 | vhost, ok := ipdisp.vhosts[host] 702 | if ok != true { 703 | ipdisp.othercount++ 704 | err = errors.New("Not found " + host) 705 | return "", "", err 706 | } 707 | vhost.reqcount++ 708 | var node *Node 709 | zonename := "None" 710 | nodeid := vhost.defaultNode 711 | ip := InetNetwork(clip) 712 | if ip == 0 { 713 | err = errors.New("Not valid ip: " + clip) 714 | return "", "", err 715 | } 716 | node = vhost.nodes[nodeid] 717 | //查找IP所属区域 718 | rbnode, ok := ipdisp.rbtree.Get(ip) 719 | if ok == true { 720 | ipz := rbnode.(Zone) 721 | zonename = ipz.name 722 | nodeid = vhost.zone2node[ipz.id] 723 | node = vhost.nodes[nodeid] 724 | } 725 | //如果节点的状态为down,以overflow节点替换,如果没有overflow节点,查找其他可用节点替换 726 | if node.status != 0 { 727 | if node.overflow2nodeid == -1 { 728 | for node.status != 0 { 729 | nid := node.id + 1 730 | node = vhost.nodes[nid] 731 | } 732 | } else { 733 | node = vhost.nodes[node.overflow2nodeid] 734 | } 735 | } 736 | //判断节点带宽使用,超过阈值,向overflow2node切流量 737 | if node.maxbw-node.bw >= node.freebw && node.reqmin > node.reqlastmin && node.overflow2nodeid >= 0 { 738 | node = vhost.nodes[node.overflow2nodeid] 739 | } 740 | curtime := time.Now().Unix() 741 | //unixtime := curtime.Unix() 742 | if curtime%60 == 0 { 743 | node.reqlastmin = node.reqmin 744 | node.reqmin = 0 745 | } 746 | node.reqcount++ 747 | node.reqmin++ 748 | var curserver *Server 749 | //根据节点负载均衡的方式,选择server。 750 | switch node.balance { 751 | case 'o': 752 | return node.curserver.ip, zonename, nil 753 | case 'a': 754 | sid := int(HashStr(hashstr)) % (swMAX - 1) 755 | curserver = node.servers[node.sw[sid]] 756 | case 'A': 757 | sid := int(HashStr(hashstr)) % (swMAX - 1) 758 | curserver = node.servers[node.sw[sid]] 759 | case 'h': 760 | //fmt.Printf("Hash: %v\n", HashStr(hashstr)) 761 | rbnode, ok := node.swtree.Get(HashStr(hashstr)) 762 | if ok == true { 763 | swnode := rbnode.(ServerWeight) 764 | curserver = swnode.server 765 | } else { 766 | curserver = getnextsvr(node) 767 | } 768 | case 'r': 769 | curserver = getnextsvr(node) 770 | } 771 | if curserver.status != 0 { 772 | curserver = getnextsvr(node) 773 | } 774 | return curserver.ip, zonename, nil 775 | } 776 | 777 | func getnextsvr(node *Node) *Server { 778 | curserver := node.curserver 779 | for curserver.status != 0 { 780 | curserver = curserver.next 781 | } 782 | node.curserver = curserver.next 783 | return curserver 784 | } 785 | -------------------------------------------------------------------------------- /rbtree/rbtree.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2015, Emir Pasic 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | * Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 19 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 21 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 22 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 23 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 24 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | */ 26 | 27 | // Implementation of Red-black tree. 28 | // Used by TreeSet and TreeMap. 29 | // Structure is not thread safe. 30 | // References: http://en.wikipedia.org/wiki/Red%E2%80%93black_tree 31 | 32 | package rbtree 33 | 34 | import ( 35 | "fmt" 36 | ) 37 | 38 | type color bool 39 | 40 | const ( 41 | black, red color = true, false 42 | ) 43 | 44 | type Comparator func(a, b interface{}) int 45 | type Tree struct { 46 | root *node 47 | size int 48 | comparator Comparator 49 | } 50 | 51 | type node struct { 52 | key interface{} 53 | color color 54 | left *node 55 | right *node 56 | parent *node 57 | } 58 | 59 | // Instantiates a red-black tree with the custom comparator. 60 | func NewWith(comparator Comparator) *Tree { 61 | return &Tree{comparator: comparator} 62 | } 63 | 64 | // Inserts node into the tree. 65 | // Key should adhere to the comparator's type assertion, otherwise method panics. 66 | func (tree *Tree) Put(key interface{}) { 67 | insertedNode := &node{key: key, color: red} 68 | if tree.root == nil { 69 | tree.root = insertedNode 70 | } else { 71 | node := tree.root 72 | loop := true 73 | for loop { 74 | compare := tree.comparator(key, node.key) 75 | switch { 76 | case compare == 0: 77 | return 78 | case compare < 0: 79 | if node.left == nil { 80 | node.left = insertedNode 81 | loop = false 82 | } else { 83 | node = node.left 84 | } 85 | case compare > 0: 86 | if node.right == nil { 87 | node.right = insertedNode 88 | loop = false 89 | } else { 90 | node = node.right 91 | } 92 | } 93 | } 94 | insertedNode.parent = node 95 | } 96 | tree.insertCase1(insertedNode) 97 | tree.size += 1 98 | } 99 | 100 | // Searches the node in the tree by key and returns its value or nil if key is not found in tree. 101 | // Second return parameter is true if key was found, otherwise false. 102 | // Key should adhere to the comparator's type assertion, otherwise method panics. 103 | func (tree *Tree) Get(key interface{}) (value interface{}, found bool) { 104 | node := tree.lookup(key) 105 | if node != nil { 106 | return node.key, true 107 | } 108 | return tree.root.key, false 109 | } 110 | 111 | func (tree *Tree) RGet(key interface{}) (value interface{}, found bool) { 112 | node := tree.rlookup(key) 113 | if node != nil { 114 | return node.key, true 115 | } 116 | return tree.root.key, false 117 | } 118 | 119 | // Remove the node from the tree by key. 120 | // Key should adhere to the comparator's type assertion, otherwise method panics. 121 | func (tree *Tree) Remove(key interface{}) { 122 | var child *node 123 | node := tree.lookup(key) 124 | if node == nil { 125 | return 126 | } 127 | if node.left != nil && node.right != nil { 128 | pred := node.left.maximumNode() 129 | node.key = pred.key 130 | node = pred 131 | } 132 | if node.left == nil || node.right == nil { 133 | if node.right == nil { 134 | child = node.left 135 | } else { 136 | child = node.right 137 | } 138 | if node.color == black { 139 | node.color = nodeColor(child) 140 | tree.deleteCase1(node) 141 | } 142 | tree.replaceNode(node, child) 143 | if node.parent == nil && child != nil { 144 | child.color = black 145 | } 146 | } 147 | tree.size -= 1 148 | } 149 | 150 | // Returns true if tree does not contain any nodes 151 | func (tree *Tree) Empty() bool { 152 | return tree.size == 0 153 | } 154 | 155 | // Returns number of nodes in the tree. 156 | func (tree *Tree) Size() int { 157 | return tree.size 158 | } 159 | 160 | // Removes all nodes from the tree. 161 | func (tree *Tree) Clear() { 162 | tree.root = nil 163 | tree.size = 0 164 | } 165 | 166 | func (tree *Tree) String() string { 167 | str := "RedBlackTree\n" 168 | if !tree.Empty() { 169 | output(tree.root, "", true, &str) 170 | } 171 | return str 172 | } 173 | 174 | func (node *node) String() string { 175 | return fmt.Sprintf("%v", node.key) 176 | } 177 | 178 | func output(node *node, prefix string, isTail bool, str *string) { 179 | if node.right != nil { 180 | newPrefix := prefix 181 | if isTail { 182 | newPrefix += "│ " 183 | } else { 184 | newPrefix += " " 185 | } 186 | output(node.right, newPrefix, false, str) 187 | } 188 | *str += prefix 189 | if isTail { 190 | *str += "└── " 191 | } else { 192 | *str += "┌── " 193 | } 194 | *str += node.String() + "\n" 195 | if node.left != nil { 196 | newPrefix := prefix 197 | if isTail { 198 | newPrefix += " " 199 | } else { 200 | newPrefix += "│ " 201 | } 202 | output(node.left, newPrefix, true, str) 203 | } 204 | } 205 | 206 | func (tree *Tree) lookup(key interface{}) *node { 207 | node := tree.root 208 | for node != nil { 209 | compare := tree.comparator(key, node.key) 210 | switch { 211 | case compare == 0: 212 | return node 213 | case compare < 0: 214 | node = node.left 215 | case compare > 0: 216 | node = node.right 217 | } 218 | } 219 | return nil 220 | } 221 | 222 | func (tree *Tree) rlookup(key interface{}) *node { 223 | node := tree.root 224 | oldcompare := 0 225 | for node != nil { 226 | compare := tree.comparator(key, node.key) 227 | switch { 228 | case compare < 0: 229 | if node.left == nil { 230 | return node 231 | } 232 | node = node.left 233 | case compare > 0 && oldcompare >= 0: 234 | if node.right == nil { 235 | return node 236 | } 237 | node = node.right 238 | case oldcompare != 0 && compare > 0 && oldcompare < 0: 239 | return node 240 | case compare == 0: 241 | return node 242 | //case oldcompare != 0 && oldcompare > 0 && compare < 0: 243 | // return node 244 | } 245 | oldcompare = compare 246 | } 247 | return nil 248 | } 249 | 250 | func (node *node) grandparent() *node { 251 | if node != nil && node.parent != nil { 252 | return node.parent.parent 253 | } 254 | return nil 255 | } 256 | 257 | func (node *node) uncle() *node { 258 | if node == nil || node.parent == nil || node.parent.parent == nil { 259 | return nil 260 | } 261 | return node.parent.sibling() 262 | } 263 | 264 | func (node *node) sibling() *node { 265 | if node == nil || node.parent == nil { 266 | return nil 267 | } 268 | if node == node.parent.left { 269 | return node.parent.right 270 | } else { 271 | return node.parent.left 272 | } 273 | } 274 | 275 | func (tree *Tree) rotateLeft(node *node) { 276 | right := node.right 277 | tree.replaceNode(node, right) 278 | node.right = right.left 279 | if right.left != nil { 280 | right.left.parent = node 281 | } 282 | right.left = node 283 | node.parent = right 284 | } 285 | 286 | func (tree *Tree) rotateRight(node *node) { 287 | left := node.left 288 | tree.replaceNode(node, left) 289 | node.left = left.right 290 | if left.right != nil { 291 | left.right.parent = node 292 | } 293 | left.right = node 294 | node.parent = left 295 | } 296 | 297 | func (tree *Tree) replaceNode(old *node, new *node) { 298 | if old.parent == nil { 299 | tree.root = new 300 | } else { 301 | if old == old.parent.left { 302 | old.parent.left = new 303 | } else { 304 | old.parent.right = new 305 | } 306 | } 307 | if new != nil { 308 | new.parent = old.parent 309 | } 310 | } 311 | 312 | func (tree *Tree) insertCase1(node *node) { 313 | if node.parent == nil { 314 | node.color = black 315 | } else { 316 | tree.insertCase2(node) 317 | } 318 | } 319 | 320 | func (tree *Tree) insertCase2(node *node) { 321 | if nodeColor(node.parent) == black { 322 | return 323 | } 324 | tree.insertCase3(node) 325 | } 326 | 327 | func (tree *Tree) insertCase3(node *node) { 328 | uncle := node.uncle() 329 | if nodeColor(uncle) == red { 330 | node.parent.color = black 331 | uncle.color = black 332 | node.grandparent().color = red 333 | tree.insertCase1(node.grandparent()) 334 | } else { 335 | tree.insertCase4(node) 336 | } 337 | } 338 | 339 | func (tree *Tree) insertCase4(node *node) { 340 | grandparent := node.grandparent() 341 | if node == node.parent.right && node.parent == grandparent.left { 342 | tree.rotateLeft(node.parent) 343 | node = node.left 344 | } else if node == node.parent.left && node.parent == grandparent.right { 345 | tree.rotateRight(node.parent) 346 | node = node.right 347 | } 348 | tree.insertCase5(node) 349 | } 350 | 351 | func (tree *Tree) insertCase5(node *node) { 352 | node.parent.color = black 353 | grandparent := node.grandparent() 354 | grandparent.color = red 355 | if node == node.parent.left && node.parent == grandparent.left { 356 | tree.rotateRight(grandparent) 357 | } else if node == node.parent.right && node.parent == grandparent.right { 358 | tree.rotateLeft(grandparent) 359 | } 360 | } 361 | 362 | func (node *node) maximumNode() *node { 363 | if node == nil { 364 | return nil 365 | } 366 | for node.right != nil { 367 | node = node.right 368 | } 369 | return node 370 | } 371 | 372 | func (tree *Tree) deleteCase1(node *node) { 373 | if node.parent == nil { 374 | return 375 | } else { 376 | tree.deleteCase2(node) 377 | } 378 | } 379 | 380 | func (tree *Tree) deleteCase2(node *node) { 381 | sibling := node.sibling() 382 | if nodeColor(sibling) == red { 383 | node.parent.color = red 384 | sibling.color = black 385 | if node == node.parent.left { 386 | tree.rotateLeft(node.parent) 387 | } else { 388 | tree.rotateRight(node.parent) 389 | } 390 | } 391 | tree.deleteCase3(node) 392 | } 393 | 394 | func (tree *Tree) deleteCase3(node *node) { 395 | sibling := node.sibling() 396 | if nodeColor(node.parent) == black && 397 | nodeColor(sibling) == black && 398 | nodeColor(sibling.left) == black && 399 | nodeColor(sibling.right) == black { 400 | sibling.color = red 401 | tree.deleteCase1(node.parent) 402 | } else { 403 | tree.deleteCase4(node) 404 | } 405 | } 406 | 407 | func (tree *Tree) deleteCase4(node *node) { 408 | sibling := node.sibling() 409 | if nodeColor(node.parent) == red && 410 | nodeColor(sibling) == black && 411 | nodeColor(sibling.left) == black && 412 | nodeColor(sibling.right) == black { 413 | sibling.color = red 414 | node.parent.color = black 415 | } else { 416 | tree.deleteCase5(node) 417 | } 418 | } 419 | 420 | func (tree *Tree) deleteCase5(node *node) { 421 | sibling := node.sibling() 422 | if node == node.parent.left && 423 | nodeColor(sibling) == black && 424 | nodeColor(sibling.left) == red && 425 | nodeColor(sibling.right) == black { 426 | sibling.color = red 427 | sibling.left.color = black 428 | tree.rotateRight(sibling) 429 | } else if node == node.parent.right && 430 | nodeColor(sibling) == black && 431 | nodeColor(sibling.right) == red && 432 | nodeColor(sibling.left) == black { 433 | sibling.color = red 434 | sibling.right.color = black 435 | tree.rotateLeft(sibling) 436 | } 437 | tree.deleteCase6(node) 438 | } 439 | 440 | func (tree *Tree) deleteCase6(node *node) { 441 | sibling := node.sibling() 442 | sibling.color = nodeColor(node.parent) 443 | node.parent.color = black 444 | if node == node.parent.left && nodeColor(sibling.right) == red { 445 | sibling.right.color = black 446 | tree.rotateLeft(node.parent) 447 | } else if nodeColor(sibling.left) == red { 448 | sibling.left.color = black 449 | tree.rotateRight(node.parent) 450 | } 451 | } 452 | 453 | func nodeColor(node *node) color { 454 | if node == nil { 455 | return black 456 | } 457 | return node.color 458 | } 459 | --------------------------------------------------------------------------------