Beispiel #1
1
var Consumer = exports.Consumer = function (handler) {
    if (!handler || typeof handler != 'function') {
        throw 'handler is not a function';
    }

    this.server = thrift.createServer(scribe, {
        Log: function (messages, response) {
            try {
                handler(messages);
            } catch (err) {
                scribely.log.error(err);
                response(scribeTypes.ResultCode.TRY_AGAIN);
            }

            response(scribeTypes.ResultCode.OK);
        }
    });
};
        }).then(() => {

        // after inital all and start thrift server
        self._server = thrift.createServer(self._innerThriftProcessor, self._innerHandler, self._serverOptions || {});
        self._server.listen(self._port);

        // inital service
        if (self._custom) {
          return self._publish(options.thrift.alias,
            {host: self._host, port: self._port, actions: false},
            utils.TTL);
        } else {
          self.add = self._add;
          // inital service
          return self._add(options.services);
        }

      }).then(() => {
Beispiel #3
1
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var thrift = require('thrift');

var AdvertiserService = require('./gen-nodejs/AdvertiserService.js'),
    ttypes = require('./gen-nodejs/AdvertiserService_types.js'),
    ttransport = require('./node_modules/thrift/lib/thrift/transport'),
    tprotocol = require('./node_modules/thrift/lib/thrift/protocol.js');

var users = {};

var server = thrift.createServer(AdvertiserService, {

    getAdGroup:function(adGroupId, requestContext, result){
        console.log(arguments);
        result(requestContext);
    }

}, {transport:ttransport.TBufferedTransport,  protocol: tprotocol.TBinaryProtocol});

server.listen(8989);

console.log('server started at port: ', 8989);
Beispiel #4
0
var Server = function(thriftServerOptions) {
  this._nameToComponents = {};
  this._thriftServer = thrift.createServer(
    ReactThrift,
    {renderComponentToString: this._renderComponentToString.bind(this)},
    thriftServerOptions || {});
};
Beispiel #5
0
Monitor.prototype.init = function(process, options) {
	var thatMonitor = this;
	this.server = thrift.createServer(DomobService, serverObj, {});
	this.aliveSince = new Date();
	this.hostProcess = process;
	this.workerPids = [];
	this.workerStatus = {};
	this.getters = [
		"test",
		"rss",
		"cpuUsage_percent"
	];
	psTree(this.hostProcess.pid, function (err, children) {
		if(err){
			console.log(err);
		}else{
			for (var i = children.length - 1; i >= 0; i--) {
				if(children[i].COMMAND == 'node'){
					thatMonitor.workerPids.push(children[i].PID);
				}
			};
		}
	});

	if(options.listen){
		this.server.listen(options.listen);
		console.log('Dm303 monitor listening on ' + options.listen);

		var thatMonitor =this;
		this.usageMonitingTimmer = setInterval(function(){
			thatMonitor.usageMoniting()
		}, 5000);
	}
};
  it('should send trace data to Scribe', (done) => {
    const logSpy = sinon.spy();
    const scribeHandler = {
      Log: (messages, result) => {
        logSpy(messages, result);
        result(ResultCode.OK);
      }
    };

    const server = thrift.createServer(Scribe, scribeHandler, {
      transport: thrift.TFramedTransport,
      protocol: thrift.TBinaryProtocol
    });
    const scribeServer = server.listen(0, () => {
      const port = scribeServer.address().port;
      const logger = new ScribeLogger({
        scribeHost: '127.0.0.1',
        scribePort: port,
        scribeInterval: 1
      });

      const ctxImpl = new ExplicitContext();
      const recorder = new BatchRecorder({logger});
      const tracer = new Tracer({recorder, ctxImpl});
      ctxImpl.scoped(() => {
        const id = new TraceId({
          traceId: new Some('abc'),
          parentId: new Some('def'),
          spanId: '123',
          sampled: new Some(true),
          flags: 0
        });
        tracer.setId(id);
        tracer.recordAnnotation(new Annotation.ServerAddr({serviceName: 'test'}));
        tracer.recordAnnotation(new Annotation.ClientSend());
        tracer.recordAnnotation(new Annotation.ClientRecv());
        setTimeout(() => {
          scribeServer.close();

          expect(logSpy.called).to.equal(true, 'Logger was not called as expected');
          const firstCall = logSpy.getCall(0);
          if (firstCall) {
            const serialized = base64decode(firstCall.args[0][0].message);
            const span = deserialize(serialized); // sanity check a little data
            expect(span.trace_id.toNumber()).to.equal(2748);
            expect(span.annotations.length).to.equal(2);
            expect(span.binary_annotations.length).to.equal(1);
          }
          done();
        }, 150);
      });
    });
  });
Beispiel #7
0
function makeServer(db) {
  const server = thrift.createServer(KeyChecker, {
    ping: function(result) {
      console.log('ping');
      result(null);
    },

    isAuthorized: function(publicKey, repository, result) {
      let apps = db.collection('apps');
      let query = {
        repository: repository,
        authorizedKeys: {$in: [publicKey]},
      };
      apps.find(query).toArray(function(err, docs) {
        assert.equal(null, err);
        result(null, docs.length);
      });
    },
  });

  return server;
}
Beispiel #8
0
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

//Node server test for the following I/O stack:
//    TJSONProtocol
//    TBufferedTransport
//    TSocket

var thrift = require('thrift');
var TFramedTransport = require('thrift/transport').TFramedTransport;
var TJSONProtocol = require('thrift/protocol').TJSONProtocol;
var ThriftTestSvc = require('./gen-nodejs/ThriftTest');
var ThriftTestHandler = require('./test_handler').ThriftTestHandler;

var ThriftTestSvcOpt = {
  transport: TFramedTransport,
  protocol: TJSONProtocol
};

thrift.createServer(ThriftTestSvc, 
                    ThriftTestHandler, 
                    ThriftTestSvcOpt).listen(9090);
var server = exports.relation = thrift.createServer(RelationService,{

    getMsgCounter: function(mids,response){
        var ret = []
        var icount = 0
        process.log.info(util.format("getMsgCounter:mids=%s",mids))
        pool.borrow(function(err,client){
            mids.forEach(function(ele){
                 client.hgetall(ele,function(err,reply){
                     icount++;
                     if(reply!=null && reply.length>0){
                         ret[ele.toString]=reply;
                     }
                     if(icount==mids.length){
                        pool.release(client)
                        if(ret.length!=mids.length){
                            ikaodbPool.borrow(function(err,idb){
                                idb.getMsgCounter(mids,function(err,reply){
                                    ikaodbPool.release(idb)
                                    response(reply);
                                })
                            })
                            return;
                        }
                        response(ret);
                        ret = null;
                     }
                 })
            })
        })
    },

    getRelatedMsg:function(mid,start,len,response){
        process.log.info(util.format("getRelatedMsg:mid=%s,start=%d,len=%d",mid,start,len))
        pool.borrow(function(err,client){
            client.zrevrange(ANSWER+"_"+mid,start-1,start+len-1,function(err,reply){
                 pool.release(client)
                 if(reply!=null && reply.length==0){
                     ikaodbPool.borrow(function(err,idb){
                           idb.getRelatedMsg(mid,start,len,function(err,reply){
                               ikaodbPool.release(idb)
                               response(reply)
                           })
                     })
                 }else{
                    response(reply)
                 }
            })
        })
    },

    initMsg:function(mid,response){
        process.log.info(util.format("initMsg:mid=%s",mid))
        pool.borrow(function(err,client){
            client.hmset(mid,ShareStruct_ttypes.MsgCounter.answer,0,ShareStruct_ttypes.MsgCounter.right,0,function(err,reply){
                client.zadd(ANSWER+"_"+mid,0,"-1",function(err,reply){
                    pool.release(client);
                    if(err!=null)
                        response(FALSE)
                    else
                        response(TRUE);
                });
            });
        })
    } ,

    incr:function(mid,type,response){
        process.log.info(util.format("incrMsg:mid=%s,type=%d",mid,type))
        pool.borrow(function(err,client){
            client.exists(mid,function(err,reply){
                ikaodbPool.borrow(function(err,idb){
                    idb.incrForMsg(mid,type,function(){ikaodbPool.release(idb)})
                })
                if(reply==1){
                    client.hincrby(mid,type,1,function(err,reply){
                        pool.release(client)
                        if(err!=null)
                            response(FALSE)
                        else
                            response(TRUE)
                    });
                }else{
                    pool.release(client)
                    response(TRUE)
                }
            })
        })
    },

    decr:function(mid,type,response){
        process.log.info(util.format("decrMsg:mid=%s,type=%d",mid,type))
        pool.borrow(function(err,client){
            client.exists(mid,function(err,reply){
                ikaodbPool.borrow(function(err,idb){
                    idb.decrForMsg(mid,type,function(){ikaodbPool.release(idb)})
                })
                if(reply==1){
                    client.hincrby(mid,type,-1,function(err,reply){
                        pool.release(client)
                        if(err!=null)
                            response(FALSE)
                        else
                            response(TRUE)
                    });
                }else{
                    pool.release(client)
                    response(TRUE)
                }
            })
        })
    },

    addRelatedMsg:function(mid,answer,response){
        process.log.info(util.format("addRelatedMsg:mid=%s",mid))
        pool.borrow(function(err,client){
            client.exists(ANSWER+"-"+mid,function(err,reply){
                ikaodbPool.borrow(function(err,idb){
                    idb.addRelatedMsg(mid,answer,function(){ikaodbPool.release(idb)})
                })
                if(reply==1){
                    client.zadd(ANSWER+"-"+mid,new Date().getTime(),answer,function(err,reply){
                        pool.release(client);
                        incr(mid,ShareStruct_ttypes.MsgCounter.answer,function(){response(TRUE)})
                    });
                }else{
                    pool.release(client);
                    incr(mid,ShareStruct_ttypes.MsgCounter.answer,function(){response(TRUE)})
                }
            })

        })
    },

    deleteRelatedMsg:function(mid,answer,response){
        process.log.info(util.format("deleteRelatedMsg:mid=%s",mid))
        ikaodbPool.borrow(function(err,idb){
            idb.deleteRelatedMsg(mid,answer,function(){ikaodbPool.release(idb)})
        })
        pool.borrow(function(err,client){
            client.zrem(ANSWER+"-"+mid,answer,function(err,reply){
                pool.release(client)
                if(err!=null){
                    response(FALSE)
                    return
                }
                decr(mid,ShareStruct_ttypes.MsgCounter.answer,function(reply){
                    response(reply)
                });
            });
        })
    }
})
Beispiel #10
0
var thrift = require('thrift');

var JobExchange = require('./gen-nodejs/JobExchange'),
    ttypes = require('./gen-nodejs/scheduler_types');

var server = thrift.createServer(JobExchange, {
  insert_job: function(job, callback) {
    // job is an instance of ttypes.Job
    return 1;
    // or
    process.nextTick(function() {
      // Uses the standard callback(err, data) signature
      callback(null, 1);
    });
  },

  get_job: function(jid, callback) {
    return new ttypes.Job();
  },

  get_all: function(callback) {
    return [new ttypes.Job()];
  }
});

server.listen(9160);
Beispiel #11
0
var protocol = thrift.TBinaryProtocol;
if (program.protocol === "json") {
  protocol = thrift.TJSONProtocol;
} else if (program.protocol === "compact") {
  protocol = thrift.TCompactProtocol;
} 

var port = 9090;
if (String(program.port) === "undefined"){
} else {
  port = program.port;
}

var handler = ThriftTestHandler;
if (program.promise) {
  handler = ThriftTestHandlerPromise;
} 

var options = {
  protocol: protocol,
  transport: transport
};
if (program.ssl) {
  options.tls = {
    key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
    cert: fs.readFileSync(path.resolve(__dirname, 'server.crt'))
  };
}
thrift.createServer(ThriftTest, handler, options).listen(port);

Beispiel #12
0
	ttypes = require('./service_types.js');


//funcion llamada al recibir una imagen desde el client thrift (c++/opencv)
var receiveImage = function(image,success){
     buf = new Buffer(image.data.toString('base64'),'base64');
     fs.writeFile('image.jpeg',buf,function(err){
        if(err) console.log(err);
     });
     events.emit('imagen_recibida');
     success(true);
}



var Tserver = thrift.createServer(ImageService,{
	receiveImage: receiveImage
});

Tserver.listen(9090);





    




 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var thrift = require('thrift');

var UserStorage = require('./gen-nodejs/UserStorage.js'),
    ttypes = require('./gen-nodejs/user_types');

var users = {};

var server = thrift.createServer(UserStorage, {
  store: function(user, result) {
    console.log("server stored:", user.uid);
    users[user.uid] = user;
    result(null);
  },

  retrieve: function(uid, result) {
    console.log("server retrieved:", uid);
    result(null, users[uid]);
  },
});

server.listen(9091);
Beispiel #14
0
var thrift = require("thrift");
var Greeter = require("./gen-nodejs/Greeter");
var types = require("./gen-nodejs/helloworld_types");

//createServer - params: processor, handler, options

var server = thrift.createServer(Greeter, {
    SayHello: function(req, callback){
        
    }
});
Beispiel #15
0
var server = thrift.createServer(ThriftTest, {
  testVoid: function(result) {
    console.log('testVoid()');
    result(null);
  },

  testString: function(thing, result) {
    console.log('testString(\'' + thing + '\')');
    result(null, thing);
  },

  testByte: function(thing, result) {
    console.log('testByte(' + thing + ')');
    result(null, thing);
  },

  testI32: function(thing, result) {
    console.log('testI32(' + thing + ')');
    result(null, thing);
  },

  testI64: function(thing, result) {
    console.log('testI64(' + thing + ')');
    result(null, thing);
  },

  testDouble: function(thing, result) {
    console.log('testDouble(' + thing + ')');
    result(null, thing);
  },

  testStruct: function(thing, result) {
    console.log('testStruct(');
    console.log(thing);
    console.log(')');
    result(null, thing);
  },

  testNest: function(nest, result) {
    console.log('testNest(');
    console.log(nest);
    console.log(')');
    result(null, nest);
  },

  testMap: function(thing, result) {
    console.log('testMap(');
    console.log(thing);
    console.log(')');
    result(null, thing);
  },

  testStringMap: function(thing, result) {
    console.log('testStringMap(');
    console.log(thing);
    console.log(')');
    result(null, thing);
  },

  testSet: function(thing, result) {
    console.log('testSet(');
    console.log(thing);
    console.log(')');
    result(null, thing);
  },

  testList: function(thing, result) {
    console.log('testList(');
    console.log(thing);
    console.log(')');
    result(null, thing);
  },

  testEnum: function(thing, result) {
    console.log('testEnum(' + thing + ')');
    result(null, thing);
  },

  testTypedef: function(thing, result) {
    console.log('testTypedef(' + thing + ')');
    result(null, thing);
  },

  testMapMap: function(hello, result) {
    console.log('testMapMap(' + hello + ')');

    var mapmap = [];
    var pos = [];
    var neg = [];
    for (var i = 1; i < 5; i++) {
      pos[i] = i;
      neg[-i] = -i;
    }
    mapmap[4] = pos;
    mapmap[-4] = neg;

    result(null, mapmap);
  },

  testInsanity: function(argument, result) {
    console.log('testInsanity(');
    console.log(argument);
    console.log(')');

    var hello = new ttypes.Xtruct();
    hello.string_thing = 'Hello2';
    hello.byte_thing = 2;
    hello.i32_thing = 2;
    hello.i64_thing = 2;

    var goodbye = new ttypes.Xtruct();
    goodbye.string_thing = 'Goodbye4';
    goodbye.byte_thing = 4;
    goodbye.i32_thing = 4;
    goodbye.i64_thing = 4;

    var crazy = new ttypes.Insanity();
    crazy.userMap = [];
    crazy.userMap[ttypes.Numberz.EIGHT] = 8;
    crazy.userMap[ttypes.Numberz.FIVE] = 5;
    crazy.xtructs = [goodbye, hello];

    var first_map = [];
    var second_map = [];

    first_map[ttypes.Numberz.TWO] = crazy;
    first_map[ttypes.Numberz.THREE] = crazy;

    var looney = new ttypes.Insanity();
    second_map[ttypes.Numberz.SIX] = looney;

    var insane = [];
    insane[1] = first_map;
    insane[2] = second_map;

    console.log('insane result:');
    console.log(insane);
    result(null, insane);
  },

  testMulti: function(arg0, arg1, arg2, arg3, arg4, arg5, result) {
    console.log('testMulti()');

    var hello = new ttypes.Xtruct();;
    hello.string_thing = 'Hello2';
    hello.byte_thing = arg0;
    hello.i32_thing = arg1;
    hello.i64_thing = arg2;
    result(null, hello);
  },

  testException: function(arg, result) {
    console.log('testException('+arg+')');
    if (arg === 'Xception') {
      var x = new ttypes.Xception();
      x.errorCode = 1001;
      x.message = arg;
      result(x);
    } else if (arg === 'TException') {
      result(new Thrift.TException(arg));
    } else {
      result(null);
    }
  },

  testMultiException: function(arg0, arg1, result) {
    console.log('testMultiException(' + arg0 + ', ' + arg1 + ')');
    if (arg0 === ('Xception')) {
      var x = new ttypes.Xception();
      x.errorCode = 1001;
      x.message = 'This is an Xception';
      result(x);
    } else if (arg0 === ('Xception2')) {
      var x = new ttypes.Xception2();
      x.errorCode = 2002;
      x.struct_thing = new ttypes.Xtruct();
      x.struct_thing.string_thing = 'This is an Xception2';
      result(x);
    }

    var res = new ttypes.Xtruct();
    res.string_thing = arg1;
    result(null, res);
  },

  testOneway: function(sleepFor, result) {
    console.log('testOneway(' + sleepFor + ') => sleeping...');
    setTimeout(function(){
      console.log('Done sleeping for testOneway!');
    }, sleepFor*1000); //seconds
  }
}, { //server options
  'transport': ttransport.TFramedTransport
});
Beispiel #16
0
//index.js
var thrift = require('thrift');
var couponServices = require('./gen-nodejs/CouponServices');
var ttypes = require('./gen-nodejs/coupon_types');
var handlers = require('./handlers');

var queryCoupon = function(queryParam, callback) {
	console.log('queryCoupon');
	callback('ok');
	return;
}

var consumeCoupon = function(consumeParam, callback) {
	console.log('consumeCoupon');
	callback('ok');
	return;
}

var connection = thrift.createServer(couponServices,{
	queryCoupon: handlers.query,
	consumeCoupon: handlers.consume,
	queryProjects: handlers.queryPros
});

connection.listen(9090);

console.log("server listenning 9090");
Beispiel #17
0
var server = exports.timeline = thrift.createServer(UserService,{
    isRegister:function(phone,response){
        mysqlPool.borrow(function(err,mysql){
            ret = FALSE;
            mysql.execute("select phone from user where phone=?",[phone]).on("row",function(r){
                ret = TRUE
            }).on("error",function(e){
                mysqlPool.release(mysql)
                process.log.error(e)
                response(ret)
            }).on("end",function(){
                mysqlPool.release(mysql)
                response(ret)
            })
        })
    },

    registerUser:function(user,response){
        mysqlPool.borrow(function(err,mysql){
            mysql.execute("insert into user (uid,phone,nick,password,sex,type,qq,renren) values (?,?,?,?,?)",[user.uid,
                user.phone,user.nick,user.password,user.sex,user.type,user.qq,user.renren]).on("error",function(){
                     mysqlPool.release(mysql)
                     response(FALSE)
                }).on("end",function(){
                    mysql.execute("insert into user_desc (uid,city,street,school,grade,money,point,desc)",[user.uid,
                        user.city,user.street,user.school,user.grade,user.money,user.point,user.desc]).on("error",function(){
                            mysqlPool.release(mysql)
                            response(FALSE)
                        }).on("end",function(){
                            mysqlPool.release(mysql)
                            response(TRUE)
                        })
                })


          /* mysql.execute("set autocommit = 0").on("end",function(){
               mysql.execute("insert into user (uid,phone,nick,password,sex,type,qq,renren) values (?,?,?,?,?)",[user.uid,
               user.phone,user.nick,user.password,user.sex,user.type,user.qq,user.renren]).on("error",function(){
                   mysql.execute("rollback").on("end",function(){
                       mysql.execute("set autocommit = 1").on("end",function(){
                           mysqlPool.release(mysql)
                           response(FALSE)
                       })
                   })
               }).on("end",function(){
                   mysql.execute("insert into user_desc (uid,city,street,school,grade,money,point,desc)",[user.uid,
                   user.city,user.street,user.school,user.grade,user.money,user.point,user.desc]).on("error",function(){
                           mysql.execute("rollback").on("end",function(){
                               mysql.execute("set autocommit = 1").on("end",function(){
                                   mysqlPool.release(mysql)
                                   response(FALSE)
                               })
                           })
               }).on("end",function(){
                           mysql.execute("commit").on("end",function(){
                               mysql.execute("set autocommit = 1").on("end",function(){
                                   mysqlPool.release(mysql)
                                   response(TRUE)
                               })
                           })
                   })
           }).on("error",function(){
                mysqlPool.release(mysql)
                response(FALSE)
           })
        })*/
    })},

    modifyPasswd:function(user,newpasswd,response){
        mysqlPool.borrow(function(err,mysql){
           var ret = FALSE;
           mysql.execute("update user set password=? where uid=? and password=?",[user.password,user.uid,newpasswd]).on("result",
           function(r){
               if(r.affected_rows==1){
                   ret = TRUE;
               }
           }).on("end",function(){
                   mysqlPool.release(mysql)
                   response(ret)
               })
        })
    },

    bindingQQ:function(qq,uid,response){
        mysqlPool.borrow(function(err,mysql){
            var ret = FALSE;
            mysql.execute("update user set qq=? where uid=?",[qq,uid]).on("result",
                function(r){
                    if(r.affected_rows==1){
                        ret = TRUE;
                    }
                }).on("end",function(){
                    mysqlPool.release(mysql)
                    response(ret)
                })
        })
    },

    bindingRenRen:function(renren,uid,response){
        mysqlPool.borrow(function(err,mysql){
            var ret = FALSE;
            mysql.execute("update user set renren=? where uid=?",[renren,uid]).on("result",
                function(r){
                    if(r.affected_rows==1){
                        ret = TRUE;
                    }
                }).on("end",function(){
                    mysqlPool.release(mysql)
                    response(ret)
                })
        })
    },

    login:function(user,token,expire,response){
        mysqlPool.borrow(function(err,mysql){
            var ret = false;
            var uid = "";
            mysql.execute("select uid from user where phone=? and password=?",[user.phone,user.password]).on("row",function(r){
                    ret = true;
                    uid = r.uid;
                }).on("end",function(){
                    mysqlPool.release(mysql)
                    if(ret){
                        var m = getMd5(user.id+"_"+new Date().getTime())
                        pool.borrow(function(err,redis){
                            redis.hmset("token_"+token,"uid",uid,"token",token,"expire",expire,function(err,reply){
                                redis.expireat("token_"+token,expire,function(){
                                    pool.release(redis)
                                });
                                response(m);
                            });
                        })
                    }else{
                        response("")
                    }
                })
        })
     },

    logout:function(token,respnose){
        pool.borrow(function(err,redis){
            redis.del("token_"+token,function(){
                pool.release(redis)
                response(TRUE)
            })
        })
    },

    sendCode:function(phone,expire,response){
        pool.borrow(function(err,redis){
            redis.set("code_"+phone,"123",function(err,reply){
                 redis.expireat("code_"+phone,expire,function(){
                    pool.release(redis)
                    response(TRUE)
                 })
            })
        })
    },

    verifyCode:function(phone,code,response){
         pool.borrow(function(err,redis){
            redis.get("code_"+phone,function(err,reply){
                 pool.release(redis);
                if(reply==code){
                    response(TRUE)
                }else{
                    response(FALSE)
                }
            })
         })
    },

    getCity:function(response){
        mysqlPool.borrow(function(err,mysql){
            var city= []
            mysql.execute("select city,cid from city").on("row",function(r){
                 city[r.city] = r.cid;
            }).on("error",function(){
                 mysqlPool.release(mysql)
                 response(city)
            }).on("end",function(){
                 mysqlPool.release(mysql)
                 response(city)
            })
        })
    },

    getStreet:function(city,response){
        mysqlPool.borrow(function(err,mysql){
            var street = []
            mysql.execute("select street,sid from street where cid=?",[city]).on("row",function(r){
                street[r.street] = r.sid
            }).on("error",function(){
                mysqlPool.release(mysql)
                response(street)
            }).on("end",function(){
                mysqlPool.release(mysql)
                response(street)
            })
        })
    },

    getSchool:function(street,response){
        mysqlPool.borrow(function(err,mysql){
            var school = []
            mysql.execute("select school,schoolid from school where sid=?",[street]).on("row",function(r){
                school[r.school] = r.schoolid
            }).on("error",function(){
                    mysqlPool.release(mysql)
                    response(school)
                }).on("end",function(){
                    mysqlPool.release(mysql)
                    response(school)
            })
        })
    },

    getGrade:function(school,response){
        mysqlPool.borrow(function(err,mysql){
            var grade = []
            mysql.execute("select grade,gid from grade where schoolid=?",[school]).on("row",function(r){
                grade[r.grade] = r.gid
            }).on("error",function(){
                    mysqlPool.release(mysql)
                    response(grade)
                }).on("end",function(){
                    mysqlPool.release(mysql)
                    response(grade)
                })
        })
    },

    getCounter:function(uid,response){
        pool.borrow(function(err,redis){
            redis.hgetall("counter_"+uid,function(err,reply){
                pool.release(redis)
                response(reply)
            })
        })
    },

    incCounter:function(uid,g,step,response){
        pool.borrow(function(err,redis){
            redis.hincby("counter_"+uid,g,step,function(err,reply){
                pool.release(redis)
                response(TRUE)
            })
        })
    },

    decrCounter:function(uid,g,step,response){
        pool.borrow(function(err,redis){
            redis.hincby("counter_"+uid,g,step,function(err,reply){
                pool.release(redis)
                response(TRUE)
            })
        })
    },

    getMd5:function(str){
        var hash = require('crypto').createHash('md5');
        return hash.update(str+"").digest('hex');
    }

})
Beispiel #18
0
var SumService = require('gen-nodejs/SumService'),
    ttypes = require('gen-nodejs/SumService_types');

var thrift = require('thrift'),
    fibrous = require('fibrous');

var s = 0;

function add(x) {
  s += x;
}

function get() {
  return s;
}

var server = thrift.createServer(SumService, {
  add: fibrous(add),
  get: fibrous(get)
});

server.listen(9090);
Beispiel #19
0
program
  .option('-p, --protocol <protocol>', 'Set thift protocol (binary|json) [protocol]')
  .option('-t, --transport <transport>', 'Set thift transport (buffered|framed) [transport]')
  .parse(process.argv);

var protocol = undefined;
var transport =  undefined;

if (program.protocol === "binary") {
  protocol = ThriftProtocols.TBinaryProtocol;
} else if (program.protocol === "json") {
  protocol = ThriftProtocols.TJSONProtocol;
} else {
  //default
  protocol = ThriftProtocols.TBinaryProtocol;
}

if (program.transport === "framed") {
  transport = ThriftTransports.TFramedTransport;
} else if (program.transport === "buffered") {
  transport = ThriftTransports.TBufferedTransport;
} else {
  //default
  transport = ThriftTransports.TBufferedTransport;
}

thrift.createServer(ThriftTest, ThriftTestHandler, {
  protocol: protocol,
  transport: transport
}).listen(9090);
Beispiel #20
0
var thrift = require('thrift'),
    ttransport = require('thrift/transport');

var UserStorage = require('./gen-nodejs/UserStorage'),
    ttypes = require('./gen-nodejs/user_types');

var users = {};

var store = function(user, result) {
  console.log("stored:", user.uid);
  users[user.uid] = user;
  result(null);
};
var retrieve = function(uid, result) {
  console.log("retrieved:", uid);
  result(null, users[uid]);
};

var server_framed = thrift.createServer(UserStorage, {
  store: store,
  retrieve: retrieve
});
server_framed.listen(9090);
var server_buffered = thrift.createServer(UserStorage, {
 store: store,
 retrieve: retrieve
}, {transport: ttransport.TBufferedTransport});
server_buffered.listen(9091);
Beispiel #21
0
            console.log('cost(ms):', Date.now()-t1);
            console.log('Search results for "%s"', results);
            fn('{"flag":true,"data":' + JSON.stringify(results) +'}');
            return;   
        });
    }
};



