forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHypervResourceController.cs
More file actions
2493 lines (2265 loc) · 106 KB
/
Copy pathHypervResourceController.cs
File metadata and controls
2493 lines (2265 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using log4net;
using Microsoft.CSharp.RuntimeBinder;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Web.Http;
using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2;
namespace HypervResource
{
public struct HypervResourceControllerConfig
{
private string privateIpAddress;
private static ILog logger = LogManager.GetLogger(typeof(HypervResourceControllerConfig));
public string PrivateIpAddress
{
get
{
return privateIpAddress;
}
set
{
ValidateIpAddress(value);
privateIpAddress = value;
System.Net.NetworkInformation.NetworkInterface nic = HypervResourceController.GetNicInfoFromIpAddress(privateIpAddress, out PrivateNetmask);
PrivateMacAddress = nic.GetPhysicalAddress().ToString();
}
}
private static void ValidateIpAddress(string value)
{
// Convert to IP address
IPAddress ipAddress;
if (!IPAddress.TryParse(value, out ipAddress))
{
String errMsg = "Invalid PrivateIpAddress: " + value;
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
}
public string GatewayIpAddress;
public string PrivateMacAddress;
public string PrivateNetmask;
public string StorageNetmask;
public string StorageMacAddress;
public string StorageIpAddress;
public long RootDeviceReservedSpaceBytes;
public string RootDeviceName;
public ulong ParentPartitionMinMemoryMb;
public string LocalSecondaryStoragePath;
public string systemVmIso;
private string getPrimaryKey(string id)
{
return "primary_storage_" + id;
}
public string getPrimaryStorage(string id)
{
NameValueCollection settings = ConfigurationManager.AppSettings;
return settings.Get(getPrimaryKey(id));
}
public void setPrimaryStorage(string id, string path)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;
string key = getPrimaryKey(id);
if (settings[key] != null)
{
settings.Remove(key);
}
settings.Add(key, path);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
public List<string> getAllPrimaryStorages()
{
List<string> poolPaths = new List<string>();
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;
foreach (string key in settings.AllKeys)
{
if (key.Contains("primary_storage_"))
{
poolPaths.Add(settings[key].Value);
}
}
return poolPaths;
}
}
/// <summary>
/// Supports one HTTP GET and multiple HTTP POST URIs
/// </summary>
/// <remarks>
/// <para>
/// POST takes dynamic to allow it to receive JSON without concern for what is the underlying object.
/// E.g. http://stackoverflow.com/questions/14071715/passing-dynamic-json-object-to-web-api-newtonsoft-example
/// and http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object
/// Use ActionName attribute to allow multiple POST URLs, one for each supported command
/// E.g. http://stackoverflow.com/a/12703423/939250
/// Strictly speaking, this goes against the purpose of an ApiController, which is to provide one GET/POST/PUT/DELETE, etc.
/// However, it reduces the amount of code by removing the need for a switch according to the incoming command type.
/// http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx
/// </para>
/// <para>
/// Exceptions handled on command by command basis rather than globally to allow details of the command
/// to be reflected in the response. Default error handling is in the catch for Exception, but
/// other exception types may be caught where the feedback would be different.
/// NB: global alternatives discussed at
/// http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx
/// </para>
/// </remarks>
public class HypervResourceController : ApiController
{
public static void Configure(HypervResourceControllerConfig config)
{
HypervResourceController.config = config;
wmiCallsV2 = new WmiCallsV2();
}
public static HypervResourceControllerConfig config = new HypervResourceControllerConfig();
private static ILog logger = LogManager.GetLogger(typeof(HypervResourceController));
private string systemVmIso = "";
Dictionary<String, String> contextMap = new Dictionary<String, String>();
public static void Initialize()
{
}
public static IWmiCallsV2 wmiCallsV2 { get; set;}
// GET api/HypervResource
public string Get()
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
return "HypervResource controller running, use POST to send JSON encoded RPCs"; ;
}
}
/// <summary>
/// NOP - placeholder for future setup, e.g. delete existing VMs or Network ports
/// POST api/HypervResource/SetupCommand
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
/// TODO: produce test
[HttpPost]
[ActionName(CloudStackTypes.SetupCommand)]
public JContainer SetupCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.SetupCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
try
{
result = true;
}
catch (Exception sysEx)
{
details = CloudStackTypes.SetupCommand + " failed due to " + sysEx.Message;
logger.Error(details, sysEx);
}
object ansContent = new
{
result = result,
details = "success - NOP",
_reconnect = false,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.SetupAnswer);
}
}
// POST api/HypervResource/AttachCommand
[HttpPost]
[ActionName(CloudStackTypes.AttachCommand)]
public JContainer AttachCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.AttachCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
try
{
string vmName = (string)cmd.vmName;
DiskTO disk = DiskTO.ParseJson(cmd.disk);
if (disk.type.Equals("ISO"))
{
TemplateObjectTO dataStore = disk.templateObjectTO;
NFSTO share = dataStore.nfsDataStoreTO;
string diskPath = Utils.NormalizePath(Path.Combine(share.UncPath, dataStore.path));
wmiCallsV2.AttachIso(vmName, diskPath);
result = true;
}
else if (disk.type.Equals("DATADISK"))
{
VolumeObjectTO volume = disk.volumeObjectTO;
string diskPath = Utils.NormalizePath(volume.FullFileName);
wmiCallsV2.AttachDisk(vmName, diskPath, disk.diskSequence);
result = true;
}
else
{
details = "Invalid disk type to be attached to vm " + vmName;
}
}
catch (Exception sysEx)
{
details = CloudStackTypes.AttachCommand + " failed due to " + sysEx.Message;
logger.Error(details, sysEx);
}
object ansContent = new
{
result = result,
details = details,
disk = cmd.disk,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.AttachAnswer);
}
}
// POST api/HypervResource/DetachCommand
[HttpPost]
[ActionName(CloudStackTypes.DettachCommand)]
public JContainer DetachCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.DettachCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
try
{
string vmName = (string)cmd.vmName;
DiskTO disk = DiskTO.ParseJson(cmd.disk);
if (disk.type.Equals("ISO"))
{
TemplateObjectTO dataStore = disk.templateObjectTO;
NFSTO share = dataStore.nfsDataStoreTO;
string diskPath = Utils.NormalizePath(Path.Combine(share.UncPath, dataStore.path));
wmiCallsV2.DetachDisk(vmName, diskPath);
result = true;
}
else if (disk.type.Equals("DATADISK"))
{
VolumeObjectTO volume = disk.volumeObjectTO;
string diskPath = Utils.NormalizePath(volume.FullFileName);
wmiCallsV2.DetachDisk(vmName, diskPath);
result = true;
}
else
{
details = "Invalid disk type to be dettached from vm " + vmName;
}
}
catch (Exception sysEx)
{
details = CloudStackTypes.DettachCommand + " failed due to " + sysEx.Message;
logger.Error(details, sysEx);
}
object ansContent = new
{
result = result,
details = details,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.DettachAnswer);
}
}
// POST api/HypervResource/RebootCommand
[HttpPost]
[ActionName(CloudStackTypes.RebootCommand)]
public JContainer RebootCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.RebootCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
try
{
string vmName = (string)cmd.vmName;
var sys = wmiCallsV2.GetComputerSystem(vmName);
if (sys == null)
{
details = CloudStackTypes.RebootCommand + " requested unknown VM " + vmName;
logger.Error(details);
}
else
{
wmiCallsV2.SetState(sys, RequiredState.Reset);
result = true;
}
}
catch (Exception sysEx)
{
details = CloudStackTypes.RebootCommand + " failed due to " + sysEx.Message;
logger.Error(details, sysEx);
}
object ansContent = new
{
result = result,
details = details,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.RebootAnswer);
}
}
// POST api/HypervResource/DestroyCommand
[HttpPost]
[ActionName(CloudStackTypes.DestroyCommand)]
public JContainer DestroyCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.DestroyCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
try
{
// Assert
String errMsg = "No 'volume' details in " + CloudStackTypes.DestroyCommand + " " + Utils.CleanString(cmd.ToString());
if (cmd.volume == null)
{
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
// Assert
errMsg = "No valide path in DestroyCommand in " + CloudStackTypes.DestroyCommand + " " + (String)cmd.ToString();
if (cmd.volume.path == null)
{
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
String path = (string)cmd.volume.path;
if (!File.Exists(path))
{
logger.Info(CloudStackTypes.DestroyCommand + ", but volume at pass already deleted " + path);
}
string vmName = (string)cmd.vmName;
if (!string.IsNullOrEmpty(vmName) && File.Exists(path))
{
// Make sure that this resource is removed from the VM
wmiCallsV2.DetachDisk(vmName, path);
}
File.Delete(path);
result = true;
}
catch (Exception sysEx)
{
details = CloudStackTypes.DestroyCommand + " failed due to " + sysEx.Message;
logger.Error(details, sysEx);
}
object ansContent = new
{
result = result,
details = details,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer);
}
}
// POST api/HypervResource/DeleteCommand
[HttpPost]
[ActionName(CloudStackTypes.DeleteCommand)]
public JContainer DeleteCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.DestroyCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
try
{
// Assert
String errMsg = "No 'volume' details in " + CloudStackTypes.DestroyCommand + " " + Utils.CleanString(cmd.ToString());
VolumeObjectTO destVolumeObjectTO = VolumeObjectTO.ParseJson(cmd.data);
if (destVolumeObjectTO.name == null)
{
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
String path = destVolumeObjectTO.FullFileName;
if (!File.Exists(path))
{
logger.Info(CloudStackTypes.DestroyCommand + ", but volume at pass already deleted " + path);
}
string vmName = (string)cmd.vmName;
if (!string.IsNullOrEmpty(vmName) && File.Exists(path))
{
// Make sure that this resource is removed from the VM
wmiCallsV2.DetachDisk(vmName, path);
}
File.Delete(path);
result = true;
}
catch (Exception sysEx)
{
details = CloudStackTypes.DestroyCommand + " failed due to " + sysEx.Message;
logger.Error(details, sysEx);
}
object ansContent = new
{
result = result,
details = details,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer);
}
}
private static JArray ReturnCloudStackTypedJArray(object ansContent, string ansType)
{
JObject ansObj = Utils.CreateCloudStackObject(ansType, ansContent);
JArray answer = new JArray(ansObj);
logger.Info(Utils.CleanString(ansObj.ToString()));
return answer;
}
// POST api/HypervResource/CreateCommand
[HttpPost]
[ActionName(CloudStackTypes.CreateCommand)]
public JContainer CreateCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.CreateCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
VolumeInfo volume = new VolumeInfo();
try
{
string diskType = cmd.diskCharacteristics.type;
ulong disksize = cmd.diskCharacteristics.size;
string templateUri = cmd.templateUrl;
// assert: valid storagepool?
string poolTypeStr = cmd.pool.type;
string poolLocalPath = cmd.pool.path;
string poolUuid = cmd.pool.uuid;
string newVolPath = null;
long volId = cmd.volId;
string newVolName = null;
if (ValidStoragePool(poolTypeStr, poolLocalPath, poolUuid, ref details))
{
// No template URI? Its a blank disk.
if (string.IsNullOrEmpty(templateUri))
{
// assert
VolumeType volType;
if (!Enum.TryParse<VolumeType>(diskType, out volType) && volType != VolumeType.DATADISK)
{
details = "Cannot create volumes of type " + (string.IsNullOrEmpty(diskType) ? "NULL" : diskType);
}
else
{
newVolName = cmd.diskCharacteristics.name;
newVolPath = Path.Combine(poolLocalPath, newVolName, diskType.ToLower());
// TODO: make volume format and block size configurable
wmiCallsV2.CreateDynamicVirtualHardDisk(disksize, newVolPath);
if (File.Exists(newVolPath))
{
result = true;
}
else
{
details = "Failed to create DATADISK with name " + newVolName;
}
}
}
else
{
// TODO: Does this always work, or do I need to download template at times?
if (templateUri.Contains("/") || templateUri.Contains("\\"))
{
details = "Problem with templateURL " + templateUri +
" the URL should be volume UUID in primary storage created by previous PrimaryStorageDownloadCommand";
logger.Error(details);
}
else
{
logger.Debug("Template's name in primary store should be " + templateUri);
// HypervPhysicalDisk BaseVol = primaryPool.getPhysicalDisk(tmplturl);
FileInfo srcFileInfo = new FileInfo(templateUri);
newVolName = Guid.NewGuid() + srcFileInfo.Extension;
newVolPath = Path.Combine(poolLocalPath, newVolName);
logger.Debug("New volume will be at " + newVolPath);
string oldVolPath = Path.Combine(poolLocalPath, templateUri);
File.Copy(oldVolPath, newVolPath);
if (File.Exists(newVolPath))
{
result = true;
}
else
{
details = "Failed to create DATADISK with name " + newVolName;
}
}
volume = new VolumeInfo(
volId, diskType,
poolTypeStr, poolUuid, newVolName,
newVolPath, newVolPath, (long)disksize, null);
}
}
}
catch (Exception sysEx)
{
// TODO: consider this as model for error processing in all commands
details = CloudStackTypes.CreateCommand + " failed due to " + sysEx.Message;
logger.Error(details, sysEx);
}
object ansContent = new
{
result = result,
details = details,
volume = volume,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CreateAnswer);
}
}
// POST api/HypervResource/PrimaryStorageDownloadCommand
[HttpPost]
[ActionName(CloudStackTypes.PrimaryStorageDownloadCommand)]
public JContainer PrimaryStorageDownloadCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.PrimaryStorageDownloadCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
long size = 0;
string newCopyFileName = null;
string poolLocalPath = cmd.localPath;
if (!Directory.Exists(poolLocalPath))
{
details = "None existent local path " + poolLocalPath;
}
else
{
// Compose name for downloaded file.
string sourceUrl = cmd.url;
if (sourceUrl.ToLower().EndsWith(".vhd"))
{
newCopyFileName = Guid.NewGuid() + ".vhd";
}
if (sourceUrl.ToLower().EndsWith(".vhdx"))
{
newCopyFileName = Guid.NewGuid() + ".vhdx";
}
// assert
if (newCopyFileName == null)
{
details = CloudStackTypes.PrimaryStorageDownloadCommand + " Invalid file extension for hypervisor type in source URL " + sourceUrl;
logger.Error(details);
}
else
{
try
{
FileInfo newFile;
if (CopyURI(sourceUrl, newCopyFileName, poolLocalPath, out newFile, ref details))
{
size = newFile.Length;
result = true;
}
}
catch (System.Exception ex)
{
details = CloudStackTypes.PrimaryStorageDownloadCommand + " Cannot download source URL " + sourceUrl + " due to " + ex.Message;
logger.Error(details, ex);
}
}
}
object ansContent = new
{
result = result,
details = details,
templateSize = size,
installPath = newCopyFileName,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.PrimaryStorageDownloadAnswer);
}
}
private static bool ValidStoragePool(string poolTypeStr, string poolLocalPath, string poolUuid, ref string details)
{
StoragePoolType poolType;
if (!Enum.TryParse<StoragePoolType>(poolTypeStr, out poolType) || poolType != StoragePoolType.Filesystem)
{
details = "Primary storage pool " + poolUuid + " type " + poolType + " local path " + poolLocalPath + " has invalid StoragePoolType";
logger.Error(details);
return false;
}
else if (!Directory.Exists(poolLocalPath))
{
details = "Primary storage pool " + poolUuid + " type " + poolType + " local path " + poolLocalPath + " has invalid local path";
logger.Error(details);
return false;
}
return true;
}
/// <summary>
/// Exceptions to watch out for:
/// Exceptions related to URI creation
/// System.SystemException
/// +-System.ArgumentNullException
/// +-System.FormatException
/// +-System.UriFormatException
///
/// Exceptions related to NFS URIs
/// System.SystemException
/// +-System.NotSupportedException
/// +-System.ArgumentException
/// +-System.ArgumentNullException
/// +-System.Security.SecurityException;
/// +-System.UnauthorizedAccessException
/// +-System.IO.IOException
/// +-System.IO.PathTooLongException
///
/// Exceptions related to HTTP URIs
/// System.SystemException
/// +-System.InvalidOperationException
/// +-System.Net.WebException
/// +-System.NotSupportedException
/// +-System.ArgumentNullException
/// </summary>
/// <param name="sourceUri"></param>
/// <param name="newCopyFileName"></param>
/// <param name="poolLocalPath"></param>
/// <returns></returns>
private bool CopyURI(string sourceUri, string newCopyFileName, string poolLocalPath, out FileInfo newFile, ref string details)
{
Uri source = new Uri(sourceUri);
String destFilePath = Path.Combine(poolLocalPath, newCopyFileName);
string[] pathSegments = source.Segments;
String templateUUIDandExtension = pathSegments[pathSegments.Length - 1];
newFile = new FileInfo(destFilePath);
// NFS URI assumed to already be mounted locally. Mount location given by settings.
if (source.Scheme.ToLower().Equals("nfs"))
{
String srcDiskPath = Path.Combine(HypervResourceController.config.LocalSecondaryStoragePath, templateUUIDandExtension);
String taskMsg = "Copy NFS url in " + sourceUri + " at " + srcDiskPath + " to pool " + poolLocalPath;
logger.Debug(taskMsg);
File.Copy(srcDiskPath, destFilePath);
}
else if (source.Scheme.ToLower().Equals("http") || source.Scheme.ToLower().Equals("https"))
{
System.Net.WebClient webclient = new WebClient();
webclient.DownloadFile(source, destFilePath);
}
else
{
details = "Unsupported URI scheme " + source.Scheme.ToLower() + " in source URI " + sourceUri;
logger.Error(details);
return false;
}
if (!File.Exists(destFilePath))
{
details = "Filed to copy " + sourceUri + " to primary pool destination " + destFilePath;
logger.Error(details);
return false;
}
return true;
}
// POST api/HypervResource/CheckHealthCommand
[HttpPost]
[ActionName(CloudStackTypes.CheckHealthCommand)]
public JContainer CheckHealthCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.CheckHealthCommand + Utils.CleanString(cmd.ToString()));
object ansContent = new
{
result = true,
details = "resource is alive",
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckHealthAnswer);
}
}
// POST api/HypervResource/CheckOnHostCommand
[HttpPost]
[ActionName(CloudStackTypes.CheckOnHostCommand)]
public JContainer CheckOnHostCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.CheckOnHostCommand + Utils.CleanString(cmd.ToString()));
string details = "host is not alive";
bool result = true;
try
{
foreach (string poolPath in config.getAllPrimaryStorages())
{
if (IsHostAlive(poolPath, (string)cmd.host.privateNetwork.ip))
{
result = false;
details = "host is alive";
break;
}
}
}
catch (Exception e)
{
logger.Error("Error Occurred in " + CloudStackTypes.CheckOnHostCommand + " : " + e.Message);
}
object ansContent = new
{
result = result,
details = details,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckOnHostAnswer);
}
}
private bool IsHostAlive(string poolPath, string privateIp)
{
bool hostAlive = false;
try
{
string hbFile = Path.Combine(poolPath, "hb-" + privateIp);
FileInfo file = new FileInfo(hbFile);
using (StreamReader sr = file.OpenText())
{
string epoch = sr.ReadLine();
string[] dateTime = epoch.Split('@');
string[] date = dateTime[0].Split('-');
string[] time = dateTime[1].Split(':');
DateTime epochTime = new DateTime(Convert.ToInt32(date[0]), Convert.ToInt32(date[1]), Convert.ToInt32(date[2]), Convert.ToInt32(time[0]),
Convert.ToInt32(time[1]), Convert.ToInt32(time[2]), DateTimeKind.Utc);
DateTime currentTime = DateTime.UtcNow;
DateTime ThreeMinuteLaterEpoch = epochTime.AddMinutes(3);
if (currentTime.CompareTo(ThreeMinuteLaterEpoch) < 0)
{
hostAlive = true;
}
sr.Close();
}
}
catch (Exception e)
{
logger.Info("Exception occurred in verifying host " + e.Message);
}
return hostAlive;
}
// POST api/HypervResource/CheckSshCommand
// TODO: create test
[HttpPost]
[ActionName(CloudStackTypes.CheckSshCommand)]
public JContainer CheckSshCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.CheckSshCommand + Utils.CleanString(cmd.ToString()));
object ansContent = new
{
result = true,
details = "NOP, TODO: implement properly",
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckSshAnswer);
}
}
// POST api/HypervResource/CheckVirtualMachineCommand
[HttpPost]
[ActionName(CloudStackTypes.CheckVirtualMachineCommand)]
public JContainer CheckVirtualMachineCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.CheckVirtualMachineCommand + Utils.CleanString(cmd.ToString()));
string details = null;
bool result = false;
string vmName = cmd.vmName;
string powerState = null;
// TODO: Look up the VM, convert Hyper-V state to CloudStack version.
var sys = wmiCallsV2.GetComputerSystem(vmName);
if (sys == null)
{
details = CloudStackTypes.CheckVirtualMachineCommand + " requested unknown VM " + vmName;
logger.Error(details);
}
else
{
powerState = EnabledState.ToCloudStackPowerState(sys.EnabledState);
result = true;
}
object ansContent = new
{
result = result,
details = details,
powerstate = powerState,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckVirtualMachineAnswer);
}
}
// POST api/HypervResource/DeleteStoragePoolCommand
[HttpPost]
[ActionName(CloudStackTypes.DeleteStoragePoolCommand)]
public JContainer DeleteStoragePoolCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.DeleteStoragePoolCommand + Utils.CleanString(cmd.ToString()));
object ansContent = new
{
result = true,
details = "Current implementation does not delete local path corresponding to storage pool!",
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer);
}
}
/// <summary>
/// NOP - legacy command -
/// POST api/HypervResource/CreateStoragePoolCommand
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
[HttpPost]
[ActionName(CloudStackTypes.CreateStoragePoolCommand)]
public JContainer CreateStoragePoolCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.CreateStoragePoolCommand + Utils.CleanString(cmd.ToString()));
object ansContent = new
{
result = true,
details = "success - NOP",
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer);
}
}
// POST api/HypervResource/ModifyStoragePoolCommand
[HttpPost]
[ActionName(CloudStackTypes.ModifyStoragePoolCommand)]
public JContainer ModifyStoragePoolCommand([FromBody]dynamic cmd)
{
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
{
logger.Info(CloudStackTypes.ModifyStoragePoolCommand + Utils.CleanString(cmd.ToString()));
string details = null;
string localPath;
StoragePoolType poolType;
long capacityBytes = 0;
long availableBytes = 0;
string hostPath = null;
bool result = false;
var tInfo = new Dictionary<string, string>();
object ansContent;
try
{
result = ValidateStoragePoolCommand(cmd, out localPath, out poolType, ref details);
if (!result)
{
ansContent = new
{
result = result,
details = details,
contextMap = contextMap
};
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.Answer);
}
if (poolType == StoragePoolType.Filesystem)
{
GetCapacityForLocalPath(localPath, out capacityBytes, out availableBytes);
hostPath = localPath;
}
else if (poolType == StoragePoolType.NetworkFilesystem ||
poolType == StoragePoolType.SMB)
{
NFSTO share = new NFSTO();
String uriStr = "cifs://" + (string)cmd.pool.host + (string)cmd.pool.path;
share.uri = new Uri(uriStr);
hostPath = Utils.NormalizePath(share.UncPath);
// Check access to share.
Utils.GetShareDetails(hostPath, out capacityBytes, out availableBytes);
config.setPrimaryStorage((string)cmd.pool.uuid, hostPath);
}
else
{
result = false;
}
}
catch
{
result = false;
details = String.Format("Failed to add storage pool {0}, please verify your pool details", (string)cmd.pool.uuid);