Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Partial payments script #114

Merged
merged 22 commits into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
4a8510f
Multi activity script
nieznanysprawiciel Apr 11, 2024
d9fb4ea
Replace restarting activity with more often DebitNotes configuration
nieznanysprawiciel Apr 15, 2024
f588bfe
Merge branch 'master' of github.com:golemfactory/gamerhash-facade int…
nieznanysprawiciel Apr 15, 2024
6389fae
Filter Jobs by timestamp
nieznanysprawiciel Apr 15, 2024
e277f58
Fix filtering by timestamp
nieznanysprawiciel Apr 15, 2024
7e1dd7d
GetPayments starting at job timestamp
nieznanysprawiciel Apr 15, 2024
e7ebc4e
Refactor to make less calls to api
nieznanysprawiciel Apr 15, 2024
88afc47
Refactor UpdateJob to better handle both usages
nieznanysprawiciel Apr 15, 2024
c13ffe9
Use GetInvoicePayments instead of listing all Payments and filtering
nieznanysprawiciel Apr 15, 2024
a708a92
Handle partial payments during Job duration
nieznanysprawiciel Apr 15, 2024
3f44a3b
Fix workaround for Invoice Settled status not set by yagna
nieznanysprawiciel Apr 15, 2024
840eaee
Merge branch 'master' of github.com:golemfactory/gamerhash-facade int…
nieznanysprawiciel Apr 18, 2024
108eb28
Configurable payment interval; additions to readme
nieznanysprawiciel Apr 18, 2024
d0d8ea3
Use yagna pre-rel-v0.16.0-rc16
nieznanysprawiciel Apr 18, 2024
f955169
pay-interval default=null
nieznanysprawiciel Apr 18, 2024
6d5c9cc
Merge branch 'master' of github.com:golemfactory/gamerhash-facade int…
nieznanysprawiciel Apr 18, 2024
fe65f8b
Remove unnecessary yield
nieznanysprawiciel Apr 18, 2024
f6fefb0
CultureInvariant ToDecimal conversion
nieznanysprawiciel Apr 18, 2024
ec57e82
Fix Invoice and Payments loop async Tasks
nieznanysprawiciel Apr 19, 2024
4b4bfbd
Merge branch 'master' of github.com:golemfactory/gamerhash-facade int…
nieznanysprawiciel Apr 19, 2024
1d0077a
Update MockGUI/GolemModel.cs
nieznanysprawiciel Apr 19, 2024
5f8f549
Fix exception in ListJobs caller
nieznanysprawiciel Apr 19, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions ExampleRunner/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ public class AppArguments
[Option('f', "framework", Default = Framework.Automatic, Required = false, HelpText = "Type of AI Framework to run")]
public required Framework AiFramework { get; set; }
[Option('m', "mainnet", Default = false, Required = false, HelpText = "Enables usage of mainnet")]
public required bool Mainnet { get; set; }

public required bool Mainnet { get; set; }
[Option('p', "pay-interval", Default = false, Required = false, HelpText = "Interval between partial payments in seconds")]
pwalski marked this conversation as resolved.
Show resolved Hide resolved
public UInt32? PaymentInterval { get; set; }
}


Expand All @@ -41,6 +42,8 @@ static void Main(string[] args)
GolemRelay.SetEnv(parsed.Relay);

var App = new FullExample(workDir, "Requestor", loggerFactory, runtime: parsed.AiFramework.ToString().ToLower(), parsed.Mainnet);

App.PaymentInterval = parsed.PaymentInterval;
var logger = loggerFactory.CreateLogger("Example");