var server_framed = thrift.createServer(Nodis, {
    createUserIndex : createUserIndex,
    modifyUserIndex : modifyUserIndex,
    queryUserPage : queryUserPage,

    createGroupIndex : createGroupIndex,
    modifyGroupIndex : modifyGroupIndex,
    queryGroupPage : queryGroupPage,

    queryPrefixUserPage : queryPrefixUserPage
});

server_framed.listen(config.nodis_thrift_service_port);
console.log('NodisServer is running now...');


zkUtils.registerService('/thrift_services/nodis', config.nodis_thrift_service_ip + ':' + config.nodis_thrift_service_port);


//add shutdown hook: remove service from zookeeper
process.on('SIGTERM', function () {
Beispiel #22
0
var server = thrift.createServer(Calculator, {
  ping: function(result) {
    console.log("ping()");
    result(null);
  },

  add: function(n1, n2, result) {
    console.log("add(", n1, ",", n2, ")");
    result(null, n1 + n2);
  },

  calculate: function(logid, work, result) {
    console.log("calculate(", logid, ",", work, ")");

    var val = 0;
    if (work.op == ttypes.Operation.ADD) {
      val = work.num1 + work.num2;
    } else if (work.op === ttypes.Operation.SUBTRACT) {
      val = work.num1 - work.num2;
    } else if (work.op === ttypes.Operation.MULTIPLY) {
      val = work.num1 * work.num2;
    } else if (work.op === ttypes.Operation.DIVIDE) {
      if (work.num2 === 0) {
        var x = new ttypes.InvalidOperation();
        x.whatOp = work.op;
        x.why = 'Cannot divide by 0';
        result(x);
        return;
      }
      val = work.num1 / work.num2;
    } else {
      var x = new ttypes.InvalidOperation();
      x.whatOp = work.op;
      x.why = 'Invalid operation';
      result(x);
      return;
    }

    var entry = new SharedStruct();
    entry.key = logid;
    entry.value = ""+val;
    data[logid] = entry;

    result(null, val);
  },

  getStruct: function(key, result) {
    console.log("getStruct(", key, ")");
    result(null, data[key]);
  },

  zip: function() {
    console.log("zip()");
    result(null);
  }

});
Beispiel #23
0
var getSchema = function(success){
  if (query_schema == undefined) {
    success(mock.schema());
    return;
  }
  success(query_schema);
};

var getThriftSchema = function(success){
  getSchema(success);
};

var getQueryPlan = function(success){
  if (query_plan == undefined) {
    success(mock.query_plan());
  }
  success(query_plan);
};

var server_mock = thrift.createServer(ThriftHive, {
  getClusterStatus: getClusterStatus,
  execute: execute,
  fetchOne: fetchOne,
  fetchN: fetchN,
  fetchAll: fetchAll,
  getSchema: getSchema,
  getThriftSchema: getThriftSchema,
  getQueryPlan: getQueryPlan
}, {transport: ttransport.TBufferedTransport});
server_mock.listen(10000);
var thrift = require('thrift');
var helloSvc = require('./gen-nodejs/helloSvc.js');

var helloHandler = {
  getMessage: function (name, result) {
    console.log("Received: " + name);
    result(null, "Hello " + name);
  }
};

var serverOpt = {
  protocol: thrift.TBinaryProtocol,
  transport: thrift.TBufferedTransport
}
var port = 8585;

thrift.createServer(helloSvc, helloHandler, serverOpt)
  .on('error', function(error) { console.log(error); })
  .listen(port);
console.log("Thrift Server running on port: " + port);


Beispiel #25
0
var thrift = require('thrift');

var JobExchange = require('./examples/gen-nodejs/JobExchange.js'),
    ttypes = require('./examples/gen-nodejs/scheduler_types');

var server = thrift.createServer(JobExchange, {
  insert_job: function(job, callback) {
    // job is an instance of ttypes.Job
    callback(1);
  },

  get_job: function(jid, callback) {
    callback(new ttypes.Job());
  },

  get_all: function(callback) {
    callback([new ttypes.Job({})]);
  }
});

server.listen(9160);
Beispiel #26
0
  protocol = ThriftProtocols.TJSONProtocol;
} else {
  //default
  protocol = ThriftProtocols.TBinaryProtocol;
}

if (program.transport === "framed") {
  transport = ThriftTransports.TFramedTransport;
} else if (program.transport === "buffered") {
  transport = ThriftTransports.TBufferedTransport;
} else {
  //default
  transport = ThriftTransports.TBufferedTransport;
}

var options = {
  protocol: protocol,
  transport: transport
};

if (program.ssl) {
  //ssl options
  options.key = fs.readFileSync(path.resolve(__dirname, 'server.key'));
  options.cert = fs.readFileSync(path.resolve(__dirname, 'server.crt'));
  thrift.createSSLServer(ThriftTest, ThriftTestHandler, options).listen(9090);

} else {
  //default
  thrift.createServer(ThriftTest, ThriftTestHandler, options).listen(9090);
}
Beispiel #27
0
    policyAgreed: true,
    activationCode: 'fuckteamsecret',
    username: 'miracle9000',
    phone: '138781236651',
    password: 'oioqwe',
  }

  return new Promise((resolve) => {
    setTimeout(() => {
      const rand = Math.random()

      data.location = rand
      if (rand > 0.5) {
        resolve({
          status: 200,
          msg: data,
        })
      } else {
        resolve({
          status: 401,
        })
      }
    }, 300)
  })
}

