Skip to content
Snippets Groups Projects
Commit 55dfaf04 authored by Jesper Fyhr Knudsen's avatar Jesper Fyhr Knudsen
Browse files

Refactored the code style and Added a license text to all production code.

parent b3660ede
Branches
No related tags found
No related merge requests found
Showing
with 1110 additions and 1052 deletions
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2014 Chaos ApS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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.
\ No newline at end of file
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.agent;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import com.chaos.octopus.commons.core.*;
import com.chaos.octopus.commons.exception.DisconnectError;
import com.chaos.octopus.commons.util.Commands;
import com.chaos.octopus.commons.util.NetworkingUtil;
import com.chaos.octopus.commons.util.StreamUtilities;
/**
* User: Jesper Fyhr Knudsen
* Date: 16-07-13
* Time: 14:20
*/
public class Agent implements Runnable, AutoCloseable, TaskUpdatedListener
{
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class Agent implements Runnable, AutoCloseable, TaskUpdatedListener {
private AtomicInteger _currentQueueSize;
private boolean _isRunning;
private Thread _thread;
......@@ -28,74 +29,58 @@ public class Agent implements Runnable, AutoCloseable, TaskUpdatedListener
private Orchestrator _orchestrator;
private ServerSocket _Server;
public Agent(String orchestratorHostname, int orchestratorPort, int listenPort)
{
public Agent(String orchestratorHostname, int orchestratorPort, int listenPort) {
this(new OrchestratorProxy(orchestratorHostname, orchestratorPort, listenPort), 4);
}
public Agent(String orchestratorHostname, int orchestratorPort, int listenPort, int parrallelism)
{
public Agent(String orchestratorHostname, int orchestratorPort, int listenPort, int parrallelism) {
this(new OrchestratorProxy(orchestratorHostname, orchestratorPort, listenPort), parrallelism);
}
public Agent(Orchestrator orchestrator, int parrallelism)
{
public Agent(Orchestrator orchestrator, int parallelism) {
_orchestrator = orchestrator;
_currentQueueSize = new AtomicInteger(0);
_isRunning = false;
_thread = new Thread(this);
_thread.setName("Agent");
_PluginDefinitions = new HashMap<>();
_executionHandler = new ExecutionHandler(this, parrallelism);
_executionHandler = new ExecutionHandler(this, parallelism);
}
public static Agent create(OctopusConfiguration config)
{
public static Agent create(OctopusConfiguration config) {
return new Agent(config.getOrchestratorIp(), config.getOrchestratorPort(), config.getListeningPort(), config.getNumberOfParallelTasks());
}
public void open() throws IOException
{
try
{
public void open() throws IOException {
try {
_orchestrator.open();
_Server = new ServerSocket(_orchestrator.get_localListenPort());
_isRunning = true;
_thread.start();
}
catch (DisconnectError e)
{
} catch (DisconnectError e) {
System.out.println(Thread.currentThread().getId() + " AGENT DISCONNECTED");
try
{
try {
close();
}
catch (Exception ex)
{
} catch (Exception ex) {
e.printStackTrace();
}
}
}
public void run()
{
while(_isRunning)
{
try
{
public void run() {
while (_isRunning) {
try {
// todo refactor so the implementation doesn't depend on the socket
try(Socket socket = _Server.accept())
{
try (Socket socket = _Server.accept()) {
String message = StreamUtilities.ReadString(socket.getInputStream());
Message msg = StreamUtilities.ReadJson(message, Message.class);
OutputStream out = socket.getOutputStream();
switch (msg.getAction())
{
switch (msg.getAction()) {
case Commands.LIST_SUPPORTED_PLUGINS:
AgentConfigurationMessage response = createAgentConfigurationMessage();
......@@ -112,68 +97,54 @@ public class Agent implements Runnable, AutoCloseable, TaskUpdatedListener
break;
}
}
}
catch (Exception e)
{
} catch (Exception e) {
if (!_Server.isClosed()) e.printStackTrace();
}
}
}
private AgentConfigurationMessage createAgentConfigurationMessage()
{
private AgentConfigurationMessage createAgentConfigurationMessage() {
AgentConfigurationMessage message = new AgentConfigurationMessage();
message.setNumberOfSimulataniousTasks(_executionHandler.getParralelism());
message.setNumberOfSimulataniousTasks(_executionHandler.getParallelism());
for (PluginDefinition definition : get_SupportedPlugins())
{
message.getSupportedPlugins().add(definition.getId());
}
return message;
}
public void close() throws Exception
{
public void close() throws Exception {
_isRunning = false;
if (_Server != null) _Server.close();
if (_executionHandler != null) _executionHandler.close();
}
public byte[] serializeSupportedPlugins()
{
public byte[] serializeSupportedPlugins() {
StringBuilder sb = new StringBuilder();
for (PluginDefinition definition : get_SupportedPlugins())
{
sb.append(String.format("%s;", definition.getId()));
}
return sb.toString().getBytes();
}
public void addPlugin(PluginDefinition pluginFactory)
{
public void addPlugin(PluginDefinition pluginFactory) {
_PluginDefinitions.put(pluginFactory.getId(), pluginFactory);
}
// TODO CAN BE REMOVED????
public List<PluginDefinition> get_SupportedPlugins()
{
public List<PluginDefinition> get_SupportedPlugins() {
List<PluginDefinition> list = new ArrayList<>();
for (PluginDefinition definition : _PluginDefinitions.values())
{
list.add(definition);
}
return list;
}
public Plugin enqueue(Task task)
{
public Plugin enqueue(Task task) {
Plugin plugin = _PluginDefinitions.get(task.pluginId).create(task);
_executionHandler.enqueue(plugin);
......@@ -182,20 +153,17 @@ public class Agent implements Runnable, AutoCloseable, TaskUpdatedListener
return plugin;
}
public void onTaskComplete(Task task)
{
public void onTaskComplete(Task task) {
_currentQueueSize.decrementAndGet();
_orchestrator.taskCompleted(task);
}
@Override
public void onTaskUpdate(Task task)
{
public void onTaskUpdate(Task task) {
_orchestrator.taskUpdate(task);
}
public int getQueueSize()
{
public int getQueueSize() {
return _currentQueueSize.get();
}
}
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.agent;
import com.chaos.octopus.commons.core.Plugin;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.chaos.octopus.commons.core.Plugin;
public class ExecutionHandler implements AutoCloseable, TaskCompleteListener
{
public class ExecutionHandler implements AutoCloseable, TaskCompleteListener {
private Agent _agent;
private ExecutorService _pool;
private int parrallelism;
private int parallelism;
public ExecutionHandler(Agent agent, int parrallelism)
{
this.parrallelism = parrallelism;
public ExecutionHandler(Agent agent, int parallelism) {
this.parallelism = parallelism;
_pool = Executors.newFixedThreadPool(parrallelism);
_pool = Executors.newFixedThreadPool(parallelism);
_agent = agent;
}
@Override
public void onTaskComplete(ExecutionSlot completedTask)
{
public void onTaskComplete(ExecutionSlot completedTask) {
_agent.onTaskComplete(completedTask.getPlugin().getTask());
}
public void enqueue(Plugin plugin)
{
public void enqueue(Plugin plugin) {
ExecutionSlot slot = new ExecutionSlot(plugin);
slot.addTaskCompleteListener(this);
slot.addTaskUpdateListener(_agent);
......@@ -37,14 +36,12 @@ public class ExecutionHandler implements AutoCloseable, TaskCompleteListener
}
@Override
public void close() throws Exception
{
public void close() throws Exception {
_pool.shutdown();
_pool.awaitTermination(5000, TimeUnit.MILLISECONDS);
}
public int getParralelism()
{
return parrallelism;
public int getParallelism() {
return parallelism;
}
}
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.agent;
import java.util.ArrayList;
import java.util.List;
import com.chaos.octopus.commons.core.Plugin;
import com.chaos.octopus.commons.core.Task;
import com.chaos.octopus.commons.core.TaskState;
public class ExecutionSlot implements Runnable
{
import java.util.ArrayList;
import java.util.List;
public class ExecutionSlot implements Runnable {
private Plugin _plugin;
private List<TaskCompleteListener> _taskCompleteListeners;
private List<TaskUpdatedListener> _taskUpdateListeners;
public ExecutionSlot(Plugin plugin)
{
public ExecutionSlot(Plugin plugin) {
_taskCompleteListeners = new ArrayList<>();
_taskUpdateListeners = new ArrayList<>();
_plugin = plugin;
}
// todo: rollback and commit it not implemetned correctly
@Override
public void run()
{
try
{
public void run() {
try {
_plugin.getTask().set_State(TaskState.Executing);
onTaskUpdated(_plugin.getTask());
_plugin.execute();
......@@ -35,49 +36,36 @@ public class ExecutionSlot implements Runnable
_plugin.commit();
_plugin.getTask().set_State(TaskState.Committed);
onTaskUpdated(_plugin.getTask());
}
catch(Exception e)
{
} catch (Exception e) {
_plugin.getTask().set_State(TaskState.Rollingback);
//onTaskUpdated(_plugin.getTask());
_plugin.rollback();
_plugin.getTask().set_State(TaskState.Rolledback);
onTaskUpdated(_plugin.getTask());
}
finally
{
} finally {
onTaskComplete();
}
}
public void addTaskCompleteListener(TaskCompleteListener callback)
{
public void addTaskCompleteListener(TaskCompleteListener callback) {
_taskCompleteListeners.add(callback);
}
public void addTaskUpdateListener(TaskUpdatedListener listener)
{
public void addTaskUpdateListener(TaskUpdatedListener listener) {
_taskUpdateListeners.add(listener);
}
public Plugin getPlugin()
{
public Plugin getPlugin() {
return _plugin;
}
private void onTaskComplete()
{
private void onTaskComplete() {
for (TaskCompleteListener callback : _taskCompleteListeners)
{
callback.onTaskComplete(this);
}
}
private void onTaskUpdated(Task task)
{
private void onTaskUpdated(Task task) {
for (TaskUpdatedListener callback : _taskUpdateListeners)
{
callback.onTaskUpdate(task);
}
}
}
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.agent;
import java.net.*;
import java.net.ConnectException;
import com.chaos.octopus.commons.core.*;
import com.chaos.octopus.commons.util.Commands;
import com.chaos.octopus.commons.util.NetworkingUtil;
import com.google.gson.Gson;
public class OrchestratorProxy implements Orchestrator
{
import java.net.ConnectException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
public class OrchestratorProxy implements Orchestrator {
private int _localListenPort;
private String _localHostAddress;
private NetworkingUtil _network;
public OrchestratorProxy(String hostname, int port, int listenPort)
{
public OrchestratorProxy(String hostname, int port, int listenPort) {
_localHostAddress = getHostAddress();
_localListenPort = listenPort;
_network = new NetworkingUtil(hostname, port);
}
private String getHostAddress()
{
try
{
private String getHostAddress() {
try {
String hostAddress = Inet4Address.getLocalHost().getHostAddress();
System.out.println("Local IP: " + hostAddress);
return hostAddress;
}
catch (UnknownHostException e)
{
} catch (UnknownHostException e) {
throw new com.chaos.octopus.commons.exception.ConnectException("Could not determine local host address", e);
}
}
public void open() throws ConnectException
{
public void open() throws ConnectException {
ConnectMessage msg = new ConnectMessage(_localHostAddress, _localListenPort);
_network.send(msg.toJson());
}
public void taskCompleted(Task task)
{
public void taskCompleted(Task task) {
TaskMessage msg = new TaskMessage(Commands.TASK_DONE, task);
_network.send(msg.toJson());
}
@Override
public void taskUpdate(Task task)
{
public void taskUpdate(Task task) {
TaskMessage msg = new TaskMessage(Commands.TASK_UPDATE, task);
_network.send(msg.toJson());
}
@Override
public int get_localListenPort()
{
public int get_localListenPort() {
return _localListenPort;
}
@Override
public void enqueue(Job job)
{
public void enqueue(Job job) {
}
@Override
public void close() throws Exception
{
public void close() throws Exception {
}
}
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.agent.plugin;
import com.chaos.octopus.commons.core.Plugin;
import com.chaos.octopus.commons.core.PluginDefinition;
import com.chaos.octopus.commons.core.Task;
import com.chaos.sdk.AuthenticatedChaosClient;
import com.chaos.sdk.Chaos;
import com.chaos.sdk.model.McmObject;
import com.chaos.sdk.AuthenticatedChaosClient;
import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* User: Jesper Fyhr Knudsen
* Date: 23-10-13
* Time: 17:06
*/
public class ChaosPlugin implements Plugin, PluginDefinition
{
public class ChaosPlugin implements Plugin, PluginDefinition {
private Task _Task;
@Override
public String getId()
{
public String getId() {
return "com.chaos.octopus.plugins.ChaosPlugin, 1.0.0";
}
public ChaosPlugin(){ }
public ChaosPlugin() {
}
public ChaosPlugin(Task task)
{
public ChaosPlugin(Task task) {
setTask(task);
}
@Override
public Plugin create(Task data)
{
public Plugin create(Task data) {
return new ChaosPlugin(data);
}
@Override
public Task getTask()
{
public Task getTask() {
return _Task;
}
private void setTask(Task task)
{
private void setTask(Task task) {
_Task = task;
}
@Override
public void execute() throws Exception
{
public void execute() throws Exception {
// TODO once more actions are implemented, replace with Strategy pattern
if("object.createFromJson".equals(getAction()))
{
if ("object.createFromJson".equals(getAction())) {
String metadata = getInoutXmlContent();
Chaos api = new Chaos(getChaosLocation());
......@@ -68,17 +63,14 @@ public class ChaosPlugin implements Plugin, PluginDefinition
}
}
private String getInoutXmlContent() throws IllegalAccessException, IOException
{
private String getInoutXmlContent() throws IllegalAccessException, IOException {
File f = new File(getInputXml());
StringBuffer result = new StringBuffer();
if (!f.exists()) throw new IllegalAccessException("xml path is incorrect");
try(FileReader fr = new FileReader(getInputXml()))
{
try(BufferedReader in = new BufferedReader(fr))
{
try (FileReader fr = new FileReader(getInputXml())) {
try (BufferedReader in = new BufferedReader(fr)) {
String inputLine;
while ((inputLine = in.readLine()) != null)
......@@ -90,47 +82,38 @@ public class ChaosPlugin implements Plugin, PluginDefinition
}
@Override
public void rollback()
{
public void rollback() {
}
@Override
public void commit()
{
public void commit() {
}
public String getAction()
{
public String getAction() {
return getTask().properties.get("action");
}
public String getInputXml()
{
public String getInputXml() {
return getTask().properties.get("input-xmlfilepath");
}
public String getChaosLocation()
{
public String getChaosLocation() {
return getTask().properties.get("chaos-location");
}
public String getApiKey()
{
public String getApiKey() {
return getTask().properties.get("chaos-apikey");
}
public int getObjectTypeId()
{
public int getObjectTypeId() {
return Integer.parseInt(getTask().properties.get("chaos-objecttypeid"));
}
public int getFolderId()
{
public int getFolderId() {
return Integer.parseInt(getTask().properties.get("chaos-folderid"));
}
public String getMetadataSchemaId()
{
public String getMetadataSchemaId() {
return getTask().properties.get("chaos-metadataschemaid");
}
}
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.agent.plugin;
import com.chaos.octopus.commons.core.Plugin;
......@@ -6,85 +10,66 @@ import com.chaos.octopus.commons.core.Task;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* User: Jesper Fyhr Knudsen
* Date: 16-10-13
* Time: 15:00
*/
public class CommandLinePlugin implements Plugin, PluginDefinition
{
public class CommandLinePlugin implements Plugin, PluginDefinition {
private Task _Task;
public CommandLinePlugin()
{
public CommandLinePlugin() {
}
public CommandLinePlugin(Task task)
{
public CommandLinePlugin(Task task) {
this();
_Task = task;
}
private String getCommandLine()
{
private String getCommandLine() {
return _Task.properties.get("commandline");
}
@Override
public String getId()
{
public String getId() {
return "com.chaos.octopus.CommandLinePlugin, 1.0.0";
}
@Override
public Plugin create(Task task)
{
public Plugin create(Task task) {
return new CommandLinePlugin(task);
}
@Override
public Task getTask()
{
public Task getTask() {
return _Task;
}
@Override
public void execute() throws Exception
{
public void execute() throws Exception {
Process process = Runtime.getRuntime().exec(getCommandLine());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())))
{
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine ()) != null)
{
while ((line = reader.readLine()) != null) {
Pattern r = Pattern.compile("<PROGRESS>(.*?)</PROGRESS>", Pattern.CASE_INSENSITIVE);
Matcher m = r.matcher(line);
if(m.find())
{
if (m.find()) {
getTask().progress = Double.parseDouble(m.group(1));
}
r = Pattern.compile("<STATUS>(.*?)</STATUS>", Pattern.CASE_INSENSITIVE);
m = r.matcher(line);
if(m.find())
{
if (m.find()) {
setOrAppend("status", m.group(1));
}
r = Pattern.compile("<WARNING>(.*?)</WARNING>", Pattern.CASE_INSENSITIVE);
m = r.matcher(line);
if(m.find())
{
if (m.find()) {
setOrAppend("warning", m.group(1));
System.err.println("warning: " + m.group(1));
}
......@@ -92,8 +77,7 @@ public class CommandLinePlugin implements Plugin, PluginDefinition
r = Pattern.compile("<EXCEPTION>(.*?)</EXCEPTION>", Pattern.CASE_INSENSITIVE);
m = r.matcher(line);
if(m.find())
{
if (m.find()) {
setOrAppend("exception", m.group(1));
System.err.println("exception: " + m.group(1));
}
......@@ -103,8 +87,7 @@ public class CommandLinePlugin implements Plugin, PluginDefinition
process.waitFor();
}
private void setOrAppend(String key, String value)
{
private void setOrAppend(String key, String value) {
if (getTask().properties.containsKey(key))
value = getTask().properties.get(key) + " [###] " + value;
......@@ -112,14 +95,12 @@ public class CommandLinePlugin implements Plugin, PluginDefinition
}
@Override
public void rollback()
{
public void rollback() {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void commit()
{
public void commit() {
//To change body of implemented methods use File | Settings | File Templates.
}
}
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.commons.core;
import com.google.gson.Gson;
import java.util.ArrayList;
/**
* Copyright (c) 2014 Chaos ApS. All rights reserved. See LICENSE.TXT for details.
*/
public class AgentConfigurationMessage extends Message
{
public class AgentConfigurationMessage extends Message {
private int numberOfSimulataniousTasks = 0;
private ArrayList<String> supportedPlugins = new ArrayList<>();
public AgentConfigurationMessage()
{
public AgentConfigurationMessage() {
}
public static AgentConfigurationMessage create(String config)
{
public static AgentConfigurationMessage create(String config) {
return new Gson().fromJson(config, AgentConfigurationMessage.class);
}
......@@ -38,8 +36,7 @@ public class AgentConfigurationMessage extends Message
this.supportedPlugins = supportedPlugins;
}
public String toJson()
{
public String toJson() {
return new Gson().toJson(this);
}
}
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.commons.core;
import com.chaos.octopus.commons.util.StreamUtilities;
public class ConnectMessage extends Message
{
public class ConnectMessage extends Message {
private String hostname;
private int port;
public ConnectMessage(){}
public ConnectMessage(String hostname, int port)
{
public ConnectMessage() {
}
public ConnectMessage(String hostname, int port) {
setAction("connect");
this.hostname = hostname;
this.port = port;
}
public static ConnectMessage createFromJson(String json)
{
public static ConnectMessage createFromJson(String json) {
return StreamUtilities.ReadJson(json, ConnectMessage.class);
}
public String get_Hostname()
{
public String get_Hostname() {
return hostname;
}
public int get_Port()
{
public int get_Port() {
return port;
}
}
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.commons.core;
import java.util.*;
import java.util.ArrayList;
public class Job
{
public class Job {
public String id;
public ArrayList<Step> steps = new ArrayList<>();
public String status;
public Job()
{
public Job() {
id = "";
status = "new";
}
public boolean validate()
{
for (Step step : steps)
{
public boolean validate() {
for (Step step : steps) {
if (step == null || !step.validate()) return false;
}
return true;
}
public Iterable<Task> getTasks(TaskState... criteria)
{
try
{
for(Step step : steps)
{
public Iterable<Task> getTasks(TaskState... criteria) {
try {
for (Step step : steps) {
if (step.isFailed()) break;
if (!step.isCompleted())
return step.getTasks(criteria);
}
}
catch (Exception e)
{
} catch (Exception e) {
e.printStackTrace();
}
return new ArrayList<>();
}
public boolean isComplete()
{
for(Step step : steps)
{
public boolean isComplete() {
for (Step step : steps) {
if (step.isFailed()) return true;
if (!step.isCompleted()) return false;
}
......@@ -55,51 +48,37 @@ public class Job
return true;
}
public Boolean containsTask(String taskId)
{
public Boolean containsTask(String taskId) {
for (Step step : steps)
{
for (Task task : step.tasks)
{
if (task.taskId.equals(taskId))
return true;
}
}
return false;
}
public void replaceTask(Task replace)
{
public void replaceTask(Task replace) {
for (Step step : steps)
{
if(step.containsTask(replace.taskId))
{
if (step.containsTask(replace.taskId)) {
step.replaceTask(replace.taskId, replace);
break;
}
}
}
public void resume()
{
for(Task task : getTasks(new TaskState[]{TaskState.Executing, TaskState.Queued}))
{
public void resume() {
for (Task task : getTasks(new TaskState[]{TaskState.Executing, TaskState.Queued})) {
task.set_State(TaskState.New);
}
}
public void print()
{
public void print() {
System.out.println("Job enqued: " + id);
for(Step step : steps)
{
for (Step step : steps) {
System.out.println("\tStep: " + step.tasks.size());
for(Task task : step.tasks)
{
for (Task task : step.tasks) {
System.out.println("\t\t" + task.get_State() + " " + task.taskId);
}
}
......
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.commons.core;
import com.chaos.octopus.commons.util.StreamUtilities;
import com.google.gson.Gson;
public class Message
{
public class Message {
private String action;
public Message() { }
public Message() {
}
public static Message createFromJson(String json)
{
public static Message createFromJson(String json) {
return StreamUtilities.ReadJson(json, Message.class);
}
public static Message createWithAction(String action)
{
public static Message createWithAction(String action) {
Message msg = new Message();
msg.setAction(action);
return msg;
}
public String getAction()
{
public String getAction() {
return action;
}
public void setAction(String action)
{
public void setAction(String action) {
this.action = action;
}
public String toJson()
{
public String toJson() {
Gson gson = new Gson();
return gson.toJson(this);
......
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.commons.core;
import org.apache.commons.configuration.Configuration;
......@@ -6,11 +10,7 @@ import org.apache.commons.configuration.PropertiesConfiguration;
import java.nio.file.Paths;
/**
* Created by JesperFyhr on 05-02-14.
*/
public class OctopusConfiguration
{
public class OctopusConfiguration {
private int port;
private String orchestratorIp = null;
......@@ -19,8 +19,7 @@ public class OctopusConfiguration
private String chaosApiUrl = null;
private String chaosApiKey = null;
public OctopusConfiguration() throws ConfigurationException
{
public OctopusConfiguration() throws ConfigurationException {
String wd = System.getProperty("user.dir");
String path = Paths.get(wd, "octopus.properties").toString();
Configuration config = new PropertiesConfiguration(path);
......@@ -42,23 +41,19 @@ public class OctopusConfiguration
chaosApiKey = config.getString("orchestrator.chaosApiKey");
}
public int getListeningPort()
{
public int getListeningPort() {
return port;
}
public String getOrchestratorIp()
{
public String getOrchestratorIp() {
return orchestratorIp;
}
public int getOrchestratorPort()
{
public int getOrchestratorPort() {
return orchestratorPort;
}
public Boolean getIsAgent()
{
public Boolean getIsAgent() {
return getOrchestratorIp() != null && getOrchestratorPort() != 0;
}
......
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.commons.core;
import java.net.ConnectException;
public interface Orchestrator extends AutoCloseable
{
public interface Orchestrator extends AutoCloseable {
void open() throws ConnectException;
void taskCompleted(Task task);
void taskUpdate(Task task);
int get_localListenPort();
void enqueue(Job job);
}
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.commons.core;
public interface Plugin
{
String getId();
Task getTask();
void execute() throws Exception;
void rollback();
void commit();
......
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.commons.core;
public interface PluginDefinition
......
......@@ -2,77 +2,62 @@ package com.chaos.octopus.commons.core;
import java.util.ArrayList;
public class Step
{
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
public class Step {
public ArrayList<Task> tasks = new ArrayList<>();
public boolean isCompleted()
{
public boolean isCompleted() {
for (Task task : tasks)
{
if (task.get_State() != TaskState.Committed && task.get_State() != TaskState.Rolledback && task.get_State() != TaskState.Executed)
return false;
}
return true;
}
public boolean isFailed()
{
public boolean isFailed() {
for (Task task : tasks)
{
if (task.get_State() == TaskState.Rolledback || task.get_State() == TaskState.Rollingback)
return true;
}
return false;
}
public boolean isFinished()
{
public boolean isFinished() {
for (Task task : tasks)
{
if (task.get_State() != TaskState.Committed)
return false;
}
return true;
}
public boolean validate()
{
public boolean validate() {
return !tasks.isEmpty();
}
public Iterable<Task> getTasks(TaskState... criteria)
{
public Iterable<Task> getTasks(TaskState... criteria) {
ArrayList<Task> list = new ArrayList<>();
for (Task task : tasks)
{
//if(task.isQueueable() || task.get_State() == TaskState.Executing || task.get_State() == TaskState.Queued)
if (task.get_State().isIn(criteria))
list.add(task);
}
return list;
}
public boolean containsTask(String taskId)
{
public boolean containsTask(String taskId) {
for (Task task : tasks)
{
if (task.taskId.equals(taskId))
return true;
}
return false;
}
public void replaceTask(String taskId, Task replace)
{
for(int i = 0; i < tasks.size(); i++)
{
public void replaceTask(String taskId, Task replace) {
for (int i = 0; i < tasks.size(); i++) {
Task task = tasks.get(i);
if (task.taskId.equals(taskId) && task.get_State() != TaskState.Committed)
......
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.chaos.octopus.commons.core;
import com.chaos.octopus.commons.util.StreamUtilities;
/**
* User: Jesper Fyhr Knudsen
* Date: 09.10.13
* Time: 17:25
*/
public class TaskMessage extends Message
{
public class TaskMessage extends Message {
private Task task;
public TaskMessage(){}
public TaskMessage(String action, Task task)
{
public TaskMessage() {
}
public TaskMessage(String action, Task task) {
setAction(action);
setTask(task);
}
public static TaskMessage createFromJson(String json)
{
public static TaskMessage createFromJson(String json) {
return StreamUtilities.ReadJson(json, TaskMessage.class);
}
......
package com.chaos.octopus.commons.core;
public enum TaskState
{
/**
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
public enum TaskState {
New,
Queued,
Executing,
......@@ -11,27 +14,23 @@ public enum TaskState
Rolledback,
Committed;
public static TaskState[] isQueueable()
{
public static TaskState[] isQueueable() {
return new TaskState[]{
TaskState.New
};
}
public static TaskState[] isCompleted()
{
public static TaskState[] isCompleted() {
return new TaskState[]{
TaskState.Committed,
TaskState.Rolledback
};
}
public boolean isIn(TaskState... criteria)
{
public boolean isIn(TaskState... criteria) {
if (criteria.length == 0) return true;
for (TaskState state : criteria)
{
for (TaskState state : criteria) {
if (state == this) return true;
}
......
package com.chaos.octopus.commons.exception;
/**
* Copyright (c) 2014 Chaos ApS. All rights reserved. See LICENSE.TXT for details.
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
public class ConnectException extends Error
{
package com.chaos.octopus.commons.exception;
public class ConnectException extends Error {
public ConnectException() {
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment