Prometheus gauge with custom collector - go - loops

i have problem on "reseting" the values for gauges because "life stops" as soon http servervice is started or when i start looping my "runJob" then is server not started..
the way how i am trying to establish this:
i load all the Job-s from YAML array.
i generate gauges from that, then i run loop to get some values for them.
Then i register them.
And after that i start http service for prometheus.
All works perfect, until next cycle - next cycle is just not starting.
I tryed to move functions inside functions etc..
so thats my main function:
//gets poll time from yaml (60s)
timerCh := time.Tick(time.Duration(appConf.PollTimeSec) * time.Second)
//loop after given time
for range timerCh {
runJobs()
}
//start new muxServer
server := http.NewServeMux()
log.Println("DEBUG: Starting server")
server.Handle(appConf.HostPath, promhttp.Handler())
http.ListenAndServe(":"+appConf.ListenerPort, server)
and my runJobs function basicly gets Http response codes
and ads them to prometheus gauge values.
-- everything is OK with that and it works very well on starting, but after i try to start it wheet sleep (as shown in main go) it just gets stuck -
Server is up and values do not change.
So i have (my optinion) two possible ways of fixing it:
My "runJobs" is infinitive loop what runs after every minute
thats why is server not started.
But when i add there a if statement that on first run(cycle) should server be started, then it still gets stuck when server gets started (next loop cycle just woun't get started)
And the other part, when i start the server first, then it never gets to the part where it starts runJobs()
Prefered outcome should be that:
server is started with first values, and after every minute it runs "runJobs" again.

The way it is written, your program will not go beyond that for loop. Try this instead:
go func() {
//loop after given time
for range timerCh {
runJobs()
}
}()
This runs the for loop in its own goroutine, and runJobs executes every so often.

Related

CANOPEN SYNC timeout after enable Operation

I am a newbie in CANOPEN. I wrote a program that read actual position via PDO1 (default is statusword + actual position).
void canopen_init() {
// code1 setup PDO mapping
nmtPreOperation();
disablePDO(PDO_TX1_CONFIG_COMM);
setTransmissionTypePDO(PDO_TX1_CONFIG_COMM, 1);
setInhibitTimePDO(PDO_TX1_CONFIG_COMM, 0);
setEventTimePDO(PDO_TX1_CONFIG_COMM, 0);
enablePDO(PDO_TX1_CONFIG_COMM);
setCyclePeriod(1000);
setSyncWindow(100);
//code 2: enable OPeration
readyToSwitchOn();
switchOn();
enableOperation();
motionStart();
// code 3
nmtActiveNode();
}
int main (void) {
canopen_init();
while {
delay_ms(1);
send_sync();
}
}
If I remove "code 2" (the servo is in Switch_on_disable status), i can read position each time sync send. But if i use "code 2", the driver has error "sync frame timeout". I dont know driver has problem or my code has problem. Does my code has problem? thank you!
I don't know what protocol stack this is or how it works, but these:
setCyclePeriod(1000);
setSyncWindow(100);
likely correspond to these OD entries :
Object 1006h: Communication cycle period (CiA 301 7.5.2.6)
Object 1007h: Synchronous window length (CiA 301 7.5.2.7)
They set the SYNC interval and time window for synchronous PDOs respectively. The latter is described by the standard as:
If the synchronous window length expires all synchronous TPDOs may be discarded and an EMCY message may be transmitted; all synchronous RPDOs may be discarded until the next SYNC message is received. Synchronous RPDO processing is resumed with the next SYNC message.
Now if you set this sync time window to 100us but have a sloppy busy-wait delay delay_ms(1), then that doesn't add up. If you write zero to Object 1007h, you disable the sync window feature. I suppose setSyncWindow(0); might do that. You can try to do that to see if that's the issue. If so, you have to drop your busy-wait in favour for proper hardware timers, one for the SYNC period and one for PDO timeout (if you must use that feature).
Problem fixed. Due to much EMI from servo, that make my controller didn't work properly. After isolating, it worked very well :)!

Infinite AMQP Consumer with Alpakka

I'm trying to implement a very simple service connected to an AMQP broker with Alpakka. I just want it to consume messages from its queue as a stream at the moment they are pushed on a given exchange/topic.
Everything seemed to work fine in my tests, but when I tried to start my service, I realized that my stream was only consuming my messages once and then exited.
Basically I'm using the code from Alpakka documentation :
def consume()={
val amqpSource = AmqpSource.committableSource(
TemporaryQueueSourceSettings(connectionProvider, exchangeName)
.withDeclaration(exchangeDeclaration)
.withRoutingKey(topic),
bufferSize = prefetchCount
)
val amqpSink = AmqpSink.replyTo(AmqpReplyToSinkSettings(connectionProvider))
amqpSource.mapAsync(4)(msg => onMessage(msg)).runWith(amqpSink)
}
I tried to schedule the consume() execution every second, but I experienced OutOfMemoryException issues.
Is there any proper way to make this code run as an infinite loop ?
If you want to have a Source restarted when it fails or is cancelled, wrap it with RestartSource.withBackoff.

store data in every minute what should use Service, AsyncTask

I want to store data in database in every minute . For the same what should I use Service, AsyncTask or anything else. I go through various link which made me more confused .
I read the developer guide and came to know about getWritableDatabase
Database upgrade may take a long time, you should not call this method from the application main thread,
Then first I think I will use AsyncTask then about this
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
After that I think I can use Service then about Service
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
Here I am not able to understand what should I use to store data in database periodically. Please help me here as struck badly.
Thanks in advance
you cant do a lot work on the UI thread, so making database operations you could choose different approaches, few of them that I prefer to use are listed below;
Create a thread pool and execute each database operation via a thread, this reduces load on UI thread, also it never initializes lot of threads.
You can use services for updating the database operations. since services running on UI thread you cant write your operations in Services, so that you have to create a separate thread inside service method. or you can use Intent service directly since it is not working on UI Thread.
here is developer documentation on thread pool in android
and this is the documentation for IntentService
UPDATE
This will send an intent to your service every minute without using any processor time in your activity in between
Intent myIntent = new Intent(context, MyServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 60); // first time
long frequency= 60 * 1000; // in ms
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, pendingIntent);
Before that check if you really need a service to be started in each minute. or if you can have one service which checks for the data changes in each minute, starting new service would consume maybe more resources than checking itself.
UPDATE 2
private ping() {
// periodic action here.
scheduleNext();
}
private scheduleNext() {
mHandler.postDelayed(new Runnable() {
public void run() { ping(); }
}, 60000);
}
int onStartCommand(Intent intent, int x, int y) {
mHandler = new android.os.Handler();
ping();
return STICKY;
}
this is a simple example like that you can do