const api = { getUser }
const userServer = thrift.createServer(User, api)

userServer.listen(9090)
Beispiel #28
0
    socket.on('error', function (exc) {
        console.log("ignoring exception: " + exc);
   });
});

var thrift = require('thrift');
       
var UserStorage = require('./gen-nodejs/SendStockDataTool.js'),
    ttypes = require('./gen-nodejs/SendStockDataTool_types');
       
var server = thrift.createServer(UserStorage, {
  sendStockData: function(stockdata, success) {
    console.log("server stored:");
    for(sc in clients)
    {
       console.log("clinet:");
       console.log("clinet:"+clients[sc].id);
       clients[sc].volatile.emit('message', stockdata);
    }
    success();
  },
});
server.listen(9799);

process.on('uncaughtException', function(err){
     console.log("error:"+err);
});




 
    });
    result(null, gateway);
};
var updGatewayInfo = function(gateway, result) {
    console.log("node server updGatewayInfo:",gateway);
    result(null);
};

var delGatewayInfo = function(id, result) {
    console.log("node server delGatewayInfo:", id);
    result(null,true);
};

var server = thrift.createServer(GatewayService, {
    getGatewayInfo: getGatewayInfo,
    updGatewayInfo: updGatewayInfo,
    delGatewayInfo: delGatewayInfo
},{transport: thrift.TBufferedTransport});