_ = Task.Run(async () =>
Expand Down
4 changes: 2 additions & 2 deletions Golem.Package/Args.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ public class BuildArgs
{
[Option('t', "target", Default = "package", Required = false, HelpText = "Directory where binaries will be generated relative to working dir")]
public required string Target { get; set; }
[Option('y', "yagna-version", Default = "pre-rel-v0.16.0-ai-rc15", Required = false, HelpText = "Yagna version github tag")]
[Option('y', "yagna-version", Default = "pre-rel-v0.16.0-ai-rc16", Required = false, HelpText = "Yagna version github tag")]
public required string GolemVersion { get; set; }
[Option('r', "runtime-version", Default = "v0.2.0", Required = false, HelpText = "Runtime version github tag")]
[Option('r', "runtime-version", Default = "pre-rel-v0.2.1-rc1", Required = false, HelpText = "Runtime version github tag")]
public required string RuntimeVersion { get; set; }
[Option('c', "dont-clean", Default = false, Required = false, HelpText = "Remove temporary directories")]
public required bool DontClean { get; set; }
Expand Down
23 changes: 15 additions & 8 deletions Golem.Tools/App/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import json

from dataclasses import dataclass
from datetime import datetime
from datetime import datetime, timedelta, timezone

from yapapi import Golem
from yapapi.payload import Payload
Expand All @@ -15,7 +15,6 @@
import argparse
import asyncio
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

Expand All @@ -26,6 +25,7 @@
from yapapi import windows_event_loop_fix
from yapapi.log import enable_default_logger
from yapapi.strategy import SCORE_TRUSTED, SCORE_REJECTED, MarketStrategy
from yapapi.strategy.base import PropValueRange, PROP_DEBIT_NOTE_INTERVAL_SEC, PROP_PAYMENT_TIMEOUT_SEC

# Utils

Expand Down Expand Up @@ -61,6 +61,7 @@ def build_parser(description: str) -> argparse.ArgumentParser:
)
parser.add_argument("--runtime", default="dummy", help="Runtime name, for example `automatic`")
parser.add_argument("--descriptor", default=None, help="Path to node descriptor file")
parser.add_argument("--pay-interval", default=180, help="Interval of making partial payments")
return parser


Expand Down Expand Up @@ -131,8 +132,12 @@ class ProviderOnceStrategy(MarketStrategy):
"""Hires provider only once.
"""

def __init__(self):
def __init__(self, pay_interval=180):
self.history = set(())
self.acceptable_prop_value_range_overrides = {
PROP_DEBIT_NOTE_INTERVAL_SEC: PropValueRange(60, None),
PROP_PAYMENT_TIMEOUT_SEC: PropValueRange(int(pay_interval), None),
}

async def score_offer(self, offer):
if offer.issuer not in self.history:
Expand Down Expand Up @@ -193,12 +198,12 @@ async def start(self):
def __init__(self, strategy: ProviderOnceStrategy):
super().__init__()
self.strategy = strategy



async def main(subnet_tag, descriptor, driver=None, network=None, runtime="dummy"):
strategy = ProviderOnceStrategy()
async def main(subnet_tag, descriptor, driver=None, network=None, runtime="dummy", args=None):
strategy = ProviderOnceStrategy(pay_interval=args.pay_interval)
async with Golem(
budget=1.0,
budget=4.0,
subnet_tag=subnet_tag,
strategy=strategy,
payment_driver=driver,
Expand All @@ -212,6 +217,7 @@ async def main(subnet_tag, descriptor, driver=None, network=None, runtime="dummy
{"strategy": strategy}
],
num_instances=1,
expiration=datetime.now(timezone.utc) + timedelta(days=10),
)

async def print_usage():
Expand Down Expand Up @@ -264,7 +270,6 @@ def instances():
} for s in cluster.instances
]


usage_printed = False
while True:
await asyncio.sleep(3)
Expand All @@ -278,6 +283,7 @@ def instances():

print(f"""instances: {[f"{r['name']}: {r['state']}" for r in i]}""")


