forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathConsoleProxyManagerImpl.java
More file actions
1768 lines (1523 loc) · 73 KB
/
ConsoleProxyManagerImpl.java
File metadata and controls
1768 lines (1523 loc) · 73 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.
package com.cloud.consoleproxy;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.agent.lb.IndirectAgentLB;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.security.keys.KeysManager;
import org.apache.cloudstack.framework.security.keystore.KeystoreDao;
import org.apache.cloudstack.framework.security.keystore.KeystoreManager;
import org.apache.cloudstack.framework.security.keystore.KeystoreVO;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.ConsoleProxyLoadReportCommand;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupProxyCommand;
import com.cloud.agent.api.check.CheckSshAnswer;
import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
import com.cloud.agent.manager.Commands;
import com.cloud.cluster.ClusterManager;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManagerImpl;
import com.cloud.configuration.ZoneConfig;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.host.Host;
import com.cloud.host.Host.Type;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.info.ConsoleProxyConnectionInfo;
import com.cloud.info.ConsoleProxyInfo;
import com.cloud.info.ConsoleProxyLoadInfo;
import com.cloud.info.ConsoleProxyStatus;
import com.cloud.info.RunningHostCountInfo;
import com.cloud.info.RunningHostInfoAgregator;
import com.cloud.info.RunningHostInfoAgregator.ZoneHostInfo;
import com.cloud.network.Network;
import com.cloud.network.NetworkModel;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.IPAddressVO;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.rules.RulesManager;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceStateAdapter;
import com.cloud.resource.ServerResource;
import com.cloud.resource.UnableDeleteHostException;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.Storage;
import com.cloud.storage.StoragePoolStatus;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.QueryBuilder;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.events.SubscriptionMgr;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.ConsoleProxyVO;
import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext;
import com.cloud.vm.SystemVmLoadScanHandler;
import com.cloud.vm.SystemVmLoadScanner;
import com.cloud.vm.SystemVmLoadScanner.AfterScanAction;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineGuru;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineName;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.ConsoleProxyDao;
import com.cloud.vm.dao.UserVmDetailsDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
//
// Possible console proxy state transition cases
// Stopped --> Starting -> Running
// HA -> Stopped -> Starting -> Running
// Migrating -> Running (if previous state is Running before it enters into Migrating state
// Migrating -> Stopped (if previous state is not Running before it enters into Migrating state)
// Running -> HA (if agent lost connection)
// Stopped -> Destroyed
//
// Starting, HA, Migrating, Running state are all counted as "Open" for available capacity calculation
// because sooner or later, it will be driven into Running state
//
public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxyManager, VirtualMachineGuru, SystemVmLoadScanHandler<Long>, ResourceStateAdapter, Configurable {
private static final Logger s_logger = Logger.getLogger(ConsoleProxyManagerImpl.class);
private static final int DEFAULT_CAPACITY_SCAN_INTERVAL = 30000; // 30 seconds
private static final int ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC = 180; // 3 minutes
private static final int STARTUP_DELAY = 60000; // 60 seconds
private int _consoleProxyPort = ConsoleProxyManager.DEFAULT_PROXY_VNC_PORT;
private int _mgmtPort = 8250;
private List<ConsoleProxyAllocator> _consoleProxyAllocators;
@Inject
private ConsoleProxyDao _consoleProxyDao;
@Inject
private DataCenterDao _dcDao;
@Inject
private VMTemplateDao _templateDao;
@Inject
private HostPodDao _podDao;
@Inject
private HostDao _hostDao;
@Inject
private ConfigurationDao _configDao;
@Inject
private VMInstanceDao _instanceDao;
@Inject
private TemplateDataStoreDao _vmTemplateStoreDao;
@Inject
private AgentManager _agentMgr;
@Inject
private NetworkOrchestrationService _networkMgr;
@Inject
private NetworkModel _networkModel;
@Inject
private AccountManager _accountMgr;
@Inject
private ServiceOfferingDao _offeringDao;
@Inject
private NetworkOfferingDao _networkOfferingDao;
@Inject
private PrimaryDataStoreDao _storagePoolDao;
@Inject
private UserVmDetailsDao _vmDetailsDao;
@Inject
private ResourceManager _resourceMgr;
@Inject
private NetworkDao _networkDao;
@Inject
private RulesManager _rulesMgr;
@Inject
private IPAddressDao _ipAddressDao;
@Inject
private KeysManager _keysMgr;
@Inject
private VirtualMachineManager _itMgr;
@Inject
private IndirectAgentLB indirectAgentLB;
private ConsoleProxyListener _listener;
private ServiceOfferingVO _serviceOffering;
/*
* private final ExecutorService _requestHandlerScheduler = Executors.newCachedThreadPool(new
* NamedThreadFactory("Request-handler"));
*/
private long _capacityScanInterval = DEFAULT_CAPACITY_SCAN_INTERVAL;
private int _capacityPerProxy = ConsoleProxyManager.DEFAULT_PROXY_CAPACITY;
private int _standbyCapacity = ConsoleProxyManager.DEFAULT_STANDBY_CAPACITY;
private boolean _useStorageVm;
private boolean _disableRpFilter = false;
private String _instance;
private int _proxySessionTimeoutValue = DEFAULT_PROXY_SESSION_TIMEOUT;
private boolean _sslEnabled = false;
private String _consoleProxyUrlDomain;
// global load picture at zone basis
private SystemVmLoadScanner<Long> _loadScanner;
private Map<Long, ZoneHostInfo> _zoneHostInfoMap; // map <zone id, info about running host in zone>
private Map<Long, ConsoleProxyLoadInfo> _zoneProxyCountMap; // map <zone id, info about proxy VMs count in zone>
private Map<Long, ConsoleProxyLoadInfo> _zoneVmCountMap; // map <zone id, info about running VMs count in zone>
private String _staticPublicIp;
private int _staticPort;
private final GlobalLock _allocProxyLock = GlobalLock.getInternLock(getAllocProxyLockName());
@Inject
private KeystoreDao _ksDao;
@Inject
private KeystoreManager _ksMgr;
public class VmBasedAgentHook extends AgentHookBase {
public VmBasedAgentHook(VMInstanceDao instanceDao, HostDao hostDao, ConfigurationDao cfgDao, KeystoreManager ksMgr, AgentManager agentMgr, KeysManager keysMgr) {
super(instanceDao, hostDao, cfgDao, ksMgr, agentMgr, keysMgr);
}
@Override
public void onLoadReport(ConsoleProxyLoadReportCommand cmd) {
if (cmd.getLoadInfo() == null) {
return;
}
ConsoleProxyStatus status = null;
try {
GsonBuilder gb = new GsonBuilder();
gb.setVersion(1.3);
Gson gson = gb.create();
status = gson.fromJson(cmd.getLoadInfo(), ConsoleProxyStatus.class);
} catch (Throwable e) {
s_logger.warn("Unable to parse load info from proxy, proxy vm id : " + cmd.getProxyVmId() + ", info : " + cmd.getLoadInfo());
}
if (status != null) {
int count = 0;
if (status.getConnections() != null) {
count = status.getConnections().length;
}
byte[] details = null;
if (cmd.getLoadInfo() != null) {
details = cmd.getLoadInfo().getBytes(Charset.forName("US-ASCII"));
}
_consoleProxyDao.update(cmd.getProxyVmId(), count, DateUtil.currentGMTTime(), details);
} else {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Unable to get console proxy load info, id : " + cmd.getProxyVmId());
}
_consoleProxyDao.update(cmd.getProxyVmId(), 0, DateUtil.currentGMTTime(), null);
}
}
@Override
public void onAgentDisconnect(long agentId, com.cloud.host.Status state) {
if (state == com.cloud.host.Status.Alert || state == com.cloud.host.Status.Disconnected) {
// be it either in alert or in disconnected state, the agent
// process
// may be gone in the VM,
// we will be reacting to stop the corresponding VM and let the
// scan
// process to
HostVO host = _hostDao.findById(agentId);
if (host.getType() == Type.ConsoleProxy) {
String name = host.getName();
if (s_logger.isInfoEnabled()) {
s_logger.info("Console proxy agent disconnected, proxy: " + name);
}
if (name != null && name.startsWith("v-")) {
String[] tokens = name.split("-");
long proxyVmId = 0;
try {
proxyVmId = Long.parseLong(tokens[1]);
} catch (NumberFormatException e) {
s_logger.error("Unexpected exception " + e.getMessage(), e);
return;
}
final ConsoleProxyVO proxy = _consoleProxyDao.findById(proxyVmId);
if (proxy != null) {
// Disable this feature for now, as it conflicts
// with
// the case of allowing user to reboot console proxy
// when rebooting happens, we will receive
// disconnect
// here and we can't enter into stopping process,
// as when the rebooted one comes up, it will kick
// off a
// newly started one and trigger the process
// continue on forever
/*
* _capacityScanScheduler.execute(new Runnable() {
* public void run() { if(s_logger.isInfoEnabled())
* s_logger.info("Stop console proxy " +
* proxy.getName() +
* " VM because of that the agent running inside it has disconnected"
* ); stopProxy(proxy.getId()); } });
*/
} else {
if (s_logger.isInfoEnabled()) {
s_logger.info("Console proxy agent disconnected but corresponding console proxy VM no longer exists in DB, proxy: " + name);
}
}
} else {
assert (false) : "Invalid console proxy name: " + name;
}
}
}
}
@Override
protected HostVO findConsoleProxyHost(StartupProxyCommand startupCmd) {
long proxyVmId = startupCmd.getProxyVmId();
ConsoleProxyVO consoleProxy = _consoleProxyDao.findById(proxyVmId);
if (consoleProxy == null) {
s_logger.info("Proxy " + proxyVmId + " is no longer in DB, skip sending startup command");
return null;
}
assert (consoleProxy != null);
return findConsoleProxyHostByName(consoleProxy.getHostName());
}
}
@Override
public ConsoleProxyInfo assignProxy(final long dataCenterId, final long vmId) {
ConsoleProxyVO proxy = doAssignProxy(dataCenterId, vmId);
if (proxy == null) {
return null;
}
if (proxy.getPublicIpAddress() == null) {
s_logger.warn("Assigned console proxy does not have a valid public IP address");
return null;
}
KeystoreVO ksVo = _ksDao.findByName(ConsoleProxyManager.CERTIFICATE_NAME);
if (proxy.isSslEnabled() && ksVo == null) {
s_logger.warn("SSL enabled for console proxy but no server certificate found in database");
}
if (_staticPublicIp == null) {
return new ConsoleProxyInfo(proxy.isSslEnabled(), proxy.getPublicIpAddress(), _consoleProxyPort, proxy.getPort(), _consoleProxyUrlDomain);
} else {
return new ConsoleProxyInfo(proxy.isSslEnabled(), _staticPublicIp, _consoleProxyPort, _staticPort, _consoleProxyUrlDomain);
}
}
public ConsoleProxyVO doAssignProxy(long dataCenterId, long vmId) {
ConsoleProxyVO proxy = null;
VMInstanceVO vm = _instanceDao.findById(vmId);
if (vm == null) {
s_logger.warn("VM " + vmId + " no longer exists, return a null proxy for vm:" + vmId);
return null;
}
if (vm != null && vm.getState() != State.Starting && vm.getState() != State.Running
&& vm.getState() != State.Stopping && vm.getState() != State.Migrating) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Detected that vm : " + vmId + " is not currently in starting or running or stopping or migrating state, we will fail the proxy assignment for it");
}
return null;
}
if (_allocProxyLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC)) {
try {
if (vm.getProxyId() != null) {
proxy = _consoleProxyDao.findById(vm.getProxyId());
if (proxy != null) {
if (!isInAssignableState(proxy)) {
if (s_logger.isInfoEnabled()) {
s_logger.info("A previous assigned proxy is not assignable now, reassign console proxy for user vm : " + vmId);
}
proxy = null;
} else {
if (_consoleProxyDao.getProxyActiveLoad(proxy.getId()) < _capacityPerProxy || hasPreviousSession(proxy, vm)) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Assign previous allocated console proxy for user vm : " + vmId);
}
if (proxy.getActiveSession() >= _capacityPerProxy) {
s_logger.warn("Assign overloaded proxy to user VM as previous session exists, user vm : " + vmId);
}
} else {
proxy = null;
}
}
}
}
if (proxy == null) {
proxy = assignProxyFromRunningPool(dataCenterId);
}
} finally {
_allocProxyLock.unlock();
}
} else {
s_logger.error("Unable to acquire synchronization lock to get/allocate proxy resource for vm :" + vmId +
". Previous console proxy allocation is taking too long");
}
if (proxy == null) {
s_logger.warn("Unable to find or allocate console proxy resource");
return null;
}
// if it is a new assignment or a changed assignment, update the record
if (vm.getProxyId() == null || vm.getProxyId().longValue() != proxy.getId()) {
_instanceDao.updateProxyId(vmId, proxy.getId(), DateUtil.currentGMTTime());
}
proxy.setSslEnabled(_sslEnabled);
if (_sslEnabled) {
proxy.setPort(443);
} else {
proxy.setPort(80);
}
return proxy;
}
private static boolean isInAssignableState(ConsoleProxyVO proxy) {
// console proxies that are in states of being able to serve user VM
State state = proxy.getState();
if (state == State.Running) {
return true;
}
return false;
}
private boolean hasPreviousSession(ConsoleProxyVO proxy, VMInstanceVO vm) {
ConsoleProxyStatus status = null;
try {
GsonBuilder gb = new GsonBuilder();
gb.setVersion(1.3);
Gson gson = gb.create();
byte[] details = proxy.getSessionDetails();
status = gson.fromJson(details != null ? new String(details, Charset.forName("US-ASCII")) : null, ConsoleProxyStatus.class);
} catch (Throwable e) {
s_logger.warn("Unable to parse proxy session details : " + Arrays.toString(proxy.getSessionDetails()));
}
if (status != null && status.getConnections() != null) {
ConsoleProxyConnectionInfo[] connections = status.getConnections();
for (int i = 0; i < connections.length; i++) {
long taggedVmId = 0;
if (connections[i].tag != null) {
try {
taggedVmId = Long.parseLong(connections[i].tag);
} catch (NumberFormatException e) {
s_logger.warn("Unable to parse console proxy connection info passed through tag: " + connections[i].tag, e);
}
}
if (taggedVmId == vm.getId()) {
return true;
}
}
//
// even if we are not in the list, it may because we haven't
// received load-update yet
// wait until session time
//
if (DateUtil.currentGMTTime().getTime() - vm.getProxyAssignTime().getTime() < _proxySessionTimeoutValue) {
return true;
}
return false;
} else {
s_logger.error("No proxy load info on an overloaded proxy ?");
return false;
}
}
@Override
public ConsoleProxyVO startProxy(long proxyVmId, boolean ignoreRestartSetting) {
try {
ConsoleProxyVO proxy = _consoleProxyDao.findById(proxyVmId);
if (proxy.getState() == VirtualMachine.State.Running) {
return proxy;
}
String restart = _configDao.getValue(Config.ConsoleProxyRestart.key());
if (!ignoreRestartSetting && restart != null && restart.equalsIgnoreCase("false")) {
return null;
}
if (proxy.getState() == VirtualMachine.State.Stopped) {
_itMgr.advanceStart(proxy.getUuid(), null, null);
proxy = _consoleProxyDao.findById(proxy.getId());
return proxy;
}
// For VMs that are in Stopping, Starting, Migrating state, let client to wait by returning null
// as sooner or later, Starting/Migrating state will be transited to Running and Stopping will be transited
// to Stopped to allow Starting of it
s_logger.warn("Console proxy is not in correct state to be started: " + proxy.getState());
return null;
} catch (StorageUnavailableException e) {
s_logger.warn("Exception while trying to start console proxy", e);
return null;
} catch (InsufficientCapacityException e) {
s_logger.warn("Exception while trying to start console proxy", e);
return null;
} catch (ResourceUnavailableException e) {
s_logger.warn("Exception while trying to start console proxy", e);
return null;
} catch (ConcurrentOperationException e) {
s_logger.warn("Runtime Exception while trying to start console proxy", e);
return null;
} catch (CloudRuntimeException e) {
s_logger.warn("Runtime Exception while trying to start console proxy", e);
return null;
} catch (OperationTimedoutException e) {
s_logger.warn("Runtime Exception while trying to start console proxy", e);
return null;
}
}
public ConsoleProxyVO assignProxyFromRunningPool(long dataCenterId) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Assign console proxy from running pool for request from data center : " + dataCenterId);
}
ConsoleProxyAllocator allocator = getCurrentAllocator();
assert (allocator != null);
List<ConsoleProxyVO> runningList = _consoleProxyDao.getProxyListInStates(dataCenterId, State.Running);
if (runningList != null && runningList.size() > 0) {
Iterator<ConsoleProxyVO> it = runningList.iterator();
while (it.hasNext()) {
ConsoleProxyVO proxy = it.next();
if (proxy.getActiveSession() >= _capacityPerProxy) {
it.remove();
}
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Running proxy pool size : " + runningList.size());
for (ConsoleProxyVO proxy : runningList) {
s_logger.trace("Running proxy instance : " + proxy.getHostName());
}
}
List<Pair<Long, Integer>> l = _consoleProxyDao.getProxyLoadMatrix();
Map<Long, Integer> loadInfo = new HashMap<Long, Integer>();
if (l != null) {
for (Pair<Long, Integer> p : l) {
loadInfo.put(p.first(), p.second());
if (s_logger.isTraceEnabled()) {
s_logger.trace("Running proxy instance allocation load { proxy id : " + p.first() + ", load : " + p.second() + "}");
}
}
}
Long allocated = allocator.allocProxy(runningList, loadInfo, dataCenterId);
if (allocated == null) {
s_logger.debug("Unable to find a console proxy ");
return null;
}
return _consoleProxyDao.findById(allocated);
} else {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Empty running proxy pool for now in data center : " + dataCenterId);
}
}
return null;
}
public ConsoleProxyVO assignProxyFromStoppedPool(long dataCenterId) {
// practically treat all console proxy VM that is not in Running state but can be entering into Running state as
// candidates
// this is to prevent launching unneccessary console proxy VMs because of temporarily unavailable state
List<ConsoleProxyVO> l = _consoleProxyDao.getProxyListInStates(dataCenterId, State.Starting, State.Stopped, State.Migrating, State.Stopping);
if (l != null && l.size() > 0) {
return l.get(0);
}
return null;
}
public ConsoleProxyVO startNew(long dataCenterId) throws ConcurrentOperationException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Assign console proxy from a newly started instance for request from data center : " + dataCenterId);
}
if (!allowToLaunchNew(dataCenterId)) {
s_logger.warn("The number of launched console proxy on zone " + dataCenterId + " has reached to limit");
return null;
}
VMTemplateVO template = null;
HypervisorType availableHypervisor = _resourceMgr.getAvailableHypervisor(dataCenterId);
template = _templateDao.findSystemVMReadyTemplate(dataCenterId, availableHypervisor);
if (template == null) {
throw new CloudRuntimeException("Not able to find the System templates or not downloaded in zone " + dataCenterId);
}
Map<String, Object> context = createProxyInstance(dataCenterId, template);
long proxyVmId = (Long)context.get("proxyVmId");
if (proxyVmId == 0) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Creating proxy instance failed, data center id : " + dataCenterId);
}
return null;
}
ConsoleProxyVO proxy = _consoleProxyDao.findById(proxyVmId);
if (proxy != null) {
SubscriptionMgr.getInstance().notifySubscribers(ConsoleProxyManager.ALERT_SUBJECT, this,
new ConsoleProxyAlertEventArgs(ConsoleProxyAlertEventArgs.PROXY_CREATED, dataCenterId, proxy.getId(), proxy, null));
return proxy;
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to allocate console proxy storage, remove the console proxy record from DB, proxy id: " + proxyVmId);
}
}
return null;
}
/**
* Get the default network for the console proxy VM, based on the zone it is in. Delegates to
* either {@link #getDefaultNetworkForZone(DataCenter)} or {@link #getDefaultNetworkForAdvancedSGZone(DataCenter)},
* depending on the zone network type and whether or not security groups are enabled in the zone.
* @param dc - The zone (DataCenter) of the console proxy VM.
* @return The default network for use with the console proxy VM.
*/
protected NetworkVO getDefaultNetworkForCreation(DataCenter dc) {
if (dc.getNetworkType() == NetworkType.Advanced) {
return getDefaultNetworkForAdvancedZone(dc);
} else {
return getDefaultNetworkForBasicZone(dc);
}
}
/**
* Get default network for a console proxy VM starting up in an advanced zone. If the zone
* is security group-enabled, the first network found that supports SG services is returned.
* If the zone is not SG-enabled, the Public network is returned.
* @param dc - The zone.
* @return The selected default network.
* @throws CloudRuntimeException - If the zone is not a valid choice or a network couldn't be found.
*/
protected NetworkVO getDefaultNetworkForAdvancedZone(DataCenter dc) {
if (dc.getNetworkType() != NetworkType.Advanced) {
throw new CloudRuntimeException("Zone " + dc + " is not advanced.");
}
if (dc.isSecurityGroupEnabled()) {
List<NetworkVO> networks = _networkDao.listByZoneSecurityGroup(dc.getId());
if (CollectionUtils.isEmpty(networks)) {
throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc);
}
return networks.get(0);
}
else {
TrafficType defaultTrafficType = TrafficType.Public;
List<NetworkVO> defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType);
// api should never allow this situation to happen
if (defaultNetworks.size() != 1) {
throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1");
}
return defaultNetworks.get(0);
}
}
/**
* Get default network for console proxy VM for starting up in a basic zone. Basic zones select
* the Guest network whether or not the zone is SG-enabled.
* @param dc - The zone.
* @return The default network according to the zone's network selection rules.
* @throws CloudRuntimeException - If the zone is not a valid choice or a network couldn't be found.
*/
protected NetworkVO getDefaultNetworkForBasicZone(DataCenter dc) {
if (dc.getNetworkType() != NetworkType.Basic) {
throw new CloudRuntimeException("Zone " + dc + "is not basic.");
}
TrafficType defaultTrafficType = TrafficType.Guest;
List<NetworkVO> defaultNetworks = _networkDao.listByZoneAndTrafficType(dc.getId(), defaultTrafficType);
// api should never allow this situation to happen
if (defaultNetworks.size() != 1) {
throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1");
}
return defaultNetworks.get(0);
}
protected Map<String, Object> createProxyInstance(long dataCenterId, VMTemplateVO template) throws ConcurrentOperationException {
long id = _consoleProxyDao.getNextInSequence(Long.class, "id");
String name = VirtualMachineName.getConsoleProxyName(id, _instance);
DataCenterVO dc = _dcDao.findById(dataCenterId);
Account systemAcct = _accountMgr.getSystemAccount();
DataCenterDeployment plan = new DataCenterDeployment(dataCenterId);
NetworkVO defaultNetwork = getDefaultNetworkForCreation(dc);
List<? extends NetworkOffering> offerings =
_networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork, NetworkOffering.SystemManagementNetwork);
LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(offerings.size() + 1);
NicProfile defaultNic = new NicProfile();
defaultNic.setDefaultNic(true);
defaultNic.setDeviceId(2);
networks.put(_networkMgr.setupNetwork(systemAcct, _networkOfferingDao.findById(defaultNetwork.getNetworkOfferingId()), plan, null, null, false).get(0),
new ArrayList<NicProfile>(Arrays.asList(defaultNic)));
for (NetworkOffering offering : offerings) {
networks.put(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), new ArrayList<NicProfile>());
}
ServiceOfferingVO serviceOffering = _serviceOffering;
if (serviceOffering == null) {
serviceOffering = _offeringDao.findDefaultSystemOffering(ServiceOffering.consoleProxyDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId));
}
ConsoleProxyVO proxy =
new ConsoleProxyVO(id, serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId,
systemAcct.getDomainId(), systemAcct.getId(), _accountMgr.getSystemUser().getId(), 0, serviceOffering.isOfferHA());
proxy.setDynamicallyScalable(template.isDynamicallyScalable());
proxy = _consoleProxyDao.persist(proxy);
try {
_itMgr.allocate(name, template, serviceOffering, networks, plan, null);
} catch (InsufficientCapacityException e) {
s_logger.warn("InsufficientCapacity", e);
throw new CloudRuntimeException("Insufficient capacity exception", e);
}
Map<String, Object> context = new HashMap<String, Object>();
context.put("dc", dc);
HostPodVO pod = _podDao.findById(proxy.getPodIdToDeployIn());
context.put("pod", pod);
context.put("proxyVmId", proxy.getId());
return context;
}
private ConsoleProxyAllocator getCurrentAllocator() {
// for now, only one adapter is supported
for (ConsoleProxyAllocator allocator : _consoleProxyAllocators) {
return allocator;
}
return null;
}
public void onLoadAnswer(ConsoleProxyLoadAnswer answer) {
if (answer.getDetails() == null) {
return;
}
ConsoleProxyStatus status = null;
try {
GsonBuilder gb = new GsonBuilder();
gb.setVersion(1.3);
Gson gson = gb.create();
status = gson.fromJson(answer.getDetails(), ConsoleProxyStatus.class);
} catch (Throwable e) {
s_logger.warn("Unable to parse load info from proxy, proxy vm id : " + answer.getProxyVmId() + ", info : " + answer.getDetails());
}
if (status != null) {
int count = 0;
if (status.getConnections() != null) {
count = status.getConnections().length;
}
byte[] details = null;
if (answer.getDetails() != null) {
details = answer.getDetails().getBytes(Charset.forName("US-ASCII"));
}
_consoleProxyDao.update(answer.getProxyVmId(), count, DateUtil.currentGMTTime(), details);
} else {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Unable to get console proxy load info, id : " + answer.getProxyVmId());
}
_consoleProxyDao.update(answer.getProxyVmId(), 0, DateUtil.currentGMTTime(), null);
// TODO : something is wrong with the VM, restart it?
}
}
public void handleAgentDisconnect(long agentId, com.cloud.host.Status state) {
if (state == com.cloud.host.Status.Alert || state == com.cloud.host.Status.Disconnected) {
// be it either in alert or in disconnected state, the agent process
// may be gone in the VM,
// we will be reacting to stop the corresponding VM and let the scan
// process to
HostVO host = _hostDao.findById(agentId);
if (host.getType() == Type.ConsoleProxy) {
String name = host.getName();
if (s_logger.isInfoEnabled()) {
s_logger.info("Console proxy agent disconnected, proxy: " + name);
}
if (name != null && name.startsWith("v-")) {
String[] tokens = name.split("-");
long proxyVmId = 0;
try {
proxyVmId = Long.parseLong(tokens[1]);
} catch (NumberFormatException e) {
s_logger.error("Unexpected exception " + e.getMessage(), e);
return;
}
final ConsoleProxyVO proxy = _consoleProxyDao.findById(proxyVmId);
if (proxy != null) {
// Disable this feature for now, as it conflicts with
// the case of allowing user to reboot console proxy
// when rebooting happens, we will receive disconnect
// here and we can't enter into stopping process,
// as when the rebooted one comes up, it will kick off a
// newly started one and trigger the process
// continue on forever
/*
* _capacityScanScheduler.execute(new Runnable() { public void run() {
* if(s_logger.isInfoEnabled())
* s_logger.info("Stop console proxy " + proxy.getName() +
* " VM because of that the agent running inside it has disconnected" );
* stopProxy(proxy.getId()); } });
*/
} else {
if (s_logger.isInfoEnabled()) {
s_logger.info("Console proxy agent disconnected but corresponding console proxy VM no longer exists in DB, proxy: " + name);
}
}
} else {
assert (false) : "Invalid console proxy name: " + name;
}
}
}
}
private boolean reserveStandbyCapacity() {
ConsoleProxyManagementState state = getManagementState();
if (state == null || state != ConsoleProxyManagementState.Auto) {
return false;
}
return true;
}
private boolean isConsoleProxyVmRequired(long dcId) {
DataCenterVO dc = _dcDao.findById(dcId);
_dcDao.loadDetails(dc);
String cpvmReq = dc.getDetail(ZoneConfig.EnableConsoleProxyVm.key());
if (cpvmReq != null) {
return Boolean.parseBoolean(cpvmReq);
}
return true;
}
private boolean allowToLaunchNew(long dcId) {
if (!isConsoleProxyVmRequired(dcId)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console proxy vm not required in zone " + dcId + " not launching");
}
return false;
}
List<ConsoleProxyVO> l =
_consoleProxyDao.getProxyListInStates(dcId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping,
VirtualMachine.State.Stopped, VirtualMachine.State.Migrating, VirtualMachine.State.Shutdown, VirtualMachine.State.Unknown);
String value = _configDao.getValue(Config.ConsoleProxyLaunchMax.key());
int launchLimit = NumbersUtil.parseInt(value, 10);
return l.size() < launchLimit;
}
private boolean checkCapacity(ConsoleProxyLoadInfo proxyCountInfo, ConsoleProxyLoadInfo vmCountInfo) {
if (proxyCountInfo.getCount() * _capacityPerProxy - vmCountInfo.getCount() <= _standbyCapacity) {
return false;
}
return true;
}
private void allocCapacity(long dataCenterId) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Allocate console proxy standby capacity for data center : " + dataCenterId);
}
ConsoleProxyVO proxy = null;
String errorString = null;
try {
boolean consoleProxyVmFromStoppedPool = false;
proxy = assignProxyFromStoppedPool(dataCenterId);
if (proxy == null) {
if (s_logger.isInfoEnabled()) {
s_logger.info("No stopped console proxy is available, need to allocate a new console proxy");
}
if (_allocProxyLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC)) {
try {
proxy = startNew(dataCenterId);
} catch (ConcurrentOperationException e) {
s_logger.info("Concurrent operation exception caught " + e);
} finally {
_allocProxyLock.unlock();
}
} else {
if (s_logger.isInfoEnabled()) {
s_logger.info("Unable to acquire synchronization lock for console proxy vm allocation, wait for next scan");
}
}
} else {
if (s_logger.isInfoEnabled()) {
s_logger.info("Found a stopped console proxy, starting it. Vm id : " + proxy.getId());
}
consoleProxyVmFromStoppedPool = true;
}
if (proxy != null) {
long proxyVmId = proxy.getId();
proxy = startProxy(proxyVmId, false);
if (proxy != null) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Console proxy " + proxy.getHostName() + " is started");
}
SubscriptionMgr.getInstance().notifySubscribers(ConsoleProxyManager.ALERT_SUBJECT, this,
new ConsoleProxyAlertEventArgs(ConsoleProxyAlertEventArgs.PROXY_UP, dataCenterId, proxy.getId(), proxy, null));
} else {
if (s_logger.isInfoEnabled()) {
s_logger.info("Unable to start console proxy vm for standby capacity, vm id : " + proxyVmId + ", will recycle it and start a new one");
}
if (consoleProxyVmFromStoppedPool) {
destroyProxy(proxyVmId);
}
}
}
} catch (Exception e) {
errorString = e.getMessage();
throw e;
} finally {
// TODO - For now put all the alerts as creation failure. Distinguish between creation vs start failure in future.