forked from AnythingLinux/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurityGroupManagerImpl2.java
More file actions
307 lines (271 loc) · 12.5 KB
/
SecurityGroupManagerImpl2.java
File metadata and controls
307 lines (271 loc) · 12.5 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
// 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.network.security;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.manager.Commands;
import com.cloud.configuration.Config;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.network.security.SecurityGroupWork.Step;
import com.cloud.uservm.UserVm;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Profiler;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.mgmt.JmxUtil;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.network.security.SecurityRule.SecurityRuleType;
/**
* Same as the base class -- except it uses the abstracted security group work queue
*
*/
@Local(value={ SecurityGroupManager.class, SecurityGroupService.class })
public class SecurityGroupManagerImpl2 extends SecurityGroupManagerImpl{
SecurityGroupWorkQueue _workQueue = new LocalSecurityGroupWorkQueue();
SecurityGroupWorkTracker _workTracker;
SecurityManagerMBeanImpl _mBean;
WorkerThread[] _workers;
private Set<Long> _disabledVms = Collections.newSetFromMap(new ConcurrentHashMap<Long, Boolean>());
private boolean _schedulerDisabled = false;
protected class WorkerThread extends Thread {
public WorkerThread(String name) {
super(name);
}
@Override
public void run() {
while (true) {
try{
work();
} catch (final Throwable th) {
s_logger.error("SG Work: Caught this throwable, ", th);
}
}
}
}
@Override
protected void createThreadPools() {
_workers = new WorkerThread[_numWorkerThreads];
for (int i = 0; i < _workers.length; i++) {
_workers[i] = new WorkerThread("SecGrp-Worker-" + i);
}
}
@Override
//@DB
public void scheduleRulesetUpdateToHosts(List<Long> affectedVms, boolean updateSeqno, Long delayMs) {
if (affectedVms.size() == 0) {
return;
}
if (_schedulerDisabled) {
s_logger.debug("Security Group Mgr v2: scheduler disabled, doing nothing for " + affectedVms.size() + " vms");
return;
}
Set<Long> workItems = new TreeSet<Long>();
workItems.addAll(affectedVms);
workItems.removeAll(_disabledVms);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Security Group Mgr v2: scheduling ruleset updates for " + affectedVms.size() + " vms " + " (unique=" + workItems.size() + "), current queue size=" + _workQueue.size());
}
Profiler p = new Profiler();
p.start();
int updated = 0;
if (updateSeqno) {
updated = _rulesetLogDao.createOrUpdate(workItems);
if (updated < workItems.size()) {
throw new CloudRuntimeException("Failed to create ruleset log entries");
}
}
int newJobs = _workQueue.submitWorkForVms(workItems);
_mBean.logScheduledDetails(workItems);
p.stop();
if (s_logger.isDebugEnabled()){
s_logger.debug("Security Group Mgr v2: done scheduling ruleset updates for " + workItems.size() + " vms: num new jobs=" +
newJobs + " num rows insert or updated=" + updated + " time taken=" + p.getDuration());
}
}
@Override
public boolean start() {
for (final WorkerThread thread : _workers) {
thread.start();
}
return true;
}
@Override
public void work() {
s_logger.trace("Checking the work queue");
List<SecurityGroupWork> workItems;
try {
workItems = _workQueue.getWork(1);
for (SecurityGroupWork work: workItems) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Processing " + work.getInstanceId());
}
try {
VmRulesetLogVO rulesetLog = _rulesetLogDao.findByVmId(work.getInstanceId());
if (rulesetLog == null) {
s_logger.warn("Could not find ruleset log for vm " + work.getInstanceId());
continue;
}
work.setLogsequenceNumber(rulesetLog.getLogsequence());
sendRulesetUpdates(work);
_mBean.logUpdateDetails(work.getInstanceId(), work.getLogsequenceNumber());
}catch (Exception e) {
s_logger.error("Problem during SG work " + work, e);
work.setStep(Step.Error);
}
}
} catch (InterruptedException e1) {
s_logger.warn("SG work: caught InterruptException", e1);
}
}
public void sendRulesetUpdates(SecurityGroupWork work){
Long userVmId = work.getInstanceId();
UserVm vm = _userVMDao.findById(userVmId);
if (vm != null && vm.getState() == State.Running) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("SecurityGroupManager v2: found vm, " + userVmId + " state=" + vm.getState());
}
Map<PortAndProto, Set<String>> ingressRules = generateRulesForVM(userVmId, SecurityRuleType.IngressRule);
Map<PortAndProto, Set<String>> egressRules = generateRulesForVM(userVmId, SecurityRuleType.EgressRule);
Long agentId = vm.getHostId();
if (agentId != null) {
SecurityGroupRulesCmd cmd = generateRulesetCmd(vm.getInstanceName(), vm.getPrivateIpAddress(),
vm.getPrivateMacAddress(), vm.getId(), null,
work.getLogsequenceNumber(), ingressRules, egressRules);
cmd.setMsId(_serverId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("SecurityGroupManager v2: sending ruleset update for vm " + vm.getInstanceName() +
":ingress num rules=" + cmd.getIngressRuleSet().length + ":egress num rules=" + cmd.getEgressRuleSet().length + " num cidrs=" + cmd.getTotalNumCidrs() + " sig=" + cmd.getSignature());
}
Commands cmds = new Commands(cmd);
try {
_agentMgr.send(agentId, cmds, _answerListener);
if (s_logger.isTraceEnabled()) {
s_logger.trace("SecurityGroupManager v2: sent ruleset updates for " + vm.getInstanceName() + " curr queue size=" + _workQueue.size());
}
} catch (AgentUnavailableException e) {
s_logger.debug("Unable to send updates for vm: " + userVmId + "(agentid=" + agentId + ")");
_workTracker.handleException(agentId);
}
}
} else {
if (s_logger.isDebugEnabled()) {
if (vm != null)
s_logger.debug("No rules sent to vm " + vm + "state=" + vm.getState());
else
s_logger.debug("Could not find vm: No rules sent to vm " + userVmId );
}
}
}
@Override
public void cleanupFinishedWork() {
//TODO: over time clean up op_vm_ruleset_log table for destroyed vms
}
/*
* Same as the superclass, except that we use the ip address(es) returned from the join
* made with the nics table when retrieving the SecurityGroupVmMapVO. If a vm has a single
* nic then that nic is the default and then this query is correct. If the vm has multiple nics
* then we get all ips, including the default nic ip. This is also probably the correct behavior.
*/
@Override
protected Map<PortAndProto, Set<String>> generateRulesForVM(Long userVmId, SecurityRuleType type) {
Map<PortAndProto, Set<String>> allowed = new TreeMap<PortAndProto, Set<String>>();
List<SecurityGroupVMMapVO> groupsForVm = _securityGroupVMMapDao.listByInstanceId(userVmId);
for (SecurityGroupVMMapVO mapVO : groupsForVm) {
List<SecurityGroupRuleVO> rules = _securityGroupRuleDao.listBySecurityGroupId(mapVO.getSecurityGroupId(), type);
for (SecurityGroupRuleVO rule : rules) {
PortAndProto portAndProto = new PortAndProto(rule.getProtocol(), rule.getStartPort(), rule.getEndPort());
Set<String> cidrs = allowed.get(portAndProto);
if (cidrs == null) {
cidrs = new TreeSet<String>(new CidrComparator());
}
if (rule.getAllowedNetworkId() != null) {
List<SecurityGroupVMMapVO> allowedInstances = _securityGroupVMMapDao.listBySecurityGroup(rule.getAllowedNetworkId(), State.Running);
for (SecurityGroupVMMapVO ngmapVO : allowedInstances) {
//here, we differ from the superclass: instead of creating N more queries to the
//nics table, we use what's already there in the VO since the listBySecurityGroup already
//did a join with the nics table
String cidr = ngmapVO.getGuestIpAddress() + "/32";
cidrs.add(cidr);
}
} else if (rule.getAllowedSourceIpCidr() != null) {
cidrs.add(rule.getAllowedSourceIpCidr());
}
if (cidrs.size() > 0) {
allowed.put(portAndProto, cidrs);
}
}
}
return allowed;
}
public int getQueueSize() {
return _workQueue.size();
}
public SecurityGroupWorkQueue getWorkQueue() {
return _workQueue;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_mBean = new SecurityManagerMBeanImpl(this);
try {
JmxUtil.registerMBean("SecurityGroupManager", "SecurityGroupManagerImpl2", _mBean);
} catch (Exception e){
s_logger.error("Failed to register MBean", e);
}
boolean result = super.configure(name, params);
Map<String, String> configs = _configDao.getConfiguration("Network", params);
int bufferLength = NumbersUtil.parseInt(configs.get(Config.SecurityGroupWorkPerAgentMaxQueueSize.key()), 100);
_workTracker = new SecurityGroupWorkTracker(_agentMgr, _answerListener, bufferLength);
_answerListener.setWorkDispatcher(_workTracker);
return result;
}
public void disableSchedulerForVm(Long vmId, boolean disable) {
if (disable) {
_disabledVms.add(vmId);
} else {
_disabledVms.remove(vmId);
}
s_logger.warn("JMX operation: Scheduler state for vm " + vmId + ": new state disabled=" + disable);
}
public Long[] getDisabledVmsForScheduler() {
Long [] result = new Long[_disabledVms.size()];
return _disabledVms.toArray(result );
}
public void enableAllVmsForScheduler() {
s_logger.warn("Cleared list of disabled VMs (JMX operation?)");
_disabledVms.clear();
}
public void disableScheduler(boolean disable) {
_schedulerDisabled = disable;
s_logger.warn("JMX operation: Scheduler state changed: new state disabled=" + disable);
}
public boolean isSchedulerDisabled() {
return _schedulerDisabled;
}
public void clearWorkQueue() {
_workQueue.clear();
s_logger.warn("Cleared the work queue (possible JMX operation)");
}
}