/
NfsSecondaryStorageResource.java
3670 lines (3284 loc) · 162 KB
/
NfsSecondaryStorageResource.java
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.
package org.apache.cloudstack.storage.resource;
import static com.cloud.network.NetworkModel.METATDATA_DIR;
import static com.cloud.network.NetworkModel.PASSWORD_DIR;
import static com.cloud.network.NetworkModel.PASSWORD_FILE;
import static com.cloud.network.NetworkModel.PUBLIC_KEYS_FILE;
import static com.cloud.network.NetworkModel.USERDATA_DIR;
import static com.cloud.network.NetworkModel.USERDATA_FILE;
import static com.cloud.utils.storage.S3.S3Utils.putFile;
import static java.util.Arrays.asList;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.framework.security.keystore.KeystoreManager;
import org.apache.cloudstack.storage.NfsMountManagerImpl.PathParser;
import org.apache.cloudstack.storage.command.CopyCmdAnswer;
import org.apache.cloudstack.storage.command.CopyCommand;
import org.apache.cloudstack.storage.command.DeleteCommand;
import org.apache.cloudstack.storage.command.DownloadCommand;
import org.apache.cloudstack.storage.command.DownloadProgressCommand;
import org.apache.cloudstack.storage.command.MoveVolumeCommand;
import org.apache.cloudstack.storage.command.QuerySnapshotZoneCopyAnswer;
import org.apache.cloudstack.storage.command.QuerySnapshotZoneCopyCommand;
import org.apache.cloudstack.storage.command.TemplateOrVolumePostUploadCommand;
import org.apache.cloudstack.storage.command.UploadStatusAnswer;
import org.apache.cloudstack.storage.command.UploadStatusAnswer.UploadStatus;
import org.apache.cloudstack.storage.command.UploadStatusCommand;
import org.apache.cloudstack.storage.command.browser.ListDataStoreObjectsCommand;
import org.apache.cloudstack.storage.configdrive.ConfigDrive;
import org.apache.cloudstack.storage.configdrive.ConfigDriveBuilder;
import org.apache.cloudstack.storage.template.DownloadManager;
import org.apache.cloudstack.storage.template.DownloadManagerImpl;
import org.apache.cloudstack.storage.template.UploadEntity;
import org.apache.cloudstack.storage.template.UploadManager;
import org.apache.cloudstack.storage.template.UploadManagerImpl;
import org.apache.cloudstack.storage.to.SnapshotObjectTO;
import org.apache.cloudstack.storage.to.TemplateObjectTO;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.cloudstack.utils.imagestore.ImageStoreUtil;
import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils;
import org.apache.cloudstack.utils.security.DigestHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckHealthAnswer;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.ComputeChecksumCommand;
import com.cloud.agent.api.DeleteSnapshotsDirCommand;
import com.cloud.agent.api.GetStorageStatsAnswer;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.agent.api.HandleConfigDriveIsoAnswer;
import com.cloud.agent.api.HandleConfigDriveIsoCommand;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingStorageCommand;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.SecStorageFirewallCfgCommand;
import com.cloud.agent.api.SecStorageFirewallCfgCommand.PortConfig;
import com.cloud.agent.api.SecStorageSetupAnswer;
import com.cloud.agent.api.SecStorageSetupCommand;
import com.cloud.agent.api.SecStorageVMSetupCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupSecondaryStorageCommand;
import com.cloud.agent.api.storage.CreateDatadiskTemplateAnswer;
import com.cloud.agent.api.storage.CreateDatadiskTemplateCommand;
import com.cloud.agent.api.storage.CreateEntityDownloadURLCommand;
import com.cloud.agent.api.storage.DeleteEntityDownloadURLCommand;
import com.cloud.agent.api.storage.DownloadAnswer;
import com.cloud.agent.api.storage.GetDatadisksAnswer;
import com.cloud.agent.api.storage.GetDatadisksCommand;
import com.cloud.agent.api.storage.ListTemplateAnswer;
import com.cloud.agent.api.storage.ListTemplateCommand;
import com.cloud.agent.api.storage.ListVolumeAnswer;
import com.cloud.agent.api.storage.ListVolumeCommand;
import com.cloud.agent.api.storage.OVFHelper;
import com.cloud.agent.api.storage.UploadCommand;
import com.cloud.agent.api.to.DataObjectType;
import com.cloud.agent.api.to.DataStoreTO;
import com.cloud.agent.api.to.DataTO;
import com.cloud.agent.api.to.DatadiskTO;
import com.cloud.agent.api.to.NfsTO;
import com.cloud.agent.api.to.S3TO;
import com.cloud.agent.api.to.SwiftTO;
import com.cloud.configuration.Resource;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.host.Host;
import com.cloud.host.Host.Type;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.network.element.NetworkElement;
import com.cloud.resource.ServerResourceBase;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StorageLayer;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
import com.cloud.storage.template.OVAProcessor;
import com.cloud.storage.template.Processor;
import com.cloud.storage.template.Processor.FormatInfo;
import com.cloud.storage.template.QCOW2Processor;
import com.cloud.storage.template.RawImageProcessor;
import com.cloud.storage.template.TARProcessor;
import com.cloud.storage.template.TemplateConstants;
import com.cloud.storage.template.TemplateLocation;
import com.cloud.storage.template.TemplateProp;
import com.cloud.storage.template.VhdProcessor;
import com.cloud.storage.template.VmdkProcessor;
import com.cloud.utils.EncryptionUtil;
import com.cloud.utils.LogUtils;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.SwiftUtil;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script;
import com.cloud.utils.storage.S3.S3Utils;
import com.cloud.vm.SecondaryStorageVm;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class NfsSecondaryStorageResource extends ServerResourceBase implements SecondaryStorageResource {
protected Logger logger = LogManager.getLogger(NfsSecondaryStorageResource.class);
private static final String TEMPLATE_ROOT_DIR = "template/tmpl";
private static final String VOLUME_ROOT_DIR = "volumes";
private static final String POST_UPLOAD_KEY_LOCATION = "/etc/cloudstack/agent/ms-psk";
private static final String ORIGINAL_FILE_EXTENSION = ".orig";
private static final String USE_HTTPS_TO_UPLOAD = "useHttpsToUpload";
private static final Map<String, String> updatableConfigData = Maps.newHashMap();
static {
updatableConfigData.put(PUBLIC_KEYS_FILE, METATDATA_DIR);
updatableConfigData.put(USERDATA_FILE, USERDATA_DIR);
updatableConfigData.put(PASSWORD_FILE, PASSWORD_DIR);
}
int _timeout;
public int getTimeout() {
return _timeout;
}
public void setTimeout(int timeout) {
_timeout = timeout;
}
String _instance;
String _dc;
String _pod;
String _guid;
String _role;
Map<String, Object> _params;
protected StorageLayer _storage;
protected boolean _inSystemVM = false;
boolean _sslCopy = false;
protected DownloadManager _dlMgr;
protected UploadManager _upldMgr;
private String _configSslScr;
private String _configAuthScr;
private String _configIpFirewallScr;
private String _publicIp;
private String _hostname;
private String _localgw;
private String _eth1mask;
private String _eth1ip;
private String _storageIp;
private String _storageNetmask;
private String _storageGateway;
private String _nfsVersion;
private final List<String> nfsIps = new ArrayList<String>();
protected String _parent = "/mnt/SecStorage";
final private String _tmpltpp = "template.properties";
protected String createTemplateFromSnapshotXenScript;
private HashMap<String, UploadEntity> uploadEntityStateMap = new HashMap<String, UploadEntity>();
private String _ssvmPSK = null;
private long processTimeout;
public void setParentPath(String path) {
_parent = path;
}
public String getMountingRoot() {
return _parent;
}
@Override
public void disconnected() {
}
public void setInSystemVM(boolean inSystemVM) {
_inSystemVM = inSystemVM;
}
/**
* Retrieve converted "nfsVersion" value from params
* @param params
* @return nfsVersion value if exists, null in other case
*/
public static String retrieveNfsVersionFromParams(Map<String, Object> params) {
return (String)params.get("nfsVersion");
}
@Override
public Answer executeRequest(Command cmd) {
logger.debug(LogUtils.logGsonWithoutException("Executing command %s [%s].", cmd.getClass().getSimpleName(), cmd));
if (cmd instanceof DownloadProgressCommand) {
return _dlMgr.handleDownloadCommand(this, (DownloadProgressCommand)cmd);
} else if (cmd instanceof DownloadCommand) {
return execute((DownloadCommand)cmd);
} else if (cmd instanceof UploadCommand) {
return _upldMgr.handleUploadCommand(this, (UploadCommand)cmd);
} else if (cmd instanceof CreateEntityDownloadURLCommand) {
return _upldMgr.handleCreateEntityURLCommand((CreateEntityDownloadURLCommand)cmd);
} else if (cmd instanceof DeleteEntityDownloadURLCommand) {
return _upldMgr.handleDeleteEntityDownloadURLCommand((DeleteEntityDownloadURLCommand)cmd);
} else if (cmd instanceof GetStorageStatsCommand) {
return execute((GetStorageStatsCommand)cmd);
} else if (cmd instanceof CheckHealthCommand) {
return new CheckHealthAnswer((CheckHealthCommand)cmd, true);
} else if (cmd instanceof ReadyCommand) {
return new ReadyAnswer((ReadyCommand)cmd);
} else if (cmd instanceof SecStorageFirewallCfgCommand) {
return execute((SecStorageFirewallCfgCommand)cmd);
} else if (cmd instanceof SecStorageVMSetupCommand) {
return execute((SecStorageVMSetupCommand)cmd);
} else if (cmd instanceof SecStorageSetupCommand) {
return execute((SecStorageSetupCommand)cmd);
} else if (cmd instanceof ComputeChecksumCommand) {
return execute((ComputeChecksumCommand)cmd);
} else if (cmd instanceof ListTemplateCommand) {
return execute((ListTemplateCommand)cmd);
} else if (cmd instanceof ListVolumeCommand) {
return execute((ListVolumeCommand)cmd);
} else if (cmd instanceof DeleteSnapshotsDirCommand) {
return execute((DeleteSnapshotsDirCommand)cmd);
} else if (cmd instanceof CopyCommand) {
return execute((CopyCommand)cmd);
} else if (cmd instanceof DeleteCommand) {
return execute((DeleteCommand)cmd);
} else if (cmd instanceof UploadStatusCommand) {
return execute((UploadStatusCommand)cmd);
} else if (cmd instanceof HandleConfigDriveIsoCommand) {
return execute((HandleConfigDriveIsoCommand)cmd);
} else if (cmd instanceof GetDatadisksCommand) {
return execute((GetDatadisksCommand)cmd);
} else if (cmd instanceof CreateDatadiskTemplateCommand) {
return execute((CreateDatadiskTemplateCommand)cmd);
} else if (cmd instanceof MoveVolumeCommand) {
return execute((MoveVolumeCommand)cmd);
} else if (cmd instanceof ListDataStoreObjectsCommand) {
return execute((ListDataStoreObjectsCommand)cmd);
} else if (cmd instanceof QuerySnapshotZoneCopyCommand) {
return execute((QuerySnapshotZoneCopyCommand)cmd);
} else {
return Answer.createUnsupportedCommandAnswer(cmd);
}
}
private Answer execute(ListDataStoreObjectsCommand cmd) {
return listFilesAtPath(getRootDir(cmd.getStore().getUrl(), _nfsVersion), cmd.getPath(), cmd.getStartIndex(), cmd.getPageSize());
}
private Answer execute(HandleConfigDriveIsoCommand cmd) {
if (cmd.isCreate()) {
if (cmd.getIsoData() == null) {
return new HandleConfigDriveIsoAnswer(cmd, "Invalid config drive ISO data");
}
String nfsMountPoint = getRootDir(cmd.getDestStore().getUrl(), _nfsVersion);
File isoFile = new File(nfsMountPoint, cmd.getIsoFile());
if(isoFile.exists()) {
logger.debug("config drive iso already exists");
}
Path tempDir = null;
try {
tempDir = java.nio.file.Files.createTempDirectory(ConfigDrive.CONFIGDRIVEDIR);
File tmpIsoFile = ConfigDriveBuilder.base64StringToFile(cmd.getIsoData(), tempDir.toAbsolutePath().toString(), cmd.getIsoFile());
copyLocalToNfs(tmpIsoFile, new File(cmd.getIsoFile()), cmd.getDestStore());
} catch (IOException | ConfigurationException e) {
return new HandleConfigDriveIsoAnswer(cmd, "Failed due to exception: " + e.getMessage());
} finally {
try {
if (tempDir != null) {
FileUtils.deleteDirectory(tempDir.toFile());
}
} catch (IOException ioe) {
logger.warn("Failed to delete ConfigDrive temporary directory: " + tempDir.toString(), ioe);
}
}
return new HandleConfigDriveIsoAnswer(cmd, NetworkElement.Location.SECONDARY, "Successfully saved config drive at secondary storage");
} else {
DataStoreTO dstore = cmd.getDestStore();
if (dstore instanceof NfsTO) {
NfsTO nfs = (NfsTO) dstore;
String relativeTemplatePath = new File(cmd.getIsoFile()).getPath();
String nfsMountPoint = getRootDir(nfs.getUrl(), _nfsVersion);
File tmpltPath = new File(nfsMountPoint, relativeTemplatePath);
try {
Files.deleteIfExists(tmpltPath.toPath());
} catch (IOException e) {
return new HandleConfigDriveIsoAnswer(cmd, e);
}
return new HandleConfigDriveIsoAnswer(cmd);
} else {
return new HandleConfigDriveIsoAnswer(cmd, "Not implemented yet");
}
}
}
protected void copyLocalToNfs(File localFile, File isoFile, DataStoreTO destData) throws ConfigurationException, IOException {
String scriptsDir = "scripts/storage/secondary";
String createVolScr = Script.findScript(scriptsDir, "createvolume.sh");
if (createVolScr == null) {
throw new ConfigurationException("Unable to find createvolume.sh");
}
logger.info("createvolume.sh found in " + createVolScr);
int installTimeoutPerGig = 180 * 60 * 1000;
int imgSizeGigs = (int) Math.ceil(localFile.length() * 1.0d / (1024 * 1024 * 1024));
imgSizeGigs++; // add one just in case
long timeout = imgSizeGigs * installTimeoutPerGig;
Script scr = new Script(createVolScr, timeout, logger);
scr.add("-s", Integer.toString(imgSizeGigs));
scr.add("-n", isoFile.getName());
scr.add("-t", getRootDir(destData.getUrl(), _nfsVersion) + "/" + isoFile.getParent());
scr.add("-f", localFile.getAbsolutePath());
scr.add("-d", "configDrive");
String result;
result = scr.execute();
if (result != null) {
// script execution failure
throw new CloudRuntimeException("Failed to run script " + createVolScr);
}
}
public Answer execute(GetDatadisksCommand cmd) {
DataTO srcData = cmd.getData();
String configurationId = cmd.getConfigurationId();
TemplateObjectTO template = (TemplateObjectTO)srcData;
DataStoreTO srcStore = srcData.getDataStore();
if (!(srcStore instanceof NfsTO)) {
return new CreateDatadiskTemplateAnswer("Unsupported protocol");
}
NfsTO nfsImageStore = (NfsTO)srcStore;
String secondaryStorageUrl = nfsImageStore.getUrl();
assert (secondaryStorageUrl != null);
String templateUrl = secondaryStorageUrl + File.separator + srcData.getPath();
String templateDetails = ReflectionToStringBuilderUtils.reflectOnlySelectedFields(template, "uuid", "path", "name");
logger.debug(String.format("Trying to get disks of template [%s], using path [%s].", templateDetails, templateUrl));
Pair<String, String> templateInfo = decodeTemplateRelativePathAndNameFromUrl(secondaryStorageUrl, templateUrl, template.getName());
String templateRelativeFolderPath = templateInfo.first();
try {
String secondaryMountPoint = getRootDir(secondaryStorageUrl, _nfsVersion);
logger.info(String.format("Trying to find template [%s] in secondary storage root mount point [%s].", templateDetails, secondaryMountPoint));
String srcOVAFileName = getTemplateOnSecStorageFilePath(secondaryMountPoint, templateRelativeFolderPath, templateInfo.second(), ImageFormat.OVA.getFileExtension());
String ovfFilePath = getOVFFilePath(srcOVAFileName);
if (ovfFilePath == null) {
Script command = new Script("tar", 0, logger);
command.add("--no-same-owner");
command.add("--no-same-permissions");
command.add("-xf", srcOVAFileName);
command.setWorkDir(secondaryMountPoint + File.separator + templateRelativeFolderPath);
logger.info(String.format("Trying to decompress OVA file [%s] using command [%s].", srcOVAFileName, command.toString()));
String result = command.execute();
if (result != null) {
String msg = String.format("Unable to unpack snapshot OVA file [%s] due to [%s].", srcOVAFileName, result);
logger.error(msg);
throw new Exception(msg);
}
String directory = secondaryMountPoint + File.separator + templateRelativeFolderPath;
command = new Script("chmod", 0, logger);
command.add("-R");
command.add("666", directory);
logger.debug(String.format("Trying to add, recursivelly, permission 666 to directory [%s] using command [%s].", directory, command.toString()));
result = command.execute();
if (result != null) {
logger.warn(String.format("Unable to set permissions 666 for directory [%s] due to [%s].", directory, result));
}
}
Script command = new Script("cp", _timeout, logger);
command.add(ovfFilePath);
command.add(ovfFilePath + ORIGINAL_FILE_EXTENSION);
logger.debug(String.format("Trying to copy file from [%s] to [%s] using command [%s].", ovfFilePath, ovfFilePath + ORIGINAL_FILE_EXTENSION, command.toString()));
String result = command.execute();
if (result != null) {
String msg = String.format("Unable to copy original OVF file [%s] to [%s] due to [%s].", ovfFilePath, ovfFilePath + ORIGINAL_FILE_EXTENSION, result);
logger.error(msg);
}
logger.debug(String.format("Reading OVF file [%s] to retrive the number of disks present in OVA file.", ovfFilePath));
OVFHelper ovfHelper = new OVFHelper();
List<DatadiskTO> disks = ovfHelper.getOVFVolumeInfoFromFile(ovfFilePath, configurationId);
logger.debug(LogUtils.logGsonWithoutException("Found %s disks reading OVF file [%s] and using configuration id [%s]. The disks specifications are [%s].",
disks.size(), ovfFilePath, configurationId, disks));
return new GetDatadisksAnswer(disks);
} catch (Exception e) {
String msg = String.format("Failed to get disks from template [%s] due to [%s].", templateDetails, e.getMessage());
logger.error(msg, e);
return new GetDatadisksAnswer(msg);
}
}
public Answer execute(CreateDatadiskTemplateCommand cmd) {
TemplateObjectTO diskTemplate = new TemplateObjectTO();
TemplateObjectTO dataDiskTemplate = (TemplateObjectTO)cmd.getDataDiskTemplate();
DataStoreTO dataStore = dataDiskTemplate.getDataStore();
if (!(dataStore instanceof NfsTO)) {
return new CreateDatadiskTemplateAnswer("Unsupported protocol");
}
NfsTO nfsImageStore = (NfsTO)dataStore;
String secondaryStorageUrl = nfsImageStore.getUrl();
assert (secondaryStorageUrl != null);
try {
String secondaryMountPoint = getRootDir(secondaryStorageUrl, _nfsVersion);
long templateId = dataDiskTemplate.getId();
String templateUniqueName = dataDiskTemplate.getUniqueName();
if (logger.isDebugEnabled()) {
logger.debug(String.format("no cmd? %s", cmd.stringRepresentation()));
}
String origDisk = cmd.getPath();
long virtualSize = dataDiskTemplate.getSize();
String diskName = origDisk.substring((origDisk.lastIndexOf(File.separator)) + 1);
long physicalSize = new File(origDisk).length();
String newTmplDir = getTemplateRelativeDirInSecStorage(dataDiskTemplate.getAccountId(), dataDiskTemplate.getId());
String newTmplDirAbsolute = secondaryMountPoint + File.separator + newTmplDir;
String ovfFilePath = getOVFFilePath(origDisk);
if (!cmd.getBootable()) {
// Create folder to hold datadisk template
synchronized (newTmplDir.intern()) {
Script command = new Script("mkdir", _timeout, logger);
command.add("-p");
command.add(newTmplDirAbsolute);
String result = command.execute();
if (result != null) {
String msg = "Unable to prepare template directory: " + newTmplDir + ", storage: " + secondaryStorageUrl + ", error msg: " + result;
logger.error(msg);
throw new Exception(msg);
}
}
// Move Datadisk VMDK from parent template folder to Datadisk template folder
synchronized (origDisk.intern()) {
Script command = new Script("mv", _timeout, logger);
command.add(origDisk);
command.add(newTmplDirAbsolute);
String result = command.execute();
if (result != null) {
String msg = "Unable to copy VMDK from parent template folder to datadisk template folder" + ", error msg: " + result;
logger.error(msg);
throw new Exception(msg);
}
command = new Script("cp", _timeout, logger);
command.add(ovfFilePath + ORIGINAL_FILE_EXTENSION);
command.add(newTmplDirAbsolute);
result = command.execute();
if (result != null) {
String msg = "Unable to copy VMDK from parent template folder to datadisk template folder" + ", error msg: " + result;
logger.error(msg);
throw new Exception(msg);
}
}
}
// Create OVF for the disk
String newOvfFilePath = newTmplDirAbsolute + File.separator + ovfFilePath.substring(ovfFilePath.lastIndexOf(File.separator) + 1);
OVFHelper ovfHelper = new OVFHelper();
ovfHelper.rewriteOVFFileForSingleDisk(ovfFilePath + ORIGINAL_FILE_EXTENSION, newOvfFilePath, diskName);
postCreatePrivateTemplate(newTmplDirAbsolute, templateId, templateUniqueName, physicalSize, virtualSize);
writeMetaOvaForTemplate(newTmplDirAbsolute, ovfFilePath.substring(ovfFilePath.lastIndexOf(File.separator) + 1), diskName, templateUniqueName, physicalSize);
diskTemplate.setId(templateId);
if (diskName.endsWith("iso")){
diskTemplate.setPath(newTmplDir + File.separator + diskName);
}
else {
diskTemplate.setPath(newTmplDir + File.separator + templateUniqueName + ".ova");
}
diskTemplate.setSize(virtualSize);
diskTemplate.setPhysicalSize(physicalSize);
} catch (Exception e) {
String msg = "Create Datadisk template failed due to " + e.getMessage();
logger.error(msg, e);
return new CreateDatadiskTemplateAnswer(msg);
}
return new CreateDatadiskTemplateAnswer(diskTemplate);
}
public Answer execute(MoveVolumeCommand cmd) {
String volumeToString = ReflectionToStringBuilderUtils.reflectOnlySelectedFields(cmd, "volumeUuid", "volumeName");
String rootDir = getRootDir(cmd.getDatastoreUri(), _nfsVersion);
if (!rootDir.endsWith("/")) {
rootDir += "/";
}
Path srcPath = Paths.get(rootDir + cmd.getSrcPath());
Path destPath = Paths.get(rootDir + cmd.getDestPath());
try {
logger.debug(String.format("Trying to create missing directories (if any) to move volume [%s].", volumeToString));
Files.createDirectories(destPath.getParent());
logger.debug(String.format("Trying to move volume [%s] to [%s].", volumeToString, destPath));
Files.move(srcPath, destPath);
String msg = String.format("Moved volume [%s] from [%s] to [%s].", volumeToString, srcPath, destPath);
logger.debug(msg);
return new Answer(cmd, true, msg);
} catch (IOException ioException) {
logger.error(String.format("Failed to move volume [%s] from [%s] to [%s] due to [%s].", volumeToString, srcPath, destPath, ioException.getMessage()),
ioException);
return new Answer(cmd, ioException);
}
}
/*
* return Pair of <Template relative path, Template name>
* Template url may or may not end with .ova extension
*/
public Pair<String, String> decodeTemplateRelativePathAndNameFromUrl(String storeUrl, String templateUrl, String defaultName) {
logger.debug(String.format("Trying to get template relative path and name from URL [%s].", templateUrl));
String templateName = null;
String mountPoint = null;
if (templateUrl.endsWith(".ova")) {
int index = templateUrl.lastIndexOf("/");
mountPoint = templateUrl.substring(0, index);
mountPoint = mountPoint.substring(storeUrl.length() + 1);
if (!mountPoint.endsWith("/")) {
mountPoint = mountPoint + "/";
}
templateName = templateUrl.substring(index + 1).replace(".ova", "");
if (templateName == null || templateName.isEmpty()) {
logger.debug(String.format("Cannot find template name from URL [%s]. Using default name [%s].", templateUrl, defaultName));
templateName = defaultName;
}
} else {
mountPoint = templateUrl.substring(storeUrl.length() + 1);
if (!mountPoint.endsWith("/")) {
mountPoint = mountPoint + "/";
}
templateName = defaultName;
}
logger.debug(String.format("Template relative path [%s] and name [%s] found from URL [%s].", mountPoint, templateName, templateUrl));
return new Pair<String, String>(mountPoint, templateName);
}
public String getTemplateOnSecStorageFilePath(String secStorageMountPoint, String templateRelativeFolderPath, String templateName, String fileExtension) {
logger.debug(String.format("Trying to find template [%s] with file extension [%s] in secondary storage mount point [%s] using relative folder path [%s].",
templateName, fileExtension, secStorageMountPoint, templateRelativeFolderPath));
StringBuffer sb = new StringBuffer();
sb.append(secStorageMountPoint);
if (!secStorageMountPoint.endsWith("/")) {
sb.append("/");
}
sb.append(templateRelativeFolderPath);
if (!secStorageMountPoint.endsWith("/")) {
sb.append("/");
}
sb.append(templateName);
if (!fileExtension.startsWith(".")) {
sb.append(".");
}
sb.append(fileExtension);
return sb.toString();
}
public static String getSecondaryDatastoreUUID(String storeUrl) {
return UUID.nameUUIDFromBytes(storeUrl.getBytes()).toString();
}
private static String getTemplateRelativeDirInSecStorage(long accountId, long templateId) {
return "template/tmpl/" + accountId + "/" + templateId;
}
private void postCreatePrivateTemplate(final String installFullPath, final long templateId, final String templateName, final long size, final long virtualSize) throws Exception {
// TODO a bit ugly here
try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(installFullPath + "/template.properties"), "UTF-8"));) {
out.write("filename=" + templateName + ".ova");
out.newLine();
out.write("description=privateTemplate");
out.newLine();
out.write("hvm=false");
out.newLine();
out.write("size=" + size);
out.newLine();
out.write("ova=false");
out.newLine();
out.write("id=" + templateId);
out.newLine();
out.write("ova.filename=" + templateName + ".ova");
out.newLine();
out.write("uniquename=" + templateName);
out.newLine();
out.write("ova.virtualsize=" + virtualSize);
out.newLine();
out.write("virtualsize=" + virtualSize);
out.newLine();
out.write("ova.size=" + size);
out.newLine();
out.write("checksum=");
out.newLine();
out.write("public=false");
out.newLine();
}
}
private void writeMetaOvaForTemplate(final String installFullPath, final String ovfFilename, final String vmdkFilename, final String templateName, final long diskSize) throws Exception {
// TODO a bit ugly here
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(installFullPath + "/" + templateName + ".ova.meta"), "UTF-8"));
out.write("ova.filename=" + templateName + ".ova");
out.newLine();
out.write("version=1.0");
out.newLine();
out.write("ovf=" + ovfFilename);
out.newLine();
out.write("numDisks=1");
out.newLine();
out.write("disk1.name=" + vmdkFilename);
out.newLine();
out.write("disk1.size=" + diskSize);
out.newLine();
} finally {
if (out != null) {
out.close();
}
}
}
private String getOVFFilePath(String srcOVAFileName) {
logger.debug(String.format("Trying to get OVF file from OVA path [%s].", srcOVAFileName));
File file = new File(srcOVAFileName);
assert (_storage != null);
String[] files = _storage.listFiles(file.getParent());
if (files == null) {
logger.warn(String.format("Cannot find any files in parent directory [%s] of OVA file [%s].", file.getParent(), srcOVAFileName));
return null;
}
logger.debug(String.format("Found [%s] files in parent directory of OVA file [%s]. Files found are [%s].", files.length + 1, file.getParent(), StringUtils.join(files, ", ")));
for (String fileName : files) {
if (fileName.toLowerCase().endsWith(".ovf")) {
File ovfFile = new File(fileName);
String ovfFilePath = file.getParent() + File.separator + ovfFile.getName();
logger.debug(String.format("Found OVF file [%s] from OVA file [%s].", ovfFilePath, srcOVAFileName));
return ovfFilePath;
}
}
logger.warn(String.format("Cannot find any OVF file in parent directory [%s] of OVA file [%s].", file.getParent(), srcOVAFileName));
return null;
}
protected CopyCmdAnswer postProcessing(File destFile, String downloadPath, String destPath, DataTO srcData, DataTO destData) throws ConfigurationException {
if (destData.getObjectType() == DataObjectType.SNAPSHOT) {
SnapshotObjectTO snapshot = new SnapshotObjectTO();
snapshot.setPath(destPath + File.separator + destFile.getName());
CopyCmdAnswer answer = new CopyCmdAnswer(snapshot);
return answer;
}
// do post processing to unzip the file if it is compressed
String scriptsDir = "scripts/storage/secondary";
String createTmpltScr = Script.findScript(scriptsDir, "createtmplt.sh");
if (createTmpltScr == null) {
throw new ConfigurationException("Unable to find createtmplt.sh");
}
logger.info("createtmplt.sh found in " + createTmpltScr);
String createVolScr = Script.findScript(scriptsDir, "createvolume.sh");
if (createVolScr == null) {
throw new ConfigurationException("Unable to find createvolume.sh");
}
logger.info("createvolume.sh found in " + createVolScr);
String script = srcData.getObjectType() == DataObjectType.TEMPLATE ? createTmpltScr : createVolScr;
int installTimeoutPerGig = 180 * 60 * 1000;
long imgSizeGigs = (long)Math.ceil(destFile.length() * 1.0d / (1024 * 1024 * 1024));
imgSizeGigs++; // add one just in case
long timeout = imgSizeGigs * installTimeoutPerGig;
String origPath = destFile.getAbsolutePath();
String extension = null;
if (srcData.getObjectType() == DataObjectType.TEMPLATE) {
extension = ((TemplateObjectTO)srcData).getFormat().getFileExtension();
} else if (srcData.getObjectType() == DataObjectType.VOLUME) {
extension = ((VolumeObjectTO)srcData).getFormat().getFileExtension();
}
String templateName = UUID.randomUUID().toString();
String templateFilename = templateName + "." + extension;
Script scr = new Script(script, timeout, logger);
scr.add("-s", Long.toString(imgSizeGigs)); // not used for now
scr.add("-n", templateFilename);
scr.add("-t", downloadPath);
scr.add("-f", origPath); // this is the temporary
// template file downloaded
String result;
result = scr.execute();
if (result != null) {
// script execution failure
throw new CloudRuntimeException("Failed to run script " + script);
}
String finalFileName = templateFilename;
String finalDownloadPath = destPath + File.separator + templateFilename;
// compute the size of
long size = _storage.getSize(downloadPath + File.separator + templateFilename);
DataTO newDestTO = null;
if (destData.getObjectType() == DataObjectType.TEMPLATE) {
TemplateObjectTO newTemplTO = new TemplateObjectTO();
newTemplTO.setPath(finalDownloadPath);
newTemplTO.setName(finalFileName);
newTemplTO.setSize(size);
newTemplTO.setPhysicalSize(size);
newDestTO = newTemplTO;
} else {
VolumeObjectTO newVolTO = new VolumeObjectTO();
newVolTO.setPath(finalDownloadPath);
newVolTO.setName(finalFileName);
newVolTO.setSize(size);
newDestTO = newVolTO;
}
return new CopyCmdAnswer(newDestTO);
}
protected Answer copyFromSwiftToNfs(CopyCommand cmd, DataTO srcData, SwiftTO swiftTO, DataTO destData, NfsTO destImageStore) {
final String storagePath = destImageStore.getUrl();
final String destPath = destData.getPath();
try {
String downloadPath = determineStorageTemplatePath(storagePath, destPath, _nfsVersion);
final File downloadDirectory = _storage.getFile(downloadPath);
if (downloadDirectory.exists()) {
logger.debug("Directory " + downloadPath + " already exists");
} else {
if (!downloadDirectory.mkdirs()) {
final String errMsg = "Unable to create directory " + downloadPath + " to copy from Swift to cache.";
logger.error(errMsg);
return new CopyCmdAnswer(errMsg);
}
}
File destFile = SwiftUtil.getObject(swiftTO, downloadDirectory, srcData.getPath());
return postProcessing(destFile, downloadPath, destPath, srcData, destData);
} catch (Exception e) {
logger.debug("Failed to copy swift to nfs", e);
return new CopyCmdAnswer(e.toString());
}
}
protected Answer copyFromS3ToNfs(CopyCommand cmd, DataTO srcData, S3TO s3, DataTO destData, NfsTO destImageStore) {
final String storagePath = destImageStore.getUrl();
final String destPath = destData.getPath();
try {
String downloadPath = determineStorageTemplatePath(storagePath, destPath, _nfsVersion);
final File downloadDirectory = _storage.getFile(downloadPath);
if (downloadDirectory.exists()) {
logger.debug("Directory " + downloadPath + " already exists");
} else {
if (!downloadDirectory.mkdirs()) {
final String errMsg = "Unable to create directory " + downloadPath + " to copy from S3 to cache.";
logger.error(errMsg);
return new CopyCmdAnswer(errMsg);
}
}
File destFile = new File(downloadDirectory, StringUtils.substringAfterLast(srcData.getPath(), S3Utils.SEPARATOR));
S3Utils.getFile(s3, s3.getBucketName(), srcData.getPath(), destFile).waitForCompletion();
return postProcessing(destFile, downloadPath, destPath, srcData, destData);
} catch (Exception e) {
final String errMsg = String.format("Failed to download" + "due to $1%s", e.getMessage());
logger.error(errMsg, e);
return new CopyCmdAnswer(errMsg);
}
}
protected Answer copySnapshotToTemplateFromNfsToNfsXenserver(CopyCommand cmd, SnapshotObjectTO srcData, NfsTO srcDataStore, TemplateObjectTO destData, NfsTO destDataStore) {
String srcMountPoint = getRootDir(srcDataStore.getUrl(), _nfsVersion);
String snapshotPath = srcData.getPath();
int index = snapshotPath.lastIndexOf("/");
String snapshotName = snapshotPath.substring(index + 1);
if (!snapshotName.startsWith("VHD-") && !snapshotName.endsWith(".vhd")) {
snapshotName = snapshotName + ".vhd";
}
snapshotPath = snapshotPath.substring(0, index);
snapshotPath = srcMountPoint + File.separator + snapshotPath;
String destMountPoint = getRootDir(destDataStore.getUrl(), _nfsVersion);
String destPath = destMountPoint + File.separator + destData.getPath();
String errMsg = null;
try {
_storage.mkdir(destPath);
String templateUuid = UUID.randomUUID().toString();
String templateName = templateUuid + ".vhd";
Script command = new Script(createTemplateFromSnapshotXenScript, cmd.getWait() * 1000L, logger);
command.add("-p", snapshotPath);
command.add("-s", snapshotName);
command.add("-n", templateName);
command.add("-t", destPath);
String result = command.execute();
if (result != null && !result.equalsIgnoreCase("")) {
return new CopyCmdAnswer(result);
}
Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, _storage);
Processor processor = new VhdProcessor();
processor.configure("Vhd Processor", params);
FormatInfo info = processor.process(destPath, null, templateUuid);
TemplateLocation loc = new TemplateLocation(_storage, destPath);
loc.create(1, true, templateUuid);
loc.addFormat(info);
loc.save();
TemplateProp prop = loc.getTemplateInfo();
TemplateObjectTO newTemplate = new TemplateObjectTO();
newTemplate.setPath(destData.getPath() + File.separator + templateName);
newTemplate.setFormat(ImageFormat.VHD);
newTemplate.setSize(prop.getSize());
newTemplate.setPhysicalSize(prop.getPhysicalSize());
newTemplate.setName(templateUuid);
return new CopyCmdAnswer(newTemplate);
} catch (ConfigurationException e) {
logger.debug("Failed to create template from snapshot: " + e.toString());
errMsg = e.toString();
} catch (InternalErrorException e) {
logger.debug("Failed to create template from snapshot: " + e.toString());
errMsg = e.toString();
} catch (IOException e) {
logger.debug("Failed to create template from snapshot: " + e.toString());
errMsg = e.toString();
}
return new CopyCmdAnswer(errMsg);
}
protected Answer copySnapshotToTemplateFromNfsToNfs(CopyCommand cmd, SnapshotObjectTO srcData, NfsTO srcDataStore, TemplateObjectTO destData, NfsTO destDataStore) {
if (srcData.getHypervisorType() == HypervisorType.XenServer) {
return copySnapshotToTemplateFromNfsToNfsXenserver(cmd, srcData, srcDataStore, destData, destDataStore);
} else if (srcData.getHypervisorType() == HypervisorType.KVM) {
File srcFile = getFile(srcData.getPath(), srcDataStore.getUrl(), _nfsVersion);
File destFile = getFile(destData.getPath(), destDataStore.getUrl(), _nfsVersion);
VolumeObjectTO volumeObjectTO = srcData.getVolume();
ImageFormat srcFormat = null;
//TODO: the image format should be stored in snapshot table, instead of getting from volume
if (volumeObjectTO != null) {
srcFormat = volumeObjectTO.getFormat();
} else {
srcFormat = ImageFormat.QCOW2;
}
// get snapshot file name
String templateName = srcFile.getName();
// add kvm file extension for copied template name
String fileName = templateName + "." + srcFormat.getFileExtension();
String destFileFullPath = destFile.getAbsolutePath() + File.separator + fileName;
logger.debug("copy snapshot " + srcFile.getAbsolutePath() + " to template " + destFileFullPath);
Script.runSimpleBashScript("cp " + srcFile.getAbsolutePath() + " " + destFileFullPath);
String metaFileName = destFile.getAbsolutePath() + File.separator + _tmpltpp;
File metaFile = new File(metaFileName);
try {
_storage.create(destFile.getAbsolutePath(), _tmpltpp);
try ( // generate template.properties file
FileWriter writer = new FileWriter(metaFile); BufferedWriter bufferWriter = new BufferedWriter(writer);) {
// KVM didn't change template unique name, just used the template name passed from orchestration layer, so no need
// to send template name back.
bufferWriter.write("uniquename=" + destData.getName());
bufferWriter.write("\n");
bufferWriter.write("filename=" + fileName);
}
try {
/**
* Snapshots might be in either QCOW2 or RAW image format
*
* For example RBD snapshots are in RAW format
*/
Processor processor = null;
if (srcFormat == ImageFormat.QCOW2) {
processor = new QCOW2Processor();
} else if (srcFormat == ImageFormat.RAW) {