server.listen(9090,function(){
    console.log('server_buffered listen port 9090')
});

//var server_framed = thrift.createServer(GatewayService, {
//    getGatewayInfo: getGatewayInfo,
//    updGatewayInfo: updGatewayInfo,
//    delGatewayInfo: delGatewayInfo
//},{transport: thrift.TFramedTransport});
//
//server_framed.listen(9090,function(){
//    console.log('server_framed listen port 9090')
Beispiel #30
-1
  it('should send trace data to Scribe', done => {
    const logSpy = sinon.spy();
    const scribeHandler = {
      Log: (messages, result) => {
        logSpy(messages, result);
        result(ResultCode.OK);
      }
    };

    const server = thrift.createServer(Scribe, scribeHandler, {
      transport: thrift.TFramedTransport,
      protocol: thrift.TBinaryProtocol
    });
    const scribeServer = server.listen(0, () => {
      const port = scribeServer.address().port;
      const logger = new ScribeLogger({
        scribeHost: '127.0.0.1',
        scribePort: port,
        scribeInterval: 1
      });

      const ctxImpl = new ExplicitContext();
      const recorder = new BatchRecorder({logger});
      const tracer = new Tracer({recorder, ctxImpl});
      ctxImpl.scoped(() => {
        const id = new TraceId({
          traceId: new Some('abc'),
          parentId: new Some('def'),
          spanId: '123',
          sampled: new Some(true),
          flags: 0
        });
        tracer.setId(id);
        tracer.recordAnnotation(new Annotation.ServerAddr({serviceName: 'test'}));
        tracer.recordAnnotation(new Annotation.ClientSend());
        tracer.recordAnnotation(new Annotation.ClientRecv());
        setTimeout(() => {
          scribeServer.close();

          expect(logSpy.called).to.equal(true, 'Logger was not called as expected');
          const firstCall = logSpy.getCall(0);
          if (firstCall) {
            expect(firstCall.args[0][0].message).to.include(
              'CgABAAAAAAAACrwLAAMAAAAHVW5rbm93bgoABAAAAAAAAAEj');
          }
          done();
        }, 150);
      });
    });
  });