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

fix lastEventId tracking #546

Merged
merged 4 commits into from
Jul 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ public AnsibleReturnValue runCommand(AnsibleCommandConfig commandConfig, int tim
}

AnsibleReturnValue ret = new AnsibleReturnValue(AnsibleReturnCode.ERROR);
int lastEventId = 0;

String playUuid = null;
String msg = "";
Expand All @@ -158,18 +157,18 @@ public AnsibleReturnValue runCommand(AnsibleCommandConfig commandConfig, int tim
ret.setLogFile(runnerClient.getLogger().getLogFile());
ret.setPlayUuid(playUuid);
ret.setStdout(String.format("%1$s/%2$s/artifacts/%2$s/stdout", AnsibleConstants.ANSIBLE_RUNNER_PATH, playUuid));
ret.setLastEventId(0);
List<String> command = commandConfig.build();

// Run the playbook:
runnerClient.runPlaybook(command, timeout, playUuid);

if (async) {
ret.setPlayUuid(playUuid);
ret.setAnsibleReturnCode(AnsibleReturnCode.OK);
return ret;
}

ret = runnerClient.artifactHandler(commandConfig.getUuid(), lastEventId, timeout, fn);
ret = runnerClient.artifactHandler(commandConfig.getUuid(), ret.getLastEventId(), timeout, fn);
} catch (InventoryException ex) {
String message = ex.getMessage();
log.error("Error executing playbook: {}", message);
Expand All @@ -183,8 +182,7 @@ public AnsibleReturnValue runCommand(AnsibleCommandConfig commandConfig, int tim
} finally {
// Make sure all events are proccessed even in case of failure:
if (playUuid != null && runnerClient != null && !async) {
lastEventId = runnerClient.getLastEventId();
runnerClient.processEvents(playUuid, lastEventId, fn, msg, ret.getLogFile());
runnerClient.processEvents(playUuid, ret.getLastEventId(), fn, msg, ret.getLogFile());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ public class AnsibleRunnerClient {
private static Logger log = LoggerFactory.getLogger(AnsibleRunnerClient.class);
private ObjectMapper mapper;
private AnsibleRunnerLogger runnerLogger;
private String lastEvent = "";
private static final int POLL_INTERVAL = 3000;
private AnsibleReturnValue returnValue;

Expand All @@ -53,23 +52,18 @@ public AnsibleRunnerClient() {
this.returnValue = new AnsibleReturnValue(AnsibleReturnCode.ERROR);
}

public Boolean playHasEnded(UUID uuid) {
String jobEvents = getJobEventsDir(uuid.toString());
File lastEventFile = new File(jobEvents + lastEvent);
String res = "";
try {
res = Files.readString(lastEventFile.toPath());
} catch (IOException e) {
return false;
}
return res.contains("playbook_on_stats");
public Boolean playHasEnded(String uuid, int lastEventId) {
// get current status, but new events might have appeared since last processing
PlaybookStatus currentPlaybookStatus = getPlaybookStatus(uuid);
String msg = currentPlaybookStatus.getMsg();
return !msg.equalsIgnoreCase("running") && !(lastEventId < getTotalEvents(uuid));
}

public AnsibleReturnValue artifactHandler(UUID uuid, int lastEventID, int timeout, BiConsumer<String, String> fn)
throws Exception {
int executionTime = 0;
setReturnValue(uuid);
while (!playHasEnded(uuid)) {
while (!playHasEnded(uuid.toString(), lastEventID)) {
lastEventID = processEvents(uuid.toString(), lastEventID, fn, "", Paths.get(""));
if (lastEventID == -1) {
return returnValue;
Expand All @@ -93,7 +87,7 @@ public void setReturnValue(UUID uuid) {
returnValue.setStdout(Paths.get(this.getJobEventsDir(uuid.toString()), "../stdout").toString());
}

public String getNextEvent(String playUuid, int lastEventId) {
public String getEventFileName(String playUuid, int eventId) {
String jobEvents = getJobEventsDir(playUuid);
if (!Files.exists(Paths.get(jobEvents))) {
return null;
Expand All @@ -103,15 +97,11 @@ public String getNextEvent(String playUuid, int lastEventId) {
.map(File::getName)
.filter(item -> !item.contains("partial"))
.filter(item -> !item.endsWith(".tmp"))
.filter(item -> item.startsWith((lastEventId + 1) + "-"))
.filter(item -> item.startsWith(eventId + "-"))
.findFirst()
.orElse(null);
}

public int getLastEventId() {
return Integer.valueOf(lastEvent.split("-")[0]);
}

public String getJobEventsDir(String playUuid) {
return String.format("%1$s/%2$s/artifacts/%2$s/job_events/", AnsibleConstants.ANSIBLE_RUNNER_PATH, playUuid);
}
Expand All @@ -123,7 +113,8 @@ public int processEvents(String playUuid,
Path logFile) {
String jobEvents = getJobEventsDir(playUuid);
while(true){
String event = getNextEvent(playUuid, lastEventId);
// get next event
String event = getEventFileName(playUuid, lastEventId + 1);
if (event == null) {
break;
}
Expand Down Expand Up @@ -187,11 +178,10 @@ public int processEvents(String playUuid,
}
}
}
lastEvent = event;
returnValue.setLastEventId(getLastEventId());
lastEventId++;
lastEventId = Integer.valueOf(event.split("-")[0]);
returnValue.setLastEventId(lastEventId);
}
return lastEvent.isEmpty() ? lastEventId : getLastEventId();
return lastEventId;
}

private Boolean jsonIsValid(String content) {
Expand Down Expand Up @@ -270,12 +260,17 @@ public PlaybookStatus getPlaybookStatus(String playUuid) {
String privateRunDir = String.format("%1$s/%2$s/", AnsibleConstants.ANSIBLE_RUNNER_PATH, playUuid);
String playData = String.format("%1$s/%2$s/artifacts/%2$s/", AnsibleConstants.ANSIBLE_RUNNER_PATH, playUuid);
try {
// regardless if we run sync or async playbook we launch ansible-runner the same way,
// "status" and "rc" are created only once the playbook finishes
if (Files.exists(Paths.get(String.format("%1$s/status", playData)))) {
status = Files.readString(Paths.get(String.format("%1$s/status", playData)));
rc = Files.readString(Paths.get(String.format("%1$s/rc", playData)));
// we call ansible-runner synchronously and "damon.log" is crated by the main process before
// going to background. So we can rely on its existence if ansible managed to start and still runs
} else if (Files.exists(Paths.get(String.format("%1$s/daemon.log", privateRunDir)))) {
// artifacts are not yet present, try to fetch them in the next polling round
return new PlaybookStatus("", "running");
// ansible-runner didn't manage to start the background process so we know it failed right away
} else {
log.warn(String.format("The playbook failed with unknow error at: %1$s", playData));
return new PlaybookStatus("", "failed");
Expand Down