Skip to content

Commit 6d3a880

Browse files
committed
Working with updated approach using sessions.
1 parent 674f2b9 commit 6d3a880

File tree

11 files changed

+214
-105
lines changed

11 files changed

+214
-105
lines changed

DeployClient/API.cs

+31-21
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ private static HttpClient BuildClient()
1919

2020
client.BaseAddress = new Uri(new Uri(Properties.Settings.Default.TargetUri), "DesktopModules/PolyDeploy/API/");
2121
client.DefaultRequestHeaders.Add("x-api-key", Properties.Settings.Default.APIKey);
22-
client.Timeout = TimeSpan.FromMinutes(5);
22+
client.Timeout = TimeSpan.FromSeconds(25);
2323

2424
return client;
2525
}
@@ -47,9 +47,23 @@ public static string CreateSession()
4747
}
4848
}
4949

50-
public static void AddPackages(string session, List<KeyValuePair<string, Stream>> streams)
50+
public static Dictionary<string, dynamic> GetSession(string sessionGuid)
5151
{
52-
string endpoint = string.Format("CI/AddPackages?session={0}", session);
52+
string endpoint = string.Format("CI/GetSession?sessionGuid={0}", sessionGuid);
53+
54+
JavaScriptSerializer jsonSer = new JavaScriptSerializer();
55+
56+
using (HttpClient client = BuildClient())
57+
{
58+
string json = client.GetStringAsync(endpoint).Result;
59+
60+
return jsonSer.Deserialize<Dictionary<string, dynamic>>(json);
61+
}
62+
}
63+
64+
public static void AddPackages(string sessionGuid, List<KeyValuePair<string, Stream>> streams)
65+
{
66+
string endpoint = string.Format("CI/AddPackages?sessionGuid={0}", sessionGuid);
5367

5468
using (HttpClient client = BuildClient())
5569
{
@@ -64,9 +78,9 @@ public static void AddPackages(string session, List<KeyValuePair<string, Stream>
6478
}
6579
}
6680

67-
public static void AddPackageAsync(string session, Stream stream, string filename)
81+
public static void AddPackageAsync(string sessionGuid, Stream stream, string filename)
6882
{
69-
string endpoint = string.Format("CI/AddPackages?session={0}", session);
83+
string endpoint = string.Format("CI/AddPackages?sessionGuid={0}", sessionGuid);
7084

7185
using (HttpClient client = BuildClient())
7286
{
@@ -78,39 +92,35 @@ public static void AddPackageAsync(string session, Stream stream, string filenam
7892
}
7993
}
8094

81-
public static Dictionary<string, dynamic> Install(string session)
95+
public static bool Install(string sessionGuid, out Dictionary<string, dynamic> response)
8296
{
83-
string endpoint = string.Format("CI/Install?session={0}", session);
97+
string endpoint = string.Format("CI/Install?sessionGuid={0}", sessionGuid);
98+
99+
bool success = false;
84100

85101
JavaScriptSerializer jsonSer = new JavaScriptSerializer();
86102

87-
string json = "{}";
103+
response = null;
88104

89105
using (HttpClient client = BuildClient())
90106
{
91107
try
92108
{
93-
HttpResponseMessage response = client.GetAsync(endpoint).Result;
94-
95-
Console.WriteLine(response.RequestMessage.RequestUri);
109+
HttpResponseMessage httpResponse = client.GetAsync(endpoint).Result;
96110

97-
if (response.StatusCode.Equals(HttpStatusCode.OK))
111+
if (httpResponse.StatusCode.Equals(HttpStatusCode.OK))
98112
{
99-
json = response.Content.ReadAsStringAsync().Result;
113+
success = true;
114+
string json = httpResponse.Content.ReadAsStringAsync().Result;
115+
response = jsonSer.Deserialize<Dictionary<string, dynamic>>(json);
100116
}
101-
else
102-
{
103-
throw new Exception(string.Format("Received status code: {0}", response.StatusCode.ToString()));
104-
}
105-
106-
Console.WriteLine(json);
107117
}
108118
catch (Exception ex)
109119
{
110-
throw new Exception("CIInstall failure", ex);
120+
// Nothing to do.
111121
}
112122

113-
return jsonSer.Deserialize<Dictionary<string, dynamic>>(json);
123+
return success;
114124
}
115125
}
116126
}

DeployClient/Program.cs

+72-15
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Collections.Generic;
55
using System.Configuration;
66
using System.IO;
7+
using System.Web.Script.Serialization;
78

89
namespace DeployClient
910
{
@@ -110,9 +111,9 @@ static void Main(string[] args)
110111
WriteLine("Starting encryption and upload...");
111112

112113
// Get a session.
113-
string session = API.CreateSession();
114+
string sessionGuid = API.CreateSession();
114115

115-
WriteLine(string.Format("Got session: {0}", session));
116+
WriteLine(string.Format("Got session: {0}", sessionGuid));
116117

117118
DateTime startTime = DateTime.Now;
118119

@@ -121,13 +122,14 @@ static void Main(string[] args)
121122

122123
using (FileStream fs = new FileStream(zipFile, FileMode.Open))
123124
{
124-
Write(string.Format("\t{0} encrypting...", Path.GetFileName(zipFile)));
125+
WriteLine(string.Format("\t{0}", Path.GetFileName(zipFile)));
126+
Write("\t\t...encrypting...");
125127

126128
using (Stream es = Crypto.Encrypt(fs, Properties.Settings.Default.EncryptionKey))
127129
{
128130
Write("uploading...");
129131

130-
API.AddPackageAsync(session, es, Path.GetFileName(zipFile));
132+
API.AddPackageAsync(sessionGuid, es, Path.GetFileName(zipFile));
131133
}
132134

133135
WriteLine("done.");
@@ -140,24 +142,79 @@ static void Main(string[] args)
140142
WriteLine("Starting installation...");
141143

142144
DateTime installStartTime = DateTime.Now;
145+
JavaScriptSerializer jsonSer = new JavaScriptSerializer();
143146

144-
Dictionary<string, dynamic> results = API.Install(session);
147+
// Start.
148+
Dictionary<string, dynamic> results = null;
145149

146-
ArrayList installed = results.ContainsKey("Installed") ? results["Installed"] : null;
147-
ArrayList failed = results.ContainsKey("Failed") ? results["Failed"] : null;
150+
if (!API.Install(sessionGuid, out results))
151+
{
152+
DateTime abortTime = DateTime.Now.AddMinutes(10);
153+
TimeSpan interval = new TimeSpan(0, 0, 0, 2);
154+
155+
int status = -1;
156+
string previousPrint = null;
157+
158+
// While the process isn't complete and we haven't exceeded our abort time.
159+
while (status < 2 && DateTime.Now < abortTime)
160+
{
161+
// Get response.
162+
Dictionary<string, dynamic> response = API.GetSession(sessionGuid);
163+
164+
// Is there a status key?
165+
if (response.ContainsKey("Status"))
166+
{
167+
// Yes, get the status.
168+
status = response["Status"];
169+
}
170+
171+
// Is there a response key?
172+
if (response.ContainsKey("Response"))
173+
{
174+
// Yes, get the response.
175+
results = jsonSer.Deserialize<Dictionary<string, dynamic>>(response["Response"]);
176+
}
177+
178+
// As long as we have something.
179+
if (status != -1 && results != null)
180+
{
181+
// Get the installed and failed lists.
182+
ArrayList installed = results.ContainsKey("Installed") ? results["Installed"] : null;
183+
ArrayList failed = results.ContainsKey("Failed") ? results["Failed"] : null;
184+
185+
// Give some feedback on it, only if it's changed.
186+
string print = string.Format("\t{0} module archives processed, {0}/{1} succeeded.", installed.Count + failed.Count, installed.Count);
187+
188+
if (print != previousPrint)
189+
{
190+
WriteLine(print);
191+
previousPrint = print;
192+
}
193+
}
148194

149-
// Any failures?
150-
if (failed.Count > 0)
195+
// Is finished?
196+
if (status == 2)
197+
{
198+
break;
199+
}
200+
201+
// Sleep.
202+
System.Threading.Thread.Sleep(interval);
203+
}
204+
}
205+
else
151206
{
152-
WriteLine(string.Format("{0} module archives failed to install.", failed.Count));
153-
ReadLine();
154-
Environment.Exit((int)ExitCode.InstallFailure);
207+
// Get the installed and failed lists.
208+
ArrayList installed = results.ContainsKey("Installed") ? results["Installed"] : null;
209+
ArrayList failed = results.ContainsKey("Failed") ? results["Failed"] : null;
210+
211+
// Give some feedback on it.
212+
WriteLine(string.Format("\t{0} module archives processed, {0}/{1} succeeded.", installed.Count + failed.Count, installed.Count));
213+
155214
}
156215

157-
// Output result
158-
WriteLine(string.Format("{0} module archives installed successfully.", installed.Count));
159-
ReadLine();
160216
WriteLine(string.Format("Finished installation in {0} ms.", (DateTime.Now - installStartTime).TotalMilliseconds));
217+
ReadLine();
161218
}
162219
catch (Exception ex)
163220
{

PolyDeploy/Components/CIDeploy.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ internal class CIDeploy : Deployment
1515
{
1616
private APIUser APIUser { get; set; }
1717

18-
public CIDeploy(string sessionPath, string ipAddress, string apiKey) : base(sessionPath, ipAddress)
18+
public CIDeploy(Session session, string ipAddress, string apiKey) : base(session, ipAddress)
1919
{
2020
// Retrieve our API user.
2121
APIUser = APIUserController.GetByAPIKey(apiKey);

PolyDeploy/Components/Deployment.cs

+33-41
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,40 @@
1-
using System;
1+
using Cantarus.Modules.PolyDeploy.DataAccess.DataControllers;
2+
using Cantarus.Modules.PolyDeploy.DataAccess.Models;
3+
using System;
24
using System.Collections.Generic;
35
using System.IO;
46
using System.IO.Compression;
7+
using System.Web.Script.Serialization;
58

69
namespace Cantarus.Modules.PolyDeploy.Components
710
{
811
internal class Deployment
912
{
10-
//protected string IntakePath
11-
//{
12-
// get
13-
// {
14-
// return Path.Combine(WorkingPath, "intake");
15-
// }
16-
//}
17-
18-
//protected string ModulesPath
19-
//{
20-
// get
21-
// {
22-
// return Path.Combine(WorkingPath, "modules");
23-
// }
24-
//}
25-
2613
protected string TempPath
2714
{
2815
get
2916
{
30-
return Path.Combine(SessionPath, "temp");
17+
return Path.Combine(SessionController.PathForSession(Session.Guid), "temp");
3118
}
3219
}
3320

3421
protected string IPAddress { get; set; }
35-
protected string SessionPath { get; set; }
22+
protected Session Session { get; set; }
3623
protected List<string> PackageZips { get; set; }
3724

38-
public Deployment(string sessionPath, string ipAddress)
25+
public Deployment(Session session, string ipAddress)
3926
{
4027
// Store ip address for logging later.
4128
IPAddress = ipAddress;
4229

43-
// store the session path.
44-
SessionPath = sessionPath;
45-
46-
//// Create working directory if it doesn't exist.
47-
//CreateDirectoryIfNotExist(WorkingPath);
48-
49-
//// Create the intake directory if it doesn't exist.
50-
//CreateDirectoryIfNotExist(IntakePath);
51-
52-
//// Create the modules directory if it doesn't exist.
53-
//CreateDirectoryIfNotExist(ModulesPath);
30+
// Store the session.
31+
Session = session;
5432

5533
// Create the temporary directory if it doesn't exist.
5634
CreateDirectoryIfNotExist(TempPath);
5735
}
5836

59-
public Dictionary<string, List<InstallJob>> Deploy()
37+
public void Deploy()
6038
{
6139
// Identify package zips.
6240
List<string> packageZips = IdentifyPackages();
@@ -85,29 +63,43 @@ public Dictionary<string, List<InstallJob>> Deploy()
8563
List<InstallJob> successJobs = new List<InstallJob>();
8664
List<InstallJob> failedJobs = new List<InstallJob>();
8765

66+
Dictionary<string, List<InstallJob>> results = new Dictionary<string, List<InstallJob>>();
67+
68+
results.Add("Installed", successJobs);
69+
results.Add("Failed", failedJobs);
70+
71+
JavaScriptSerializer jsonSer = new JavaScriptSerializer();
72+
SessionDataController dc = new SessionDataController();
73+
74+
// Set as started.
75+
Session.Status = SessionStatus.InProgess;
76+
dc.Update(Session);
77+
8878
foreach (KeyValuePair<int, InstallJob> keyPair in orderedInstall)
8979
{
9080
InstallJob job = keyPair.Value;
9181

9282
if (job.Install())
9383
{
9484
successJobs.Add(job);
95-
} else
85+
}
86+
else
9687
{
9788
failedJobs.Add(job);
9889
}
90+
91+
// After each install job, update response.
92+
Session.Response = jsonSer.Serialize(results);
93+
dc.Update(Session);
9994
}
10095

96+
// Done.
97+
Session.Status = SessionStatus.Complete;
98+
dc.Update(Session);
99+
101100
// Log failures.
102101
LogAnyFailures(successJobs);
103102
LogAnyFailures(failedJobs);
104-
105-
Dictionary<string, List<InstallJob>> results = new Dictionary<string, List<InstallJob>>();
106-
107-
results.Add("Installed", successJobs);
108-
results.Add("Failed", failedJobs);
109-
110-
return results;
111103
}
112104

113105
protected virtual void LogAnyFailures(List<InstallJob> jobs)
@@ -201,7 +193,7 @@ private InstallJob FindInstallJobWithPackage(string name, List<InstallJob> insta
201193

202194
protected List<string> IdentifyPackages()
203195
{
204-
return IdentifyPackagesInDirectory(SessionPath);
196+
return IdentifyPackagesInDirectory(SessionController.PathForSession(Session.Guid));
205197
}
206198

207199
protected List<string> IdentifyPackagesInDirectory(string directoryPath)

PolyDeploy/Components/SessionController.cs

+7
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ public static Session CreateSession()
2121
return session;
2222
}
2323

24+
public static Session GetSession(string sessionGuid)
25+
{
26+
SessionDataController dc = new SessionDataController();
27+
28+
return dc.FindByGuid(sessionGuid); ;
29+
}
30+
2431
public static bool SessionExists(string sessionGuid)
2532
{
2633
SessionDataController dc = new SessionDataController();

0 commit comments

Comments
 (0)