Beispiel #1
0
func GetMapAclients(db autorc.Conn, sqlstr string, makeFlag string, golog syslog.Writer) []d.Aclient {

	var aclientsmap []d.Aclient

	if stmt, err := db.Prepare(sqlstr); err != nil {

		golog.Err(err.Error())

	} else {

		if rows, res, err := stmt.Exec(); err != nil {

			golog.Err(err.Error())

		} else {

			aclientsmap = make([]d.Aclient, len(rows))

			for i, row := range rows {

				aclientsmap[i].Id = row.Int(res.Map("id"))
				aclientsmap[i].Phone = row.Str(res.Map("phone"))
				aclientsmap[i].Opcode = row.Str(res.Map("opcode"))
				aclientsmap[i].Nmake = makeFlag
				aclientsmap[i].Nupdatemake = row.Localtime(res.Map("nupdate_make"))

			}

		}
	}

	return aclientsmap

}
Beispiel #2
0
func xmlcheck(golog syslog.Writer, provider string, phone string, data []byte) {

	//	log.Println("GetUrl:xmlcheck check provider ", provider, "phone", phone)
	//
	//	<SmsResponse>
	//        <version>1</version>
	//        <result>1</result>
	//        <resultstring>success</resultstring>
	//        <description></description>
	//        <partcount>1</partcount>
	//        <endcause></endcause>
	//</SmsResponse>

	v := Dataxml{}
	err := xml.Unmarshal(data, &v)
	if err != nil {
		//		fmt.Printf("error: %v", err)
		golog.Err(err.Error())

		blockphone(phone)

	} else {

		//		fmt.Printf("Result: %q\n", v.Result)
		golog.Info(v.Result)

	}
}
Beispiel #3
0
func GetSqlMainosTel(golog syslog.Writer, db sql.DB, sqlstr string) []domains.MainosTel {
	var result []domains.MainosTel

	rows, err := db.Query(sqlstr)
	if err != nil {
		golog.Err(err.Error())
	}
	defer rows.Close()

	for rows.Next() {

		var phone string
		var smstext string
		err := rows.Scan(&phone, &smstext)
		if err != nil {
			golog.Err(err.Error())
		}

		var mainostel domains.MainosTel

		if !strings.HasPrefix(phone, "09") && !strings.Contains(phone, "070057") {

			mainostel.Phone = phone
			mainostel.Text = smstext
			result = append(result, mainostel)

		}

	}
	return result
}
Beispiel #4
0
func configParse(cfg *config, mainLogger *syslog.Writer) bool {
	const KEY = 0
	const VAL = 1
	file, err := os.Open(CONFIG_PATH)
	if err != nil {
		return false
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	newConf := false
	for scanner.Scan() {
		read := scanner.Text()
		if len(read) > 0 && read[0] != '#' {
			newConf = true
			pair := strings.Split(read, "=")
			trimmedKey := strings.TrimSpace(pair[KEY])
			trimmedVal := strings.TrimSpace(pair[VAL])
			val, _ := strconv.Atoi(trimmedVal)
			configUpdate(cfg, trimmedKey, uint16(val))
			mainLogger.Info(fmt.Sprintf("Custom setting found %s: %s", trimmedKey, trimmedVal))
		}
	}

	if !newConf {
		mainLogger.Info("No custom settings found, using defaults")
	}

	if err := scanner.Err(); err != nil {
		log.Fatal("Error: could not parse config file")
	}

	return true
}
Beispiel #5
0
func apiCount(s *mgo.Session, mlog *syslog.Writer) string {
	itemCount, listCount, err := dbCountLists(s)
	var countOut struct {
		ItemCount int
		List      []struct {
			Label string
			Count int
		}
	}

	countOut.ItemCount = listCount
	countOut.List = make([]struct {
		Label string
		Count int
	}, len(itemCount))
	i := 0
	for k, v := range itemCount {
		countOut.List[i].Label = k
		countOut.List[i].Count = v
		i += 1
	}

	out, err := json.MarshalIndent(countOut, "", "  ")
	if err != nil {
		mlog.Err("Error: could not properly construct json")
		return "Error"
	}
	return string(out)
}
Beispiel #6
0
// Reads from a queue and writes to writer until the queue channel
// is closed. Signals to a WaitGroup when done.
func write(queue chan []byte, writer *syslog.Writer, wg *sync.WaitGroup) {
	defer wg.Done()

	fmt.Println("writer started")

	var totalWrites int64 = 0
	var cumuWriteDuration int64 = 0

	for line := range queue {
		start := time.Now()

		writer.Write(line)
		//var _ = line

		totalWrites++
		cumuWriteDuration += time.Now().Sub(start).Nanoseconds() / 1000
	}

	fmt.Println("writer shutting down")

	avgWriteDuration := float64(cumuWriteDuration) / float64(totalWrites)

	fmt.Println("total lines written: ", totalWrites)
	fmt.Printf("avg write duration (us): %.3v\n", avgWriteDuration)
}
Beispiel #7
0
func SendSMS(golog syslog.Writer, clphonenum string, text string, site string) {

	var smsout d.Smsout

	if text == "" {

		golog.Info("Send first SMS on " + clphonenum)
		smsout.Phoneto = strings.Replace(clphonenum, "358", "0", 1)
		smsout.Text = "Soita! Miia. puh. 070095943"
		smsout.Phonefrom = "070095943"
		smsout.Opcode = "notImpotent"
		smsout.Nmake = "notImpotent"

	} else {
		golog.Info("Send Second SMS on " + clphonenum + " " + text)

		smsout.Phoneto = strings.Replace(clphonenum, "358", "0", 1)
		smsout.Text = text
		smsout.Phonefrom = "070095943"
		smsout.Opcode = "notImpotent"
		smsout.Nmake = "notImpotent"

	}

	pr.SmsSendBy("sonera", smsout, golog)

}
Beispiel #8
0
func apiGet(s *mgo.Session, label string, todo string, mlog *syslog.Writer) string {
	if len(label) == 0 {
		return ""
	}

	list, err := dbQuery(s, label)
	if err != nil {
		mlog.Err("Error: db query went bad: " + err.Error())
		return "Error"
	}

	todos := make([]TodoItem, len(list))
	count := 0
	for i, todo := range list {
		todos[i].Text = todo.Text
		todos[i].Id = todo.Id.Hex()
		count += 1
	}
	jsonOut := struct {
		Label string
		Count int
		Todos []TodoItem
	}{label, count, todos}

	out, err := json.MarshalIndent(jsonOut, "", "  ")
	if err != nil {
		mlog.Err("Error: could not properly construct json")
		return "Error"
	}
	return string(out)
}
Beispiel #9
0
func (this *Server) StartDrainer(address string, filter EntryFilter) *Drainer {
	c := make(chan Entry)
	listener := &Listener{
		Channel:   c,
		Filter:    filter,
		LastEntry: time.Now(),
	}
	this.AddListener <- listener

	drainer := &Drainer{
		Address:   address,
		Filter:    filter,
		server:    this,
		listener:  listener,
		terminate: make(chan bool, 1),
	}
	go func() {
		var w *syslog.Writer
		var err error
		for entry := range Throttle(c, 100) {
			for {
				// If we terminated give up
				select {
				case <-drainer.terminate:
					return
				default:
				}

				// Connect
				if w == nil {
					log.Printf("connecting to syslog://%v\n", address)
					w, err = syslog.Dial("tcp", address, syslog.LOG_INFO, "")
					if err != nil {
						w = nil
						time.Sleep(time.Second * 5)
						continue
					}
				}
				// Send the message
				_, err = w.Write(entry.Line())
				if err != nil {
					w.Close()
					w = nil
					time.Sleep(time.Second * 5)
					continue
				}

				// Successfully sent the message so break
				break
			}
		}
	}()
	return drainer
}
Beispiel #10
0
func apiRemove(s *mgo.Session, label string, id string, mlog *syslog.Writer) string {
	if len(label) == 0 {
		return ""
	}

	err := dbRemove(s, label, MongoTodo{Id: bson.ObjectIdHex(id), Text: ""})
	if err != nil {
		mlog.Err("Error: db remove went bad: " + err.Error())
		return "Error"
	}
	return "Removing: " + id + " from: " + label
}
Beispiel #11
0
func apiAdd(s *mgo.Session, label string, todo string, mlog *syslog.Writer) string {
	if len(label) == 0 {
		return ""
	}

	newTodo := MongoTodo{Id: bson.NewObjectId(), Text: todo}
	err := dbInsert(s, label, newTodo)
	if err != nil {
		mlog.Err("Error: db insert went bad: " + err.Error())
		return "Error"
	}
	return newTodo.Id.Hex()
}
Beispiel #12
0
func InsertSmsRecord(db autorc.Conn, sqlstr string, golog syslog.Writer) {

	if stmt, err := db.Prepare(sqlstr); err != nil {

		golog.Err(err.Error())

	} else {
		if _, _, err := stmt.Exec(); err != nil {

			golog.Err(err.Error())

		}

	}

}
Beispiel #13
0
func GetLastMainos() {

	var golog syslog.Writer
	var config domains.Config

	confstr := config.Database.User + ":" + config.Database.Passwd + "@/" + config.Database.Database + "?parseTime=true"

	db, err := sql.Open("mysql", confstr)
	if err != nil {
		golog.Err(err.Error())
	}
	defer db.Close()

	sql2.GetSqlMainosTel(golog, *db, "select count(*) from calls where cdate>=curdate()")

}
Beispiel #14
0
func sendToSyslog(message *nats.Msg, syslog *syslog.Writer) {
	logMessage := buildLogMessage(message)
	logger.Debug("message-sent-to-syslog", lager.Data{"message": logMessage})
	err := syslog.Info(logMessage)
	if err != nil {
		logger.Error("logging-to-syslog-failed", err)
		stop <- true
	}
}
Beispiel #15
0
func fanControl(cfg *config, mainLogger *syslog.Writer) {
	currTemp := getTemp()
	prevTemp := currTemp
	prevLvl := uint16(1)
	currLvl := getFanLevel(cfg, currTemp, prevTemp, prevLvl)
	for {
		if prevLvl != currLvl {
			setFanLevel(currLvl)
			mainLogger.Debug(fmt.Sprintf("Fan level changed: %d -> %d (%d -> %d)",
				prevLvl, currLvl, prevTemp, currTemp))
		} else {
			mainLogger.Debug(fmt.Sprintf("Fan level remained: %d (%d -> %d)", currLvl, prevTemp, currTemp))
		}

		time.Sleep(time.Second * time.Duration(cfg.pollInterval))
		prevTemp = currTemp
		currTemp = getTemp()
		prevLvl = currLvl
		currLvl = getFanLevel(cfg, currTemp, prevTemp, prevLvl)
	}
}
Beispiel #16
0
func GetSqlInt(golog syslog.Writer, db sql.DB, sqlstr string) int {

	var result int

	rows, err := db.Query(sqlstr)
	if err != nil {
		golog.Err(err.Error())
	}
	defer rows.Close()

	for rows.Next() {

		err := rows.Scan(&result)
		if err != nil {
			golog.Err(err.Error())
		}

	}

	return result

}
Beispiel #17
0
func GetMobileClientId(golog syslog.Writer, db sql.DB, sqlstr string) int {

	var cliID int

	rows, err := db.Query(sqlstr)
	if err != nil {
		golog.Err(err.Error())
	}
	defer rows.Close()

	for rows.Next() {

		err := rows.Scan(&cliID)
		if err != nil {
			golog.Err(err.Error())
		}

	}

	return cliID

}
Beispiel #18
0
func GetUrl(golog syslog.Writer, provider string, phone string, urlstr string) {

	if res, err := http.Get(urlstr); err != nil {
		log.Fatalf("Get: %v", err)
		golog.Err(err.Error())
	} else {

		if data, err := ioutil.ReadAll(res.Body); err != nil {

			log.Fatalf("Get: %v", err)
			golog.Err(err.Error())

		} else {
			//			fmt.Printf("out %s", string(data))

			if provider == "voicetr" {

				xmlcheck(golog, provider, phone, data)

			}

		}
	}
}
// Get a list of devices from ring file and virtual mount them using libgfapi
func SetupGlusterDiskFile(serverconf *hummingbird.IniFile, logger *syslog.Writer) (map[string]interface{}, error) {
	hashPathPrefix, hashPathSuffix, _ := hummingbird.GetHashPrefixAndSuffix()
	objRing, _ := hummingbird.GetRing("object", hashPathPrefix, hashPathSuffix)
	bindPort := int(serverconf.GetInt("app:object-server", "bind_port", 6000))
	localDevices, _ := objRing.LocalDevices(bindPort)

	globals := make(map[string]interface{})
	globals["disableFallocate"] = serverconf.GetBool("app:object-server", "disable_fallocate", false)
	globals["glusterVolumes"] = make(map[string]*gfapi.Volume)

	var ret int
	var err error
	for _, dev := range localDevices {
		globals["glusterVolumes"].(map[string]*gfapi.Volume)[dev.Device] = new(gfapi.Volume)

		ret = globals["glusterVolumes"].(map[string]*gfapi.Volume)[dev.Device].Init("localhost", dev.Device)
		if ret < 0 {
			return nil, errors.New(fmt.Sprintf("Volume %s: Init() failed with ret = %d", dev.Device, ret))
		}

		ret, err = globals["glusterVolumes"].(map[string]*gfapi.Volume)[dev.Device].SetLogging("", gfapi.LogDebug)
		if ret < 0 {
			//FIXME: There's a bug in SetLogging: err != nil even when ret = 0
			return nil, errors.New(fmt.Sprintf("Volume %s: SetLogging() failed with ret = %d, error = %s", dev.Device, ret, err.Error()))
		}

		ret = globals["glusterVolumes"].(map[string]*gfapi.Volume)[dev.Device].Mount()
		if ret < 0 {
			return nil, errors.New(fmt.Sprintf("Volume %s: Mount() failed with ret = %d", dev.Device, ret))
		}

		logger.Info(fmt.Sprintf("GlusterFS volume %s sucessfully virtual mounted.", dev.Device))
	}

	return globals, nil
}
Beispiel #20
0
func UpdateAclient(golog syslog.Writer, db sql.DB, sqlstr string) {

	if stmt, err := db.Prepare(sqlstr); err != nil {

		golog.Err(err.Error())

	} else {

		if _, err := stmt.Exec(); err != nil {

			golog.Err(err.Error())

		} else {

			golog.Info("Aclient updated")

		}

	}

}
Beispiel #21
0
func InsertMobileClient(golog syslog.Writer, db sql.DB, sqlstr string) {

	if stmt, err := db.Prepare(sqlstr); err != nil {

		golog.Err(err.Error())

	} else {

		if _, err := stmt.Exec(); err != nil {

			golog.Err(err.Error())

		} else {

			golog.Info("New Client arrived!!!")

		}

	}

}
Beispiel #22
0
func dequeue(syslogLog *syslog.Writer, mongoHref string, mongoDatabaseName string, mongoCollectionName string, amqpHref string, amqpExchange string, amqpExchangeType string) {

	//DEBUG
	syslogLog.Notice("[dequeue] BEGIN")
	syslogLog.Notice(fmt.Sprintf("    [dequeue]           mongoHref = [%v]", mongoHref))
	syslogLog.Notice(fmt.Sprintf("    [dequeue]   mongoDatabaseName = [%v]", mongoDatabaseName))
	syslogLog.Notice(fmt.Sprintf("    [dequeue] mongoCollectionName = [%v]", mongoCollectionName))
	syslogLog.Notice(fmt.Sprintf("    [dequeue]            amqpHref = [%v]", amqpHref))
	syslogLog.Notice(fmt.Sprintf("    [dequeue]        amqpExchange = [%v]", amqpExchange))
	syslogLog.Notice(fmt.Sprintf("    [dequeue]    amqpExchangeType = [%v]", amqpExchangeType))

	// Deal with parameters.
	if "" == mongoHref {
		errMsg := fmt.Sprintf("    [dequeue] Bad mongoHref. Received: [%v].", mongoHref)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == mongoDatabaseName {
		errMsg := fmt.Sprintf("    [dequeue] Bad mongoDatabaseName. Received: [%v].", mongoDatabaseName)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == mongoCollectionName {
		errMsg := fmt.Sprintf("    [dequeue] Bad mongoCollectionName. Received: [%v].", mongoCollectionName)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpHref {
		errMsg := fmt.Sprintf("    [dequeue] Bad amqpHref. Received: [%v].", amqpHref)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	// Connect to MongoDB
	mongoSession, err := mgo.Dial(mongoHref)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [dequeue] Could NOT connect to MongoDB at [%v], received err = [%v]", mongoHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}
	defer mongoSession.Close()

	// Optional. Switch the session to a monotonic behavior.
	mongoSession.SetMode(mgo.Monotonic, true)

	mongoCollection := mongoSession.DB(mongoDatabaseName).C(mongoCollectionName)

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [dequeue] Connected to MongoDB with %v.%v", mongoDatabaseName, mongoCollectionName))

	// Connect to AMQP.
	amqpConnection, err := amqp.Dial(amqpHref)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [dequeue] Could NOT connect to AMQP server (RabbitMQ?) at [%v], received err = [%v]", amqpHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}
	defer amqpConnection.Close()

	amqpChannel, err := amqpConnection.Channel()
	if err != nil {
		syslogLog.Err("    [dequeue] Could NOT get AMQP channel")
		panic(err)
		/////////////////////// RETURN
		return
	}

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [dequeue] amqpChannel = [%v]", amqpChannel))

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [dequeue] Connected to AMQP server (RabbitMQ?)", mongoDatabaseName, mongoCollectionName))

	// Forever
	for {

		//DEBUG
		syslogLog.Notice("    [dequeue] =-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-= LOOP")

		// Check MongoDB for items that are ready.
		mongoCriteria := bson.M{"when": bson.M{"$lte": bson.Now()}}

		mongoQuery := mongoCollection.Find(mongoCriteria)

		//DEBUG
		syslogLog.Notice(fmt.Sprintf("    [dequeue] mongoQuery = [%v]", mongoQuery))

		if nil != err {
			syslogLog.Err(fmt.Sprintf("    [dequeue] Error querying MongoDB with mongoCriteria = [%v] received err = [%v]", mongoCriteria, err))
		} else {

			syslogLog.Notice(fmt.Sprintf("    [dequeue] Success querying MongoDB with mongoCriteria = [%v]", mongoCriteria, err))

			//					var x struct{
			//						_Id    bson.ObjectId
			//						When   time.Time
			//						Target string
			//						Message map[string]interface{}
			//					}

			x := map[string]interface{}{}

			items := mongoQuery.Iter()
			for items.Next(&x) {

				//DEBUG
				syslogLog.Notice(fmt.Sprintf("        [dequeue] Received row: [%v]", x))

				//						routingKey := x.Target
				routingKey := x["target"].(string)

				//DEBUG
				syslogLog.Notice(fmt.Sprintf("        [dequeue] Routing Key : [%v]", routingKey))

				//						body, err := json.Marshal(x.Message)
				body, err := json.Marshal(x["message"])
				if nil != err {
					//DEBUG
					syslogLog.Err(fmt.Sprintf("        [dequeue] Error serializing body into JSON, received err = [%v]", err))
					//@TODO #############################################################################

				}

				//DEBUG
				syslogLog.Notice(fmt.Sprintf("        [dequeue] Body : [%v]", body))

				//DEBUG
				syslogLog.Notice(fmt.Sprintf("        [dequeue] Routing key: [%v]", routingKey))
				syslogLog.Notice(fmt.Sprintf("        [dequeue] declared Exchange, publishing %dB body (%s)", len(body), body))

				if err = amqpChannel.Publish(
					amqpExchange, // publish to an exchange
					routingKey,   // routing to 0 or more queues
					false,        // mandatory
					false,        // immediate
					amqp.Publishing{
						Headers:         amqp.Table{},
						ContentType:     "text/plain",
						ContentEncoding: "",
						Body:            body,
						DeliveryMode:    amqp.Transient, // 1=non-persistent, 2=persistent
						Priority:        0,              // 0-9
						// a bunch of application/implementation-specific fields
					},
				); err != nil {

					//DEBUG
					syslogLog.Err(fmt.Sprintf("        [dequeue] Error: Exchange Publish: [%v]", err))
				} else {

					//DEBUG
					syslogLog.Err("        [dequeue] Published")
				}

				// Delete from MongoDB.
				//							err = mongoCollection.RemoveId(x._Id)
				err = mongoCollection.RemoveId(x["_id"])
				if nil != err {
					//DEBUG
					//								syslogLog.Err(  fmt.Sprintf("        [dequeue] Could NOT remove item from Mongo with _id [%v], received err = [%v]", x._Id, err)  )
					syslogLog.Err(fmt.Sprintf("        [dequeue] Could NOT remove item from Mongo with _id [%v], received err = [%v]", x["_id"], err))
				} else {
					//DEBUG
					//								syslogLog.Notice(  fmt.Sprintf("        [dequeue] Removed item from Mongo with _id [%v]", x._Id)  )
					syslogLog.Notice(fmt.Sprintf("        [dequeue] Removed item from Mongo with _id [%v]", x["_id"]))
				}

			} // for

			syslogLog.Notice("    [dequeue] Done iterating through result of query.")
		}

		// Sleep for a while before checking again.
		sleepTime := time.Duration(5+rand.Intn(7)) * time.Second

		//DEBUG
		syslogLog.Notice(fmt.Sprintf("    [dequeue] sleep for %v", sleepTime))

		time.Sleep(sleepTime)
	} // for

	//DEBUG
	syslogLog.Notice("[dequeue] END")

}
Beispiel #23
0
// Output each metric in the given registry to syslog periodically using
// the given syslogger.  The interval is to be given in seconds.
func Syslog(r Registry, interval int, w *syslog.Writer) {
	for {
		r.Each(func(name string, i interface{}) {
			switch m := i.(type) {
			case Counter:
				w.Info(fmt.Sprintf("counter %s: count: %d", name, m.Count()))
			case Gauge:
				w.Info(fmt.Sprintf("gauge %s: value: %d", name, m.Value()))
			case Healthcheck:
				m.Check()
				w.Info(fmt.Sprintf("healthcheck %s: error: %v", name, m.Error()))
			case Histogram:
				ps := m.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
				w.Info(fmt.Sprintf(
					"histogram %s: count: %d min: %d max: %d mean: %.2f stddev: %.2f median: %.2f 75%%: %.2f 95%%: %.2f 99%%: %.2f 99.9%%: %.2f",
					name,
					m.Count(),
					m.Min(),
					m.Max(),
					m.Mean(),
					m.StdDev(),
					ps[0],
					ps[1],
					ps[2],
					ps[3],
					ps[4],
				))
			case Meter:
				w.Info(fmt.Sprintf(
					"meter %s: count: %d 1-min: %.2f 5-min: %.2f 15-min: %.2f mean: %.2f",
					name,
					m.Count(),
					m.Rate1(),
					m.Rate5(),
					m.Rate15(),
					m.RateMean(),
				))
			case Timer:
				ps := m.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
				w.Info(fmt.Sprintf(
					"timer %s: count: %d min: %d max: %d mean: %.2f stddev: %.2f median: %.2f 75%%: %.2f 95%%: %.2f 99%%: %.2f 99.9%%: %.2f 1-min: %.2f 5-min: %.2f 15-min: %.2f mean: %.2f",
					name,
					m.Count(),
					m.Min(),
					m.Max(),
					m.Mean(),
					m.StdDev(),
					ps[0],
					ps[1],
					ps[2],
					ps[3],
					ps[4],
					m.Rate1(),
					m.Rate5(),
					m.Rate15(),
					m.RateMean(),
				))
			}
		})
		time.Sleep(time.Duration(int64(1e9) * int64(interval)))
	}
}
Beispiel #24
0
func enqueue(syslogLog *syslog.Writer, mongoHref string, mongoDatabaseName string, mongoCollectionName string, amqpHref string, amqpExchange string, amqpExchangeType string, amqpQueue string) {

	//DEBUG
	syslogLog.Notice("[enqueue] BEGIN")
	syslogLog.Notice(fmt.Sprintf("    [enqueue]           mongoHref = [%v]", mongoHref))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]   mongoDatabaseName = [%v]", mongoDatabaseName))
	syslogLog.Notice(fmt.Sprintf("    [enqueue] mongoCollectionName = [%v]", mongoCollectionName))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]            amqpHref = [%v]", amqpHref))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]        amqpExchange = [%v]", amqpExchange))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]    amqpExchangeType = [%v]", amqpExchangeType))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]           amqpQueue = [%v]", amqpQueue))

	// Deal with parameters.
	if "" == mongoHref {
		errMsg := fmt.Sprintf("    [enqueue] Bad mongoHref. Received: [%v].", mongoHref)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == mongoDatabaseName {
		errMsg := fmt.Sprintf("    [enqueue] Bad mongoHref. Received: [%v].", mongoDatabaseName)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == mongoCollectionName {
		errMsg := fmt.Sprintf("    [enqueue] Bad mongoHref. Received: [%v].", mongoCollectionName)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpHref {
		errMsg := fmt.Sprintf("    [enqueue] Bad amqpHref. Received: [%v].", amqpHref)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpExchange {
		errMsg := fmt.Sprintf("    [enqueue] Bad amqpExchange. Received: [%v].", amqpExchange)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpExchangeType {
		errMsg := fmt.Sprintf("    [enqueue] Bad amqpExchangeType. Received: [%v].", amqpExchangeType)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpQueue {
		errMsg := fmt.Sprintf("    [enqueue] Bad amqpQueue. Received: [%v].", amqpQueue)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	// Connect to AMQP.
	amqpConnection, err := amqp.Dial(amqpHref)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [enqueue] Could NOT connect to AMQP server (RabbitMQ?) at [%v], received err = [%v]", amqpHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}
	defer amqpConnection.Close()

	amqpChannel, err := amqpConnection.Channel()
	if err != nil {
		syslogLog.Err("    [enqueue] Could NOT get AMQP channel")
		panic(err)
		/////////////////////// RETURN
		return
	}

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [enqueue] amqpChannel = [%v]", amqpChannel))

	// Connect to MongoDB
	mongoSession, err := mgo.Dial(mongoHref)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [enqueue] Could NOT connect to MongoDB at [%v], received err = [%v]", mongoHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}
	defer mongoSession.Close()

	// Optional. Switch the session to a monotonic behavior.
	mongoSession.SetMode(mgo.Monotonic, true)

	mongoCollection := mongoSession.DB(mongoDatabaseName).C(mongoCollectionName)

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [enqueue] Connected to MongoDB with %v.%v", mongoDatabaseName, mongoCollectionName))

	// AMQP queue bind.
	amqpKey := amqpQueue

	if err = amqpChannel.QueueBind(
		amqpQueue,    // name of the queue
		amqpKey,      // bindingKey
		amqpExchange, // sourceExchange
		false,        // noWait
		nil,          // arguments
	); err != nil {
		syslogLog.Err(fmt.Sprintf("    [enqueue] Could NOT bind to queue [%v] on AMQP server (RabbitMQ?) at [%v], received err = [%v]", amqpQueue, amqpHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}

	//DEBUG
	syslogLog.Notice("    [enqueue] Queue bound.")

	// Set up AMQP consumer.
	amqpDeliveries, err := amqpChannel.Consume(
		amqpQueue,  // name
		"turtledq", // consumerTag
		false,      // noAck
		false,      // exclusive
		false,      // noLocal
		false,      // noWait
		nil,        // arguments
	)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [enqueue] Could NOT get deliverables from queue [%v] on AMQP server (RabbitMQ?) at [%v], received err = [%v]", amqpQueue, amqpHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}

	// Forever
	for d := range amqpDeliveries {

		//DEBUG
		syslogLog.Notice("        [enqueue] =-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-= LOOP")
		syslogLog.Notice(fmt.Sprintf("        [enqueue] got %dB message: [%v]", len(d.Body), d.DeliveryTag))
		syslogLog.Notice(fmt.Sprintf("        [enqueue] THING: [%v]", d))

		sjson, err := simplejson.NewJson(d.Body)
		if nil != err {
			//DEBUG
			syslogLog.Err(fmt.Sprintf("        [enqueue] Could NOT parse raw JSON: [%v]", d.Body))
			//@TODO ##################################################################################################################
		}

		//DEBUG
		syslogLog.Notice(fmt.Sprintf("        [enqueue] json = [%#v]", sjson))

		haveTarget := true
		messageTarget, err := sjson.Get("target").String()
		if nil != err {
			haveTarget = false
		}

		//DEBUG
		if haveTarget {
			syslogLog.Notice(fmt.Sprintf("        [enqueue] target = [%v]", messageTarget))
		} else {
			syslogLog.Notice("        [enqueue] either do NOT have messageTarget (or did not receive a \"good\" one)")
		}

		haveWhen := true
		messageWhen, err := sjson.Get("when").Int64()
		if nil != err {
			haveWhen = false
		}

		//DEBUG
		if haveWhen {
			syslogLog.Notice(fmt.Sprintf("        [enqueue] when = [%v]", messageWhen))
		} else {
			syslogLog.Notice("        [enqueue] either do NOT have messageTarget (or did not receive a \"good\" one)")
		}

		haveMessage := true
		messageMessage, err := sjson.Get("message").Map()
		if nil != err {
			haveMessage = false
		}

		//DEBUG
		if haveMessage {
			syslogLog.Notice(fmt.Sprintf("        [enqueue] message = [%v]", messageMessage))
		} else {
			syslogLog.Notice("        [enqueue] either do NOT have messageMessage (or did not receive a \"good\" one)")
		}

		// Deal with corrupted items.
		if !haveTarget || !haveWhen || !haveMessage {

			//DEBUG
			syslogLog.Notice("        [enqueue] Empty item from AMQP queue. Will ACK early and continue.")

			// Ack.
			err = d.Ack(false)
			if nil != err {
				syslogLog.Err(fmt.Sprintf("        [enqueue] ERROR EARLY ACKing: [%v]", err))
			}

			//DEBUG
			syslogLog.Notice("        [enqueue] EARLY ACKed")

			/////////////////////// CONTINUE
			continue
		}

		// Enqueue the item
		mongoDoc := bson.M{
			"target":  messageTarget,
			"when":    time.Unix(messageWhen, 0),
			"message": messageMessage}

		err = mongoCollection.Insert(mongoDoc)
		if nil != err {
			syslogLog.Err(fmt.Sprintf("        [enqueue] ERROR Inserting into Mongo: [%v]", err))
			//@TODO ###############################################################################################
		}

		syslogLog.Notice(fmt.Sprintf("        [enqueue] Inserted into Mongo: [%v]", mongoDoc))

		// Ack.
		err = d.Ack(false)
		if nil != err {
			syslogLog.Err(fmt.Sprintf("        [enqueue] ERROR ACKing: [%v]", err))
		}

		//DEBUG
		syslogLog.Notice("        [enqueue] ACKed")

		//			sleepTime := time.Duration(5 + rand.Intn(7)) * time.Second
		//
		//			//DEBUG
		//			syslogLog.Notice( fmt.Sprintf("    [enqueue] sleep for %v", sleepTime) )
		//
		//			time.Sleep(sleepTime)
	} // for

	//DEBUG
	syslogLog.Notice("[enqueue] END")

}
Beispiel #25
0
func SmsSendBy(provider string, smsout d.Smsout, golog syslog.Writer) {

	var urlstr string

	if provider == "elisa" {

		if Url, err := url.Parse("http://localhost:13013"); err != nil {

			panic("boom")
		} else {

			Url.Path += "/cgi-bin/sendsms"
			parameters := url.Values{}
			parameters.Add("username", "elisa")
			parameters.Add("password", "elisa")
			//		parameters.Add("charset", "ISO-8859-1")
			parameters.Add("charset", "UTF8")
			parameters.Add("to", smsout.Phoneto)
			//				parameters.Add("to", "+358504440106") //for test
			//		parameters.Add("from", smsout.Phonefrom)
			parameters.Add("text", smsout.Text)

			Url.RawQuery = parameters.Encode()
			urlstr = Url.String()

		}

	} else if provider == "sonera" {

		if Url, err := url.Parse("http://localhost:8050"); err != nil {

			panic("boom")
		} else {

			Url.Path += "/send"
			parameters := url.Values{}

			parameters.Add("to", smsout.Phoneto)

			parameters.Add("from", strings.Replace(smsout.Phonefrom, "+3587", "07", 1))
			textout := Utf8Conver(smsout.Text, "iso-8859-1")
			parameters.Add("msg", textout)

			Url.RawQuery = parameters.Encode()
			urlstr = Url.String()

		}

	} else if provider == "voicetr" {

		//		log.Println("start voicetr new 11")
		golog.Info("start voicetr")

		if Url, err := url.Parse("https://www.voicetrading.com"); err != nil {

			panic("boom")
		} else {

			Url.Path += "/myaccount/sendsms.php"
			parameters := url.Values{}
			parameters.Add("username", "voicetradingsipvip")
			parameters.Add("password", "164sipviprel")
			//		parameters.Add("charset", "ISO-8859-1")
			parameters.Add("charset", "UTF8")
			parameters.Add("to", smsout.Phoneto)
			//			parameters.Add("to", "+358451202801") /for test
			//							parameters.Add("to", "+358504440106") //for test
			parameters.Add("from", smsout.Phonefrom)
			parameters.Add("text", smsout.Text)

			Url.RawQuery = parameters.Encode()
			urlstr = Url.String()

		}

	} else if provider == "pullpull" {

		if Url, err := url.Parse("http://localhost:13013"); err != nil {

			panic("boom")
		} else {

			if smsout.Opcode == "54" {

				Url.Path += "/cgi-bin/sendsms"
				parameters := url.Values{}
				parameters.Add("username", "dna179029")
				parameters.Add("password", "dna179029")
				//		parameters.Add("charset", "ISO-8859-1")
				parameters.Add("charset", "UTF8")
				parameters.Add("to", smsout.Phoneto)
				parameters.Add("binfo", "2900")
				//				parameters.Add("to", "+358504440106") //for test
				//		parameters.Add("from", smsout.Phonefrom)
				parameters.Add("text", smsout.Text)

				Url.RawQuery = parameters.Encode()
				urlstr = Url.String()

			}

		}
	}
	//	log.Println(urlstr)
	//	fmt.Println(urlstr)
	golog.Info(urlstr)

	GetUrl(golog, provider, smsout.Phoneto, urlstr)

}
Beispiel #26
0
func Hello(mod *Model, logger *syslog.Writer, version string) string {
	s := fmt.Sprintf("Model=>%v, Version=>%s", mod, version)
	logger.Info(s)
	return s
}
Beispiel #27
0
//checkError basic error handling
func CheckError(err error, logger *syslog.Writer) {
	if err != nil {
		logger.Crit(fmt.Sprintln("Fatal error", err.Error()))
		os.Exit(1)
	}
}
Beispiel #28
0
func Settasks(makeFlag string, days int, quant int, golog syslog.Writer) {

	quantstr := strconv.Itoa(quant)
	daysstr := strconv.Itoa(days)

	var sqlselectstr string

	if makeFlag == "gsm179019" {
		sqlselectstr = "select * from aclients where (block = 0 and sulje = 0 and ennu = 0 and nmake <> '" + makeFlag + "' and opcode in (50,54,56,49,79,'na') and nupdate_make <=adddate(now(), -" + daysstr + ") and rating>5) or (nmake IS NULL and block = 0 and opcode in (50,54,56,49,79,'na')) order by id desc limit " + quantstr
	}
	if makeFlag == "voicetr" {
		sqlselectstr = "select * from aclients where (block = 0 and sulje = 0 and ennu = 0 and nmake <> '" + makeFlag + "' and opcode in (50,54,56,49,79,'na') and nupdate_make <=adddate(now(), -" + daysstr + ")) or (nmake IS NULL and block = 0 and opcode in (50,54,56,49,79,'na')) order by id desc limit " + quantstr
	}
	if makeFlag == "sms179019" {
		sqlselectstr = "select * from aclients where (block = 0 and sulje = 0 and ennu = 0 and nmake <> '" + makeFlag + "' and opcode in (50,54,56,49,79,'na') and nupdate_make <=adddate(now(), -" + daysstr + ") and smsquant>1) or (nmake IS NULL and block = 0 and opcode in (50,54,56,49,79,'na')) order by id desc limit " + quantstr
	}

	if makeFlag == "sms179029" {
		sqlselectstr = "select * from aclients where (block = 0 and sulje = 0 and ennu = 0 and nmake <> '" + makeFlag + "' and opcode in (54) and nupdate_make <=adddate(now(), -" + daysstr + ") ) or (nmake IS NULL and block = 0 and opcode in (54)) order by id desc limit " + quantstr
	}

	db.Raw.Register("SET NAMES utf8")
	var aclienmap = sql.GetMapAclients(*db, sqlselectstr, makeFlag, golog)

	golog.Info("Ready Settask for " + strconv.Itoa(len(aclienmap)))

	if aclientupdate_stmt, err := db.Prepare("update aclients set nmake = ?,nupdate_make = now() where id = ?"); err != nil {

		golog.Err(err.Error())

	} else {

		for _, Aclient := range aclienmap {

			fmt.Println(Aclient.Phone)
			fmt.Println(Aclient.Opcode)
			fmt.Println(Aclient.Nmake)
			fmt.Println("---------")

			if _, _, err := aclientupdate_stmt.Exec(makeFlag, Aclient.Id); err != nil {
				golog.Err(err.Error())
			}

		}

		jsbyte, _ := json.Marshal(aclienmap)

		buff := bytes.NewBuffer(jsbyte)

		client := &http.Client{}

		if req, err := http.NewRequest("POST", "http://latest.kannelgo.sinelgamysql.appspot.com/settasks", buff); err != nil {

			fmt.Printf("Error: %v\n", err)

		} else {

			req.Header.Add("makeFlag", makeFlag)

			if resp, err1 := client.Do(req); err1 != nil {
				fmt.Printf("Error: %v\n", err1)
			} else {
				defer resp.Body.Close()
				body, _ := ioutil.ReadAll(resp.Body)
				fmt.Println("Body: %s\n", body)
			}

		}

	}

}
Beispiel #29
0
func newSyslogAdapter(w *syslog.Writer) *LoggingAdapter {
	return &LoggingAdapter{
		Debugf: func(format string, v ...interface{}) { w.Debug(fmt.Sprintf(format, v...)) },
		Infof:  func(format string, v ...interface{}) { w.Info(fmt.Sprintf(format, v...)) },
		Warnf:  func(format string, v ...interface{}) { w.Warning(fmt.Sprintf(format, v...)) },
		Errorf: func(format string, v ...interface{}) { w.Err(fmt.Sprintf(format, v...)) },
		Fatalf: func(format string, v ...interface{}) {
			s := fmt.Sprintf(format, v...)

			w.Crit(s)

			os.Exit(1)
		},
		Panicf: func(format string, v ...interface{}) {
			s := fmt.Sprintf(format, v...)

			w.Emerg(s)

			panic(s)
		},
	}
}
Beispiel #30
0
func NewTurtleConfig(syslogLog *syslog.Writer) (*TurtleConfig, error) {

	//DEBUG
	syslogLog.Notice("    [CONFIG] BEGIN.")

	cmdPath := os.Args[0]
	cmdPathLastSlash := strings.LastIndexFunc(cmdPath, func(c rune) bool {
		return '/' == c
	})

	cmdDirPath := cmdPath[0:cmdPathLastSlash]

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] command path: [%v]", cmdPath))
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] command path last slash: [%v]", cmdPathLastSlash))
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] command dir path: [%v]", cmdDirPath))

	confRelativePath := "turtledq.ini"
	confPath := cmdDirPath + "/" + confRelativePath

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] settings file relative path: [%v]", confRelativePath))
	syslogLog.Notice(fmt.Sprintf("    [CONFIG] settings file absolute path: [%v]", confPath))

	return NewTurtleConfigFromFile(syslogLog, confPath)
}