cluster-threading.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const cluster = require('cluster')
  2. const ldap = require('ldapjs')
  3. const os = require('os')
  4. const threads = []
  5. threads.getNext = function () {
  6. return (Math.floor(Math.random() * this.length))
  7. }
  8. const serverOptions = {
  9. connectionRouter: (socket) => {
  10. socket.pause()
  11. console.log('ldapjs client requesting connection')
  12. const routeTo = threads.getNext()
  13. threads[routeTo].send({ type: 'connection' }, socket)
  14. }
  15. }
  16. const server = ldap.createServer(serverOptions)
  17. if (cluster.isMaster) {
  18. for (let i = 0; i < os.cpus().length; i++) {
  19. const thread = cluster.fork({
  20. id: i
  21. })
  22. thread.id = i
  23. thread.on('message', function () {
  24. })
  25. threads.push(thread)
  26. }
  27. server.listen(1389, function () {
  28. console.log('ldapjs listening at ' + server.url)
  29. })
  30. } else {
  31. const threadId = process.env.id
  32. serverOptions.connectionRouter = () => {
  33. console.log('should not be hit')
  34. }
  35. process.on('message', (msg, socket) => {
  36. switch (msg.type) {
  37. case 'connection':
  38. server.newConnection(socket)
  39. socket.resume()
  40. console.log('ldapjs client connection accepted on ' + threadId.toString())
  41. }
  42. })
  43. server.search('dc=example', function (req, res) {
  44. console.log('ldapjs search initiated on ' + threadId.toString())
  45. const obj = {
  46. dn: req.dn.toString(),
  47. attributes: {
  48. objectclass: ['organization', 'top'],
  49. o: 'example'
  50. }
  51. }
  52. if (req.filter.matches(obj.attributes)) { res.send(obj) }
  53. res.end()
  54. })
  55. }