Display progress in a long loop in Unity3d

I'm building a space game, populated by thousands of star systems. Right now, there is a function that generates these thousands of systems. It takes about 5-10 seconds to generate, and I would like to have a simple progress bar updating the user in the progress.
After some searching I've decided to use a coroutine, however there is a little problem: when I call the function to generate star systems, the code that called the function keeps on going, reporting zero stars (because they haven't been generated yet).
I have a feeling coroutines are not an answer for me. Basically, I am simply looking for a way to simulate Application.DoEvents to update the GUI.
Here is a sample of my code:
// Start generating thousands of systems
StartCoroutine(GalacticMap.GenerateRandomGalaxy());
// after the universe is generated...
Game.myGalaxy.StarSystems = GalacticMap.myGalaxy.StarSystems;
// report back the number of systems
print(String.Format("Generated {0} systems", Game.myGalaxy.StarSystems.Count));
In the GalacticMap.GenerateRandomGalaxy() I am yielding back like this yield return new WaitForSeconds(0.1f); however, the effect is not what I am looking for: execution goes right through to print statement while the generation is still on going.
So how do I do this?
EDIT 1:
I've cooked up a sample code to illustrate my issue.
The caller code:
Debug.Log ("Start generating");
StartCoroutine(GenerateMeGalaxy());
Debug.Log ("Finish generating");
The code I call:
public static IEnumerator GenerateMeGalaxy ()
{
Debug.Log ("GenerateMeGalaxy start");
int numberOfStars = 1000;
for (int i=0;i<=numberOfStars;i++)
{
// generate galaxy
// display progress bar on screen
Debug.Monitor(String.Format("{0}% completed", ((i*100)/numberOfStars)),2);
yield return new WaitForSeconds(0.001f);
}
Debug.Log ("GenerateMeGalaxy end");
}
In the code above, Debug.Log displays string on the screen, on a new line so you can read previous logged strings of whatever. This is to debug code execution. Debug.Monitor has a fixed location on the screen and will overwrite previous string. This is where I display progress percentage. What I see after running this code is:
Start generating
GenerateMeGalaxy start
Finish generating
GenerateMeGalaxy end
What I want to see is:
Start generating
GenerateMeGalaxy start
GenerateMeGalaxy end
Finish generating
... and also the progress update is happening in between:
GenerateMeGalaxy start
Finish generating
I think you are misunderstanding how Unity coroutines work. What the yield return new WaitForSeconds(0.1f) is essentially saying is "go do other stuff and come back to me after 0.1 second". So naturally Unity will go ahead and do other stuff, including the print statement.
What you want is something along the lines of the following pattern:
IEnumerator GenerateRandomGalaxy()
{
int numSystems = 5000; // however many systems you want to generate
foreach(int i = 0; i < numSystems; i++)
{
// insert code here that generates system i
// insert code here that updates the progress bar
yield return null;
}
// put logic that prints out final number of systems generated here
}
What this does is generate a system, update the status bar, and then -- with the yield return null statement -- tell Unity to take over (so that it do other stuff, including rendering the updated progress bar) and come back and continue the loop as soon as possible.
Finally, the print statement only happens after the loop is finished, as you intend.

how to manually set a task to run in a gae queue for the second time

I have a task that runs in GAE queue.
according to my logic, I want to determine if the task will run again or not.
I don't want it do be normally executed by the queue and then to put it again in the queue
because I want to have the ability to check the "X-AppEngine-TaskRetryCount"
and quit trying after several attempts.
To my understanding it seems that the only case that a task will re-executed is when an internal GAE error will happen (or If my code will take too long in a "DeadlineExceededException" cases..(And I don't want to hold the code "hostage" for that long :) )
How can I re-enter a task to the queue in a manner that GAE will set X-AppEngine-TaskRetryCount ++ ??
You can programmatically retry / restart a task using a self.error() in python.
From the docs: App engine retries a task by returning any HTTP status code outside of the range 200–299
And at the beginning of the task you can test for the number of retries using:
retries = int(self.request.headers['X-Appengine-Taskretrycount'])
if retries < 10 :
self.error(409)
return

Resources