if __name__ == "__main__":
parser = build_parser("Run AI runtime task")
now = datetime.now().strftime("%Y-%m-%d_%H.%M.%S")
Expand All @@ -291,6 +297,7 @@ def instances():
driver=args.payment_driver,
network=args.payment_network,
runtime=args.runtime,
args=args
),
log_file=args.log_file,
)
4 changes: 2 additions & 2 deletions Golem.Tools/GolemPackageBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ namespace Golem.Tools
{
public class PackageBuilder
{
public static string CURRENT_GOLEM_VERSION = "pre-rel-v0.16.0-ai-rc15";
public static string CURRENT_RUNTIME_VERSION = "v0.2.0";
public static string CURRENT_GOLEM_VERSION = "pre-rel-v0.16.0-ai-rc16";
public static string CURRENT_RUNTIME_VERSION = "pre-rel-v0.2.1-rc1";

internal static string InitTestDirectory(string name, bool cleanupData = true)
{
Expand Down
5 changes: 5 additions & 0 deletions Golem.Tools/SampleApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public class FullExample : IAsyncDisposable, INotifyPropertyChanged
private readonly bool _mainnet;

private readonly string _runtime;
public UInt32? PaymentInterval { get; set; }

private string _message;
public string Message
Expand Down Expand Up @@ -97,6 +98,10 @@ private string ExtraArgs()
{
args += $" --descriptor {GetNodeDescriptor()}";
}
if (PaymentInterval.HasValue)
{
args += $" --pay-interval {PaymentInterval.Value}";
}
return args;
}

Expand Down
21 changes: 11 additions & 10 deletions Golem/ActivityLoop.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,12 @@ public async Task Start(
await foreach (var trackingEvent in _yagnaApi.ActivityMonitorStream(token))
{
var activities = trackingEvent?.Activities ?? new List<ActivityState>();

List<Job> currentJobs = await UpdateJobs(_jobs, activities);

var job = SelectCurrentJob(currentJobs);
setCurrentJob(job);
if(job == null)
if (job == null)
{
// Sometimes finished jobs end up in Idle state
_jobs.SetAllJobsFinished();
Expand Down Expand Up @@ -91,7 +91,7 @@ public async Task Start(
if (currentJobs.Count == 0)
{
_logger.LogDebug("Cleaning current job field");

return null;
}
else if (currentJobs.Count == 1)
Expand Down Expand Up @@ -133,12 +133,13 @@ public async Task<List<Job>> UpdateJobs(IJobs jobs, List<ActivityState> activity
{
var result = await Task.WhenAll(
activityStates
.Select(async d => {
var usage = d.Usage!=null
? GolemUsage.From(d.Usage)
: null;
return await jobs.UpdateJob(d.Id, null, usage);
}
.Select(async d =>
{
var usage = d.Usage != null
? GolemUsage.From(d.Usage)
: null;
return await jobs.UpdateJobByActivity(d.Id, null, usage);
}
)
);

Expand Down
65 changes: 50 additions & 15 deletions Golem/InvoiceEventsLoop.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using Golem.Yagna;

using GolemLib.Types;

using Microsoft.Extensions.Logging;


Expand All @@ -9,8 +11,7 @@ class InvoiceEventsLoop
private readonly CancellationToken _token;
private readonly ILogger _logger;
private readonly IJobs _jobs;
private DateTime _since = DateTime.MinValue;



public InvoiceEventsLoop(YagnaApi yagnaApi, CancellationToken token, ILogger logger, IJobs jobs)
{
Expand All @@ -20,47 +21,81 @@ public InvoiceEventsLoop(YagnaApi yagnaApi, CancellationToken token, ILogger log
_jobs = jobs;
}

public async Task Start()
public Task Start()
{
_logger.LogInformation("Starting monitoring invoice events");
return Task.WhenAll(PaymentsLoop(), InvoiceLoop());
}

DateTime newReconnect = DateTime.Now;
public async Task InvoiceLoop()
{
_logger.LogInformation("Starting monitoring invoice events");

await Task.Yield();
pwalski marked this conversation as resolved.
Show resolved Hide resolved

DateTime since = DateTime.Now;

while (!_token.IsCancellationRequested)
{
try
{
var invoiceEvents = await _yagnaApi.GetInvoiceEvents(_since, _token);
pwalski marked this conversation as resolved.
Show resolved Hide resolved
var invoiceEvents = await _yagnaApi.GetInvoiceEvents(since, _token);
if (invoiceEvents != null && invoiceEvents.Count > 0)
{
_since = invoiceEvents.Max(x => x.EventDate);

foreach(var invoiceEvent in invoiceEvents.OrderBy(e => e.EventDate))
foreach (var invoiceEvent in invoiceEvents.OrderBy(e => e.EventDate))
{
await UpdatesForInvoice(invoiceEvent);
since = invoiceEvent.EventDate;
}
}
}
catch(TaskCanceledException)
catch (TaskCanceledException)
{
_logger.LogInformation("Invoice events loop cancelled");
return;
}
catch(Exception e)
catch (Exception e)
{
_logger.LogError("Error in invoice events loop: {e}", e.Message);
await Task.Delay(TimeSpan.FromSeconds(5), _token);
}
}
}
}

public async Task PaymentsLoop()
{
_logger.LogInformation("Starting monitoring payments");

DateTime since = DateTime.Now;
await Task.Yield();
pwalski marked this conversation as resolved.
Show resolved Hide resolved

while (!_token.IsCancellationRequested)
{
try
{
var payments = await _yagnaApi.GetPayments(since, _token);
foreach (var payment in payments.OrderBy(pay => pay.Timestamp))
{
await _jobs.UpdatePartialPayment(payment);
since = payment.Timestamp;
}
}
catch (TaskCanceledException)
{
_logger.LogInformation("Payments loop cancelled");
return;
}
catch (Exception e)
{
_logger.LogError("Error in payments loop: {e}", e.Message);
await Task.Delay(TimeSpan.FromSeconds(5), _token);
}
}
}

private async Task UpdatesForInvoice(InvoiceEvent invoiceEvent)
{
var invoice = await _yagnaApi.GetInvoice(invoiceEvent.InvoiceId, _token);

foreach(var activityId in invoice.ActivityIds)
await _jobs.UpdateJob(activityId, invoice, null);
_logger.LogDebug("Update Invoice info for Job: {}, status: {}", invoice.AgreementId, invoice.Status);
await _jobs.UpdateJob(invoice.AgreementId, invoice, null);
}
}
Loading
Loading