You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ke...@apache.org on 2013/02/02 00:27:31 UTC

[31/50] [abbrv] Merge latest master into javelin

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java
index 0000000,4a2369b..617893f
mode 000000,100755..100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java
@@@ -1,0 -1,238 +1,238 @@@
+ // 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.
+ // 
+ // Automatically generated by addcopyright.py at 01/29/2013
+ package com.cloud.baremetal.networkservice;
+ 
+ import java.net.URI;
+ import java.util.ArrayList;
+ import java.util.HashMap;
+ import java.util.List;
+ import java.util.Map;
+ 
+ import javax.ejb.Local;
++import javax.inject.Inject;
+ 
+ import org.apache.log4j.Logger;
+ 
+ import com.cloud.agent.api.Answer;
+ import com.cloud.agent.api.baremetal.IpmISetBootDevCommand;
+ import com.cloud.agent.api.baremetal.IpmISetBootDevCommand.BootDev;
+ import com.cloud.baremetal.database.BaremetalPxeDao;
+ import com.cloud.baremetal.database.BaremetalPxeVO;
+ import com.cloud.baremetal.networkservice.BaremetalPxeManager.BaremetalPxeType;
+ import com.cloud.deploy.DeployDestination;
+ import com.cloud.host.Host;
+ import com.cloud.host.HostVO;
+ import com.cloud.host.dao.HostDetailsDao;
 -import com.cloud.network.NetworkVO;
+ import com.cloud.network.PhysicalNetworkServiceProvider;
 -import com.cloud.network.PhysicalNetworkVO;
+ import com.cloud.network.dao.NetworkDao;
++import com.cloud.network.dao.NetworkVO;
+ import com.cloud.network.dao.PhysicalNetworkDao;
+ import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
+ import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
++import com.cloud.network.dao.PhysicalNetworkVO;
+ import com.cloud.resource.ResourceManager;
+ import com.cloud.resource.ServerResource;
+ import com.cloud.storage.VMTemplateVO;
+ import com.cloud.storage.dao.VMTemplateDao;
+ import com.cloud.uservm.UserVm;
 -import com.cloud.utils.component.Inject;
+ import com.cloud.utils.db.DB;
+ import com.cloud.utils.db.SearchCriteria.Op;
+ import com.cloud.utils.db.SearchCriteria2;
+ import com.cloud.utils.db.SearchCriteriaService;
+ import com.cloud.utils.db.Transaction;
+ import com.cloud.utils.exception.CloudRuntimeException;
+ import com.cloud.vm.NicProfile;
+ import com.cloud.vm.ReservationContext;
+ import com.cloud.vm.UserVmVO;
+ import com.cloud.vm.VirtualMachineProfile;
+ 
+ @Local(value = BaremetalPxeService.class)
+ public class BaremetalKickStartServiceImpl extends BareMetalPxeServiceBase implements BaremetalPxeService {
+     private static final Logger s_logger = Logger.getLogger(BaremetalKickStartServiceImpl.class);
+     @Inject
+     ResourceManager _resourceMgr;
+     @Inject
+     PhysicalNetworkDao _physicalNetworkDao;
+     @Inject
+     PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao;
+     @Inject
+     HostDetailsDao _hostDetailsDao;
+     @Inject
+     BaremetalPxeDao _pxeDao;
+     @Inject
+     NetworkDao _nwDao;
+     @Inject
+     VMTemplateDao _tmpDao;
+ 
+     @Override
+     public boolean prepare(VirtualMachineProfile<UserVmVO> profile, NicProfile nic, DeployDestination dest, ReservationContext context) {
+         NetworkVO nwVO = _nwDao.findById(nic.getNetworkId());
+         SearchCriteriaService<BaremetalPxeVO, BaremetalPxeVO> sc = SearchCriteria2.create(BaremetalPxeVO.class);
+         sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, BaremetalPxeType.KICK_START.toString());
+         sc.addAnd(sc.getEntity().getPhysicalNetworkId(), Op.EQ, nwVO.getPhysicalNetworkId());
+         BaremetalPxeVO pxeVo = sc.find();
+         if (pxeVo == null) {
+             throw new CloudRuntimeException("No kickstart PXE server found in pod: " + dest.getPod().getId() + ", you need to add it before starting VM");
+         }
+         VMTemplateVO template = _tmpDao.findById(profile.getTemplateId());
+ 
+         try {
+             String tpl = profile.getTemplate().getUrl();
+             assert tpl != null : "How can a null template get here!!!";
+             String[] tpls = tpl.split(";");
+             assert tpls.length == 2 : "Template is not correctly encoded. " + tpl;
+             PrepareKickstartPxeServerCommand cmd = new PrepareKickstartPxeServerCommand();
+             cmd.setKsFile(tpls[0]);
+             cmd.setRepo(tpls[1]);
+             cmd.setMac(nic.getMacAddress());
+             cmd.setTemplateUuid(template.getUuid());
+             Answer aws = _agentMgr.send(pxeVo.getHostId(), cmd);
+             if (!aws.getResult()) {
+                 s_logger.warn("Unable to set host: " + dest.getHost().getId() + " to PXE boot because " + aws.getDetails());
+                 return aws.getResult();
+             }
+             
+             IpmISetBootDevCommand bootCmd = new IpmISetBootDevCommand(BootDev.pxe);
+             aws = _agentMgr.send(dest.getHost().getId(), bootCmd);
+             if (!aws.getResult()) {
+                 s_logger.warn("Unable to set host: " + dest.getHost().getId() + " to PXE boot because " + aws.getDetails());
+             }
+             
+             return aws.getResult();
+         } catch (Exception e) {
+             s_logger.warn("Cannot prepare PXE server", e);
+             return false;
+         }
+     }
+ 
+     @Override
+     public boolean prepareCreateTemplate(Long pxeServerId, UserVm vm, String templateUrl) {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     @DB
+     public BaremetalPxeVO addPxeServer(AddBaremetalPxeCmd cmd) {
+         AddBaremetalKickStartPxeCmd kcmd = (AddBaremetalKickStartPxeCmd)cmd;
+         PhysicalNetworkVO pNetwork = null;
+         long zoneId;
+         
+         if (cmd.getPhysicalNetworkId() == null || cmd.getUrl() == null || cmd.getUsername() == null || cmd.getPassword() == null) {
+             throw new IllegalArgumentException("At least one of the required parameters(physical network id, url, username, password) is null");
+         } 
+         
+         pNetwork = _physicalNetworkDao.findById(cmd.getPhysicalNetworkId());
+         if (pNetwork == null) {
+             throw new IllegalArgumentException("Could not find phyical network with ID: " + cmd.getPhysicalNetworkId());
+         }
+         zoneId = pNetwork.getDataCenterId();
+         
+         PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), BaremetalPxeManager.BAREMETAL_PXE_SERVICE_PROVIDER.getName());
+         if (ntwkSvcProvider == null) {
+             throw new CloudRuntimeException("Network Service Provider: " + BaremetalPxeManager.BAREMETAL_PXE_SERVICE_PROVIDER.getName() +
+                     " is not enabled in the physical network: " + cmd.getPhysicalNetworkId() + "to add this device");
+         } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
+             throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() +
+                     " is in shutdown state in the physical network: " + cmd.getPhysicalNetworkId() + "to add this device");
+         }
+         
+         List<HostVO> pxes = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.BaremetalPxe, zoneId);
+         if (!pxes.isEmpty()) {
+             throw new IllegalArgumentException("Already had a PXE server zone: " + zoneId);
+         }
+         
+         String tftpDir = kcmd.getTftpDir();
+         if (tftpDir == null) {
+             throw new IllegalArgumentException("No TFTP directory specified");
+         }
+         
+         URI uri;
+         try {
+             uri = new URI(cmd.getUrl());
+         } catch (Exception e) {
+             s_logger.debug(e);
+             throw new IllegalArgumentException(e.getMessage());
+         }
+         String ipAddress = uri.getHost();
+         
+         String guid = getPxeServerGuid(Long.toString(zoneId), BaremetalPxeType.KICK_START.toString(), ipAddress);
+         
+         ServerResource resource = null;
+         Map params = new HashMap<String, String>();
+         params.put(BaremetalPxeService.PXE_PARAM_ZONE, Long.toString(zoneId));
+         params.put(BaremetalPxeService.PXE_PARAM_IP, ipAddress);
+         params.put(BaremetalPxeService.PXE_PARAM_USERNAME, cmd.getUsername());
+         params.put(BaremetalPxeService.PXE_PARAM_PASSWORD, cmd.getPassword());
+         params.put(BaremetalPxeService.PXE_PARAM_TFTP_DIR, tftpDir);
+         params.put(BaremetalPxeService.PXE_PARAM_GUID, guid);
+         resource = new BaremetalKickStartPxeResource();
+         try {
+             resource.configure("KickStart PXE resource", params);
+         } catch (Exception e) {
+             throw new CloudRuntimeException(e.getMessage(), e);
+         }
+         
+         Host pxeServer = _resourceMgr.addHost(zoneId, resource, Host.Type.BaremetalPxe, params);
+         if (pxeServer == null) {
+             throw new CloudRuntimeException("Cannot add PXE server as a host");
+         }
+         
+         BaremetalPxeVO vo = new BaremetalPxeVO();
+         Transaction txn = Transaction.currentTxn();
+         vo.setHostId(pxeServer.getId());
+         vo.setNetworkServiceProviderId(ntwkSvcProvider.getId());
+         vo.setPhysicalNetworkId(kcmd.getPhysicalNetworkId());
+         vo.setDeviceType(BaremetalPxeType.KICK_START.toString());
+         txn.start();
+         _pxeDao.persist(vo);
+         txn.commit();
+         return vo;
+     }
+ 
+     @Override
+     public BaremetalPxeResponse getApiResponse(BaremetalPxeVO vo) {
+         BaremetalPxeKickStartResponse response = new BaremetalPxeKickStartResponse();
+         response.setId(String.valueOf(vo.getId()));
+         response.setPhysicalNetworkId(String.valueOf(vo.getPhysicalNetworkId()));
+         response.setPodId(String.valueOf(vo.getPodId()));
+         Map<String, String> details = _hostDetailsDao.findDetails(vo.getHostId());
+         response.setTftpDir(details.get(BaremetalPxeService.PXE_PARAM_TFTP_DIR));
+         return response;
+     }
+ 
+     @Override
+     public List<BaremetalPxeResponse> listPxeServers(ListBaremetalPxePingServersCmd cmd) {
+         SearchCriteriaService<BaremetalPxeVO, BaremetalPxeVO> sc = SearchCriteria2.create(BaremetalPxeVO.class);
+         sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, BaremetalPxeType.KICK_START.toString());
+         if (cmd.getPodId() != null) {
+             sc.addAnd(sc.getEntity().getPodId(), Op.EQ, cmd.getPodId());
+             if (cmd.getId() != null) {
+                 sc.addAnd(sc.getEntity().getId(), Op.EQ, cmd.getId());
+             }
+         }
+         List<BaremetalPxeVO> vos = sc.list();
+         List<BaremetalPxeResponse> responses = new ArrayList<BaremetalPxeResponse>(vos.size());
+         for (BaremetalPxeVO vo : vos) {
+             responses.add(getApiResponse(vo));
+         }
+         return responses;
+     }
+ 
+ }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java
index 0000000,99b9c43..bc4bcd3
mode 000000,100755..100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java
@@@ -1,0 -1,178 +1,178 @@@
+ // 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.
+ // 
+ // Automatically generated by addcopyright.py at 01/29/2013
+ package com.cloud.baremetal.networkservice;
+ 
+ import java.util.HashMap;
+ import java.util.Map;
+ import java.util.Set;
+ 
+ import javax.ejb.Local;
++import javax.inject.Inject;
+ 
+ import org.apache.log4j.Logger;
+ 
+ import com.cloud.baremetal.database.BaremetalPxeVO;
+ import com.cloud.dc.DataCenter.NetworkType;
+ import com.cloud.dc.Pod;
+ import com.cloud.deploy.DeployDestination;
+ import com.cloud.exception.ConcurrentOperationException;
+ import com.cloud.exception.InsufficientCapacityException;
+ import com.cloud.exception.ResourceUnavailableException;
+ import com.cloud.hypervisor.Hypervisor.HypervisorType;
+ import com.cloud.network.Network;
+ import com.cloud.network.Network.Capability;
+ import com.cloud.network.Network.GuestType;
+ import com.cloud.network.Network.Provider;
+ import com.cloud.network.Network.Service;
+ import com.cloud.network.Networks.TrafficType;
+ import com.cloud.network.PhysicalNetworkServiceProvider;
+ import com.cloud.network.element.NetworkElement;
+ import com.cloud.offering.NetworkOffering;
+ import com.cloud.utils.component.AdapterBase;
 -import com.cloud.utils.component.Inject;
+ import com.cloud.utils.db.DB;
+ import com.cloud.utils.db.SearchCriteria.Op;
+ import com.cloud.utils.db.SearchCriteria2;
+ import com.cloud.utils.db.SearchCriteriaService;
+ import com.cloud.utils.db.Transaction;
+ import com.cloud.utils.exception.CloudRuntimeException;
+ import com.cloud.vm.NicProfile;
+ import com.cloud.vm.NicVO;
+ import com.cloud.vm.ReservationContext;
+ import com.cloud.vm.VMInstanceVO;
+ import com.cloud.vm.VirtualMachine;
+ import com.cloud.vm.VirtualMachine.Type;
+ import com.cloud.vm.VirtualMachineProfile;
+ import com.cloud.vm.dao.NicDao;
+ import com.cloud.vm.dao.VMInstanceDao;
+ 
+ @Local(value = NetworkElement.class)
+ public class BaremetalPxeElement extends AdapterBase implements NetworkElement {
+     private static final Logger s_logger = Logger.getLogger(BaremetalPxeElement.class);
+     private static final Map<Service, Map<Capability, String>> capabilities;
+     
+     @Inject BaremetalPxeManager _pxeMgr;;
+     @Inject VMInstanceDao _vmDao;
+     @Inject NicDao _nicDao;
+     
+     static {
+         Capability cap = new Capability(BaremetalPxeManager.BAREMETAL_PXE_CAPABILITY);
+         Map<Capability, String> baremetalCaps = new HashMap<Capability, String>();
+         baremetalCaps.put(cap, null);
+         capabilities = new HashMap<Service, Map<Capability, String>>();
+         capabilities.put(BaremetalPxeManager.BAREMETAL_PXE_SERVICE, baremetalCaps);
+     }
+     
+     @Override
+     public Map<Service, Map<Capability, String>> getCapabilities() {
+         return capabilities;
+     }
+ 
+     @Override
+     public Provider getProvider() {
+     	return BaremetalPxeManager.BAREMETAL_PXE_SERVICE_PROVIDER;
+     }
+ 
+     private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) {
+         Pod pod = dest.getPod();
+         if (pod != null && dest.getDataCenter().getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest) {
+             SearchCriteriaService<BaremetalPxeVO, BaremetalPxeVO> sc = SearchCriteria2.create(BaremetalPxeVO.class);
+             sc.addAnd(sc.getEntity().getPodId(), Op.EQ, pod.getId());
+             return sc.find() != null;
+         }
+         
+         return false;
+     }
+     
+     @Override
+     public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context)
+             throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+         if (offering.isSystemOnly() || !canHandle(dest, offering.getTrafficType(), network.getGuestType())) {
+             s_logger.debug("BaremetalPxeElement can not handle network offering: " + offering.getName());
+             return false;
+         }
+         return true;
+     }
+ 
+     @Override
+     @DB
+     public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest,
+             ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+         if (vm.getType() != Type.User || vm.getHypervisorType() != HypervisorType.BareMetal) {
+             return false;
+         }
+         
+         VMInstanceVO vo = _vmDao.findById(vm.getId());
+         if (vo.getLastHostId() == null) {
+             Transaction txn = Transaction.currentTxn();
+             txn.start();
+             nic.setMacAddress(dest.getHost().getPrivateMacAddress());
+             NicVO nicVo = _nicDao.findById(nic.getId());
+             assert vo != null : "Where ths nic " + nic.getId() + " going???";
+             nicVo.setMacAddress(nic.getMacAddress());
+             _nicDao.update(nicVo.getId(), nicVo);
+             txn.commit();
+             
+         	/*This vm is just being created */
+         	if (!_pxeMgr.prepare(vm, nic, dest, context)) {
+         	    throw new CloudRuntimeException("Cannot prepare pxe server");
+         	}
+         }
+         
+         return false;
+     }
+ 
+     @Override
+     public boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context)
+             throws ConcurrentOperationException, ResourceUnavailableException {
+         return true;
+     }
+ 
+     @Override
+     public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
+         return true;
+     }
+ 
+     @Override
+     public boolean isReady(PhysicalNetworkServiceProvider provider) {
+         return true;
+     }
+ 
+     @Override
+     public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
+             ResourceUnavailableException {
+         return true;
+     }
+ 
+     @Override
+     public boolean canEnableIndividualServices() {
+         return false;
+     }
+ 
+     @Override
+     public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public boolean verifyServicesCombination(Set<Service> services) {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java
index 0000000,94010ec..6e3963d
mode 000000,100755..100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java
@@@ -1,0 -1,242 +1,242 @@@
+ // 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.
+ // 
+ // Automatically generated by addcopyright.py at 01/29/2013
+ // Apache License, Version 2.0 (the "License"); you may not use this
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ // 
+ // Automatically generated by addcopyright.py at 04/03/2012
+ package com.cloud.baremetal.networkservice;
+ 
+ 
+ import java.util.List;
+ import java.util.Map;
+ 
+ import javax.ejb.Local;
++import javax.inject.Inject;
+ import javax.naming.ConfigurationException;
+ 
+ import org.apache.log4j.Logger;
+ 
+ import com.cloud.agent.AgentManager;
+ import com.cloud.agent.api.Answer;
+ import com.cloud.agent.api.StartupCommand;
+ import com.cloud.agent.api.StartupPxeServerCommand;
+ import com.cloud.agent.api.routing.VmDataCommand;
+ import com.cloud.baremetal.database.BaremetalPxeVO;
+ import com.cloud.configuration.dao.ConfigurationDao;
+ import com.cloud.dc.dao.DataCenterDao;
+ import com.cloud.deploy.DeployDestination;
+ import com.cloud.host.Host;
+ import com.cloud.host.HostVO;
+ import com.cloud.host.dao.HostDao;
 -import com.cloud.network.PhysicalNetworkVO;
+ import com.cloud.network.dao.PhysicalNetworkDao;
++import com.cloud.network.dao.PhysicalNetworkVO;
+ import com.cloud.resource.ResourceManager;
+ import com.cloud.resource.ResourceStateAdapter;
+ import com.cloud.resource.ServerResource;
+ import com.cloud.resource.UnableDeleteHostException;
+ import com.cloud.service.dao.ServiceOfferingDao;
+ import com.cloud.uservm.UserVm;
+ import com.cloud.utils.StringUtils;
 -import com.cloud.utils.component.Adapters;
 -import com.cloud.utils.component.Inject;
++import com.cloud.utils.component.AdapterBase;
++import com.cloud.utils.component.ManagerBase;
+ import com.cloud.utils.db.SearchCriteria.Op;
+ import com.cloud.utils.db.SearchCriteria2;
+ import com.cloud.utils.db.SearchCriteriaService;
+ import com.cloud.utils.exception.CloudRuntimeException;
+ import com.cloud.vm.NicProfile;
+ import com.cloud.vm.NicVO;
+ import com.cloud.vm.ReservationContext;
+ import com.cloud.vm.UserVmVO;
+ import com.cloud.vm.VirtualMachineProfile;
+ import com.cloud.vm.dao.NicDao;
+ import com.cloud.vm.dao.UserVmDao;
+ 
+ @Local(value = {BaremetalPxeManager.class})
 -public class BaremetalPxeManagerImpl implements BaremetalPxeManager, ResourceStateAdapter {
++public class BaremetalPxeManagerImpl extends ManagerBase implements BaremetalPxeManager, ResourceStateAdapter {
+ 	private static final org.apache.log4j.Logger s_logger = Logger.getLogger(BaremetalPxeManagerImpl.class);
+ 	protected String _name;
+ 	@Inject DataCenterDao _dcDao;
+ 	@Inject HostDao _hostDao;
+ 	@Inject AgentManager _agentMgr;
+ 	@Inject ResourceManager _resourceMgr;
 -	@Inject(adapter=BaremetalPxeService.class)
 -	protected Adapters<BaremetalPxeService> _services;
++	@Inject List<BaremetalPxeService> _services;
+ 	@Inject UserVmDao _vmDao;
+ 	@Inject ServiceOfferingDao _serviceOfferingDao;
+ 	@Inject NicDao _nicDao;
+ 	@Inject ConfigurationDao _configDao;
+ 	@Inject PhysicalNetworkDao _phynwDao;
+ 	
+ 	@Override
+ 	public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
+ 		_name = name;
+ 		_resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
+ 		return true;
+ 	}
+ 
+ 	@Override
+ 	public boolean start() {
+ 		return true;
+ 	}
+ 
+ 	@Override
+ 	public boolean stop() {
+     	_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
+ 		return true;
+ 	}
+ 
+ 	@Override
+ 	public String getName() {
+ 		return _name;
+ 	}
+ 
+ 	protected BaremetalPxeService getServiceByType(String type) {
+ 		BaremetalPxeService _service;
 -		_service = _services.get(type);
++		_service = AdapterBase.getAdapterByName(_services, type);
+ 		if (_service == null) {
+ 			throw new CloudRuntimeException("Cannot find PXE service for " + type);
+ 		}
+ 		return _service;
+ 	}
+ 	
+ 	@Override
+ 	public boolean prepare(VirtualMachineProfile profile, NicProfile nic, DeployDestination dest, ReservationContext context) {
+ 	    //TODO: select type from template
+ 	    BaremetalPxeType type = BaremetalPxeType.KICK_START;
+ 		return getServiceByType(type.toString()).prepare(profile, nic, dest, context);
+ 	}
+ 
+     @Override
+     public boolean prepareCreateTemplate(Long pxeServerId, UserVm vm, String templateUrl) {
+ 	    //TODO: select type from template
+ 	    BaremetalPxeType type = BaremetalPxeType.PING;
+         return getServiceByType(type.toString()).prepareCreateTemplate(pxeServerId, vm, templateUrl);
+     }
+     
+     @Override
+     public BaremetalPxeType getPxeServerType(HostVO host) {
+         if (host.getResource().equalsIgnoreCase(BaremetalPingPxeResource.class.getName())) {
+             return BaremetalPxeType.PING;
+         } else {
+             throw new CloudRuntimeException("Unkown PXE server resource " + host.getResource());
+         }
+     }
+ 
+ 	@Override
+     public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
+ 	    // TODO Auto-generated method stub
+ 	    return null;
+     }
+ 
+ 	@Override
+     public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map<String, String> details,
+             List<String> hostTags) {
+         if (!(startup[0] instanceof StartupPxeServerCommand)) {
+             return null;
+         }
+         
+         host.setType(Host.Type.BaremetalPxe);
+         return host;
+     }
+ 
+ 	@Override
+     public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
+ 	    // TODO Auto-generated method stub
+ 	    return null;
+     }
+ 
+     @Override
+     public BaremetalPxeVO addPxeServer(AddBaremetalPxeCmd cmd) {
+         return getServiceByType(cmd.getDeviceType()).addPxeServer(cmd);
+     }
+ 
+     @Override
+     public BaremetalPxeResponse getApiResponse(BaremetalPxeVO vo) {
+         return getServiceByType(vo.getDeviceType()).getApiResponse(vo);
+     }
+ 
+     @Override
+     public List<BaremetalPxeResponse> listPxeServers(ListBaremetalPxePingServersCmd cmd) {
+         return getServiceByType(BaremetalPxeManager.BaremetalPxeType.PING.toString()).listPxeServers(cmd);
+     }
+ 
+     @Override
+     public boolean addUserData(NicProfile nic, VirtualMachineProfile<UserVm> profile) {
+         UserVmVO vm = (UserVmVO) profile.getVirtualMachine();
+         _vmDao.loadDetails(vm);
+         
+         String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getServiceOfferingId()).getDisplayText();
 -        String zoneName = _dcDao.findById(vm.getDataCenterIdToDeployIn()).getName();
++        String zoneName = _dcDao.findById(vm.getDataCenterId()).getName();
+         NicVO nvo = _nicDao.findById(nic.getId());
+         VmDataCommand cmd = new VmDataCommand(nvo.getIp4Address(), vm.getInstanceName());
+         cmd.addVmData("userdata", "user-data", vm.getUserData());
+         cmd.addVmData("metadata", "service-offering", StringUtils.unicodeEscape(serviceOffering));
+         cmd.addVmData("metadata", "availability-zone", StringUtils.unicodeEscape(zoneName));
+         cmd.addVmData("metadata", "local-ipv4", nic.getIp4Address());
+         cmd.addVmData("metadata", "local-hostname", StringUtils.unicodeEscape(vm.getInstanceName()));
+         cmd.addVmData("metadata", "public-ipv4", nic.getIp4Address());
+         cmd.addVmData("metadata", "public-hostname",  StringUtils.unicodeEscape(vm.getInstanceName()));
+         cmd.addVmData("metadata", "instance-id", String.valueOf(vm.getId()));
+         cmd.addVmData("metadata", "vm-id", String.valueOf(vm.getInstanceName()));
+         cmd.addVmData("metadata", "public-keys", null);
+         String cloudIdentifier = _configDao.getValue("cloud.identifier");
+         if (cloudIdentifier == null) {
+             cloudIdentifier = "";
+         } else {
+             cloudIdentifier = "CloudStack-{" + cloudIdentifier + "}";
+         }
+         cmd.addVmData("metadata", "cloud-identifier", cloudIdentifier);
+         
 -        List<PhysicalNetworkVO> phys = _phynwDao.listByZone(vm.getDataCenterIdToDeployIn());
++        List<PhysicalNetworkVO> phys = _phynwDao.listByZone(vm.getDataCenterId());
+         if (phys.isEmpty()) {
 -            throw new CloudRuntimeException(String.format("Cannot find physical network in zone %s", vm.getDataCenterIdToDeployIn()));
++            throw new CloudRuntimeException(String.format("Cannot find physical network in zone %s", vm.getDataCenterId()));
+         }
+         if (phys.size() > 1) {
 -            throw new CloudRuntimeException(String.format("Baremetal only supports one physical network in zone, but zone %s has %s physical networks", vm.getDataCenterIdToDeployIn(), phys.size()));
++            throw new CloudRuntimeException(String.format("Baremetal only supports one physical network in zone, but zone %s has %s physical networks", vm.getDataCenterId(), phys.size()));
+         }
+         PhysicalNetworkVO phy = phys.get(0);
+         
+         SearchCriteriaService<BaremetalPxeVO, BaremetalPxeVO> sc = SearchCriteria2.create(BaremetalPxeVO.class);
+         //TODO: handle both kickstart and PING
+         //sc.addAnd(sc.getEntity().getPodId(), Op.EQ, vm.getPodIdToDeployIn());
+         sc.addAnd(sc.getEntity().getPhysicalNetworkId(), Op.EQ, phy.getId());
+         BaremetalPxeVO pxeVo = sc.find();
+         if (pxeVo == null) {
+             throw new CloudRuntimeException("No PXE server found in pod: " + vm.getPodIdToDeployIn() + ", you need to add it before starting VM");
+         }
+         
+         try {
+             Answer ans = _agentMgr.send(pxeVo.getHostId(), cmd);
+             if (!ans.getResult()) {
+                 s_logger.debug(String.format("Add userdata to vm:%s failed because %s", vm.getInstanceName(), ans.getDetails()));
+                 return false;
+             } else {
+                 return true;
+             }
+         } catch (Exception e) {
+             s_logger.debug(String.format("Add userdata to vm:%s failed", vm.getInstanceName()), e);
+             return false;
+         }
+     }
+ 
+ 	@Override
+ 	public List<Class<?>> getCommands() {
+ 		// TODO Auto-generated method stub
+ 		return null;
+ 	}
+ }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeResourceBase.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeResourceBase.java
index 0000000,34175c8..a90a789
mode 000000,100755..100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeResourceBase.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeResourceBase.java
@@@ -1,0 -1,157 +1,158 @@@
+ // 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.
+ // 
+ // Automatically generated by addcopyright.py at 01/29/2013
+ // Apache License, Version 2.0 (the "License"); you may not use this
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ // 
+ // Automatically generated by addcopyright.py at 04/03/2012
+ package com.cloud.baremetal.networkservice;
+ 
+ import java.util.Map;
+ 
+ import javax.naming.ConfigurationException;
+ 
+ import org.apache.log4j.Logger;
+ 
+ import com.cloud.agent.IAgentControl;
+ import com.cloud.agent.api.Answer;
+ import com.cloud.agent.api.Command;
+ import com.cloud.agent.api.PingCommand;
+ import com.cloud.agent.api.ReadyAnswer;
+ import com.cloud.agent.api.ReadyCommand;
+ import com.cloud.agent.api.StartupCommand;
+ import com.cloud.agent.api.StartupPxeServerCommand;
+ import com.cloud.host.Host.Type;
+ import com.cloud.resource.ServerResource;
++import com.cloud.utils.component.ManagerBase;
+ 
 -public class BaremetalPxeResourceBase implements ServerResource {
++public class BaremetalPxeResourceBase extends ManagerBase implements ServerResource {
+ 	private static final Logger s_logger = Logger.getLogger(BaremetalPxeResourceBase.class);
+ 	String _name;
+ 	String _guid;
+ 	String _username;
+ 	String _password;
+ 	String _ip;
+ 	String _zoneId;
+ 	String _podId;
+ 	
+ 	@Override
+ 	public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
+ 		_name = name;
+ 		_guid = (String)params.get(BaremetalPxeService.PXE_PARAM_GUID);
+ 		_ip = (String)params.get(BaremetalPxeService.PXE_PARAM_IP);
+ 		_username = (String)params.get(BaremetalPxeService.PXE_PARAM_USERNAME);
+ 		_password = (String)params.get(BaremetalPxeService.PXE_PARAM_PASSWORD);
+ 		_zoneId = (String)params.get(BaremetalPxeService.PXE_PARAM_ZONE);
+ 		_podId = (String)params.get(BaremetalPxeService.PXE_PARAM_POD);
+ 
+ 		if (_guid == null) {
+ 			throw new ConfigurationException("No Guid specified");
+ 		}
+ 		
+ 		if (_zoneId == null) {
+ 			throw new ConfigurationException("No Zone specified");
+ 		}
+ 		
+ 		if (_ip == null) {
+ 			throw new ConfigurationException("No IP specified");
+ 		}
+ 		
+ 		if (_username == null) {
+ 			throw new ConfigurationException("No username specified");
+ 		}
+ 		
+ 		if (_password == null) {
+ 			throw new ConfigurationException("No password specified");
+ 		}
+ 		
+ 		return true;
+ 	}
+ 	
+ 	protected ReadyAnswer execute(ReadyCommand cmd) {
+ 		s_logger.debug("Pxe resource " + _name + " is ready");
+ 		return new ReadyAnswer(cmd);
+ 	}
+ 
+ 	@Override
+ 	public boolean start() {
+ 		return true;
+ 	}
+ 
+ 	@Override
+ 	public boolean stop() {
+ 		return true;
+ 	}
+ 
+ 	@Override
+ 	public String getName() {
+ 		// TODO Auto-generated method stub
+ 		return _name;
+ 	}
+ 
+ 	@Override
+ 	public Type getType() {
+ 		return Type.BaremetalPxe;
+ 	}
+ 
+ 	@Override
+ 	public StartupCommand[] initialize() {
+ 		StartupPxeServerCommand cmd = new StartupPxeServerCommand();
+ 		cmd.setName(_name);
+ 		cmd.setDataCenter(_zoneId);
+ 		cmd.setPod(_podId);
+ 		cmd.setPrivateIpAddress(_ip);
+ 		cmd.setStorageIpAddress("");
+ 		cmd.setVersion("");
+ 		cmd.setGuid(_guid);
+ 		return new StartupCommand[]{cmd};
+ 	}
+ 
+ 	@Override
+ 	public PingCommand getCurrentStatus(long id) {
+ 		// TODO Auto-generated method stub
+ 		return null;
+ 	}
+ 
+ 	@Override
+ 	public void disconnected() {
+ 		// TODO Auto-generated method stub
+ 
+ 	}
+ 
+ 	@Override
+ 	public IAgentControl getAgentControl() {
+ 		// TODO Auto-generated method stub
+ 		return null;
+ 	}
+ 
+ 	@Override
+ 	public void setAgentControl(IAgentControl agentControl) {
+ 		// TODO Auto-generated method stub
+ 
+ 	}
+ 	
+ 	@Override
+ 	public Answer executeRequest(Command cmd) {
+ 		if (cmd instanceof ReadyCommand) {
+ 			return execute((ReadyCommand) cmd);
+ 		} else {
+ 			return Answer.createUnsupportedCommandAnswer(cmd);
+ 		}
+ 	}
+ 
+ }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java
index 0000000,b5fd6f6..ae58254
mode 000000,100755..100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalUserdataElement.java
@@@ -1,0 -1,175 +1,175 @@@
+ // 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.
+ // 
+ // Automatically generated by addcopyright.py at 01/29/2013
+ package com.cloud.baremetal.networkservice;
+ 
+ import java.util.HashMap;
+ 
+ import java.util.List;
+ import java.util.Map;
+ import java.util.Set;
+ 
+ import javax.ejb.Local;
++import javax.inject.Inject;
+ 
+ import com.cloud.baremetal.manager.BaremetalManager;
+ import com.cloud.dc.DataCenter.NetworkType;
+ import com.cloud.deploy.DeployDestination;
+ import com.cloud.exception.ConcurrentOperationException;
+ import com.cloud.exception.InsufficientCapacityException;
+ import com.cloud.exception.ResourceUnavailableException;
+ import com.cloud.hypervisor.Hypervisor.HypervisorType;
+ import com.cloud.network.Network;
+ import com.cloud.network.Network.Capability;
+ import com.cloud.network.Network.GuestType;
+ import com.cloud.network.Network.Provider;
+ import com.cloud.network.Network.Service;
+ import com.cloud.network.Networks.TrafficType;
+ import com.cloud.network.PhysicalNetworkServiceProvider;
+ import com.cloud.network.element.IpDeployer;
+ import com.cloud.network.element.NetworkElement;
+ import com.cloud.network.element.UserDataServiceProvider;
+ import com.cloud.offering.NetworkOffering;
+ import com.cloud.uservm.UserVm;
+ import com.cloud.utils.component.AdapterBase;
 -import com.cloud.utils.component.Inject;
+ import com.cloud.vm.NicProfile;
+ import com.cloud.vm.ReservationContext;
+ import com.cloud.vm.VirtualMachine;
+ import com.cloud.vm.VirtualMachineProfile;
+ 
+ @Local(value = NetworkElement.class)
+ public class BaremetalUserdataElement extends AdapterBase implements NetworkElement, UserDataServiceProvider {
+     private static Map<Service, Map<Capability, String>> capabilities;
+     
+     @Inject
+     private BaremetalPxeManager pxeMgr;
+     
+     static {
+         capabilities = new HashMap<Service, Map<Capability, String>>();
+         capabilities.put(Service.UserData, null);
+     }
+     
+     private boolean canHandle(DeployDestination dest)  {
+         if (dest.getDataCenter().getNetworkType() == NetworkType.Basic && dest.getHost().getHypervisorType() == HypervisorType.BareMetal) {
+             return true;
+         }
+         return false;
+     }
+     
+     @Override
+     public boolean addPasswordAndUserdata(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest,
+             ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
+         if (!canHandle(dest)) {
+             return false;
+         }
+         
+         if (vm.getType() != VirtualMachine.Type.User) {
+             return false;
+         }
+         
+         return pxeMgr.addUserData(nic, (VirtualMachineProfile<UserVm>) vm);
+     }
+ 
+     @Override
+     public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm) throws ResourceUnavailableException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public boolean saveSSHKey(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, String SSHPublicKey) throws ResourceUnavailableException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public Map<Service, Map<Capability, String>> getCapabilities() {
+         return capabilities;
+     }
+ 
+     @Override
+     public Provider getProvider() {
+         return BaremetalPxeManager.BAREMETAL_USERDATA_PROVIDER;
+     }
+ 
+     @Override
+     public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context)
+             throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest,
+             ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public boolean release(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, ReservationContext context)
+             throws ConcurrentOperationException, ResourceUnavailableException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public boolean isReady(PhysicalNetworkServiceProvider provider) {
+         return true;
+     }
+ 
+     @Override
+     public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
+             ResourceUnavailableException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public boolean canEnableIndividualServices() {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+ 
+     @Override
+     public boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm)
+             throws ResourceUnavailableException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+     @Override
+     public boolean verifyServicesCombination(Set<Service> services) {
+         // TODO Auto-generated method stub
+         return false;
+     }
+ 
+ }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/ListBaremetalDhcpCmd.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/ListBaremetalDhcpCmd.java
index 0000000,ba5128b..14b7433
mode 000000,100755..100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/ListBaremetalDhcpCmd.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/ListBaremetalDhcpCmd.java
@@@ -1,0 -1,102 +1,103 @@@
+ // 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.
+ // 
+ // Automatically generated by addcopyright.py at 01/29/2013
+ package com.cloud.baremetal.networkservice;
+ 
+ import java.util.List;
+ 
++import javax.inject.Inject;
++
+ import org.apache.cloudstack.api.ApiConstants;
+ import org.apache.cloudstack.api.ApiErrorCode;
+ import org.apache.cloudstack.api.BaseCmd;
+ import org.apache.cloudstack.api.BaseCmd.CommandType;
+ import org.apache.cloudstack.api.BaseListCmd;
+ import org.apache.cloudstack.api.Parameter;
 -import org.apache.cloudstack.api.PlugService;
+ import org.apache.cloudstack.api.ServerApiException;
+ import org.apache.cloudstack.api.response.ListResponse;
+ import org.apache.log4j.Logger;
+ 
+ import com.cloud.exception.ConcurrentOperationException;
+ import com.cloud.exception.InsufficientCapacityException;
+ import com.cloud.exception.NetworkRuleConflictException;
+ import com.cloud.exception.ResourceAllocationException;
+ import com.cloud.exception.ResourceUnavailableException;
+ 
+ public class ListBaremetalDhcpCmd extends BaseListCmd {
+     private static final Logger s_logger = Logger.getLogger(ListBaremetalDhcpCmd.class);
+     private static final String s_name = "listexternaldhcpresponse";
 -    @PlugService BaremetalDhcpManager _dhcpMgr;
++    @Inject BaremetalDhcpManager _dhcpMgr;
+     
+     // ///////////////////////////////////////////////////
+     // ////////////// API parameters /////////////////////
+     // ///////////////////////////////////////////////////
+     @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "DHCP server device ID")
+     private Long id;
+     
+     @Parameter(name = ApiConstants.POD_ID, type = CommandType.LONG, description = "Pod ID where pxe server is in")
+     private Long podId;
+     
+     @Parameter(name = ApiConstants.DHCP_SERVER_TYPE, type = CommandType.STRING, description = "Type of DHCP device")
+     private String deviceType;
+     
+     public Long getId() {
+         return id;
+     }
+ 
+     public void setId(Long id) {
+         this.id = id;
+     }
+ 
+     public Long getPodId() {
+         return podId;
+     }
+ 
+     public void setPodId(Long podId) {
+         this.podId = podId;
+     }
+     
+     public String getDeviceType() {
+         return deviceType;
+     }
+ 
+     public void setDeviceType(String deviceType) {
+         this.deviceType = deviceType;
+     }
+ 
+     @Override
+     public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
+             ResourceAllocationException, NetworkRuleConflictException {
+     	try {
+             ListResponse<BaremetalDhcpResponse> response = new ListResponse<BaremetalDhcpResponse>();
+             List<BaremetalDhcpResponse> dhcpResponses = _dhcpMgr.listBaremetalDhcps(this);
+             response.setResponses(dhcpResponses);
+             response.setResponseName(getCommandName());
+             this.setResponseObject(response);
+     	} catch (Exception e) {
+     		s_logger.debug("Exception happend while executing ListBaremetalDhcpCmd");
+             throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
+     	}
+ 
+     }
+ 
+     @Override
+     public String getCommandName() {
+         return s_name;
+     }
+ 
+ }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/ListBaremetalPxePingServersCmd.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/ListBaremetalPxePingServersCmd.java
index 0000000,dceb8bf..b4c569f
mode 000000,100755..100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/ListBaremetalPxePingServersCmd.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/ListBaremetalPxePingServersCmd.java
@@@ -1,0 -1,92 +1,93 @@@
+ // 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.
+ // 
+ // Automatically generated by addcopyright.py at 01/29/2013
+ package com.cloud.baremetal.networkservice;
+ 
+ import java.util.List;
+ 
++import javax.inject.Inject;
++
+ import org.apache.cloudstack.api.ApiConstants;
+ import org.apache.cloudstack.api.ApiErrorCode;
+ import org.apache.cloudstack.api.BaseCmd;
+ import org.apache.cloudstack.api.BaseCmd.CommandType;
+ import org.apache.cloudstack.api.BaseListCmd;
+ import org.apache.cloudstack.api.Parameter;
 -import org.apache.cloudstack.api.PlugService;
+ import org.apache.cloudstack.api.ServerApiException;
+ import org.apache.cloudstack.api.response.ListResponse;
+ import org.apache.log4j.Logger;
+ 
+ import com.cloud.exception.ConcurrentOperationException;
+ import com.cloud.exception.InsufficientCapacityException;
+ import com.cloud.exception.NetworkRuleConflictException;
+ import com.cloud.exception.ResourceAllocationException;
+ import com.cloud.exception.ResourceUnavailableException;
+ 
+ public class ListBaremetalPxePingServersCmd extends BaseListCmd {
+     private static final Logger s_logger = Logger.getLogger(ListBaremetalPxePingServersCmd.class);
+     private static final String s_name = "listpingpxeserverresponse";
+ 
 -    @PlugService
++    @Inject
+     BaremetalPxeManager _pxeMgr;
+     // ///////////////////////////////////////////////////
+     // ////////////// API parameters /////////////////////
+     // ///////////////////////////////////////////////////
+ 
+     @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "Ping pxe server device ID")
+     private Long id;
+     
+     @Parameter(name = ApiConstants.POD_ID, type = CommandType.LONG, description = "Pod ID where pxe server is in")
+     private Long podId;
+ 
+     public Long getId() {
+         return id;
+     }
+ 
+     public void setId(Long id) {
+         this.id = id;
+     }
+ 
+     public Long getPodId() {
+         return podId;
+     }
+ 
+     public void setPodId(Long podId) {
+         this.podId = podId;
+     }
+ 
+     @Override
+     public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
+             ResourceAllocationException, NetworkRuleConflictException {
+         try {
+             ListResponse<BaremetalPxeResponse> response = new ListResponse<BaremetalPxeResponse>();
+             List<BaremetalPxeResponse> pxeResponses = _pxeMgr.listPxeServers(this);
+             response.setResponses(pxeResponses);
+             response.setResponseName(getCommandName());
+             this.setResponseObject(response);
+         } catch (Exception e) {
+             s_logger.debug("Exception happend while executing ListPingPxeServersCmd" ,e);
+             throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
+         }
+     }
+ 
+     @Override
+     public String getCommandName() {
+         return s_name;
+     }
+ 
+ }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
index 0615a0a,96c4348..85a34eb
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
@@@ -613,49 -616,70 +615,70 @@@ public class VmwareResource implements 
  
          return new SetPortForwardingRulesAnswer(cmd, results, endResult);
      }
 -    
 +
      protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) {
 -		String controlIp = getRouterSshControlIp(cmd);
 -		String[] results = new String[cmd.getRules().length];
 +        String controlIp = getRouterSshControlIp(cmd);
 +        String[] results = new String[cmd.getRules().length];
+         FirewallRuleTO[] allrules = cmd.getRules();
+         FirewallRule.TrafficType trafficType = allrules[0].getTrafficType();
  
 -		String[][] rules = cmd.generateFwRules();
 -		String args = "";
 -		args += " -F ";
 +        String[][] rules = cmd.generateFwRules();
 +        String args = "";
 +        args += " -F ";
+         if (trafficType == FirewallRule.TrafficType.Egress){
+             args+= " -E ";
+         }
+ 
 -		StringBuilder sb = new StringBuilder();
 -		String[] fwRules = rules[0];
 -		if (fwRules.length > 0) {
 -			for (int i = 0; i < fwRules.length; i++) {
 -				sb.append(fwRules[i]).append(',');
 -			}
 -			args += " -a " + sb.toString();
 -		}
 +        StringBuilder sb = new StringBuilder();
 +        String[] fwRules = rules[0];
 +        if (fwRules.length > 0) {
 +            for (int i = 0; i < fwRules.length; i++) {
 +                sb.append(fwRules[i]).append(',');
 +            }
 +            args += " -a " + sb.toString();
 +        }
  
 -		try {
 -			VmwareManager mgr = getServiceContext().getStockObject(
 -					VmwareManager.CONTEXT_STOCK_NAME);
 +        try {
 +            VmwareManager mgr = getServiceContext().getStockObject(
 +                    VmwareManager.CONTEXT_STOCK_NAME);
-             Pair<Boolean, String> result = SshHelper.sshExecute(controlIp,
+ 
+             Pair<Boolean, String> result = null;
+ 
+             if (trafficType == FirewallRule.TrafficType.Egress){
+                 result = SshHelper.sshExecute(controlIp,
+                         DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(),
+                         null, "/root/firewallRule_egress.sh " + args);
+             } else {
+                 result = SshHelper.sshExecute(controlIp,
 -					DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(),
 -					null, "/root/firewall_rule.sh " + args);
 +                    DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(),
 +                    null, "/root/firewall_rule.sh " + args);
+             }
  
-             if (s_logger.isDebugEnabled())
+             if (s_logger.isDebugEnabled()) {
+                 if (trafficType == FirewallRule.TrafficType.Egress){
+                     s_logger.debug("Executing script on domain router " + controlIp
+                             + ": /root/firewallRule_egress.sh " + args);
+                 } else {
 -				s_logger.debug("Executing script on domain router " + controlIp
 -						+ ": /root/firewall_rule.sh " + args);
 +                s_logger.debug("Executing script on domain router " + controlIp
 +                        + ": /root/firewall_rule.sh " + args);
+                  }
+              }
  
 -			if (!result.first()) {
 -				s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: "
 -						+ args);
 -				//FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
 -	            for (int i=0; i < results.length; i++) {
 -	                results[i] = "Failed";
 -	            }
 -	            
 -	            return new SetFirewallRulesAnswer(cmd, false, results);
 -			} 
 -		} catch (Throwable e) {
 -			s_logger.error("SetFirewallRulesCommand(args: " + args
 -					+ ") failed on setting one rule due to "
 -					+ VmwareHelper.getExceptionMessage(e), e);
 -			//FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
 +            if (!result.first()) {
 +                s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: "
 +                        + args);
 +                //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
 +                for (int i=0; i < results.length; i++) {
 +                    results[i] = "Failed";
 +                }
 +
 +                return new SetFirewallRulesAnswer(cmd, false, results);
 +            } 
 +        } catch (Throwable e) {
 +            s_logger.error("SetFirewallRulesCommand(args: " + args
 +                    + ") failed on setting one rule due to "
 +                    + VmwareHelper.getExceptionMessage(e), e);
 +            //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
              for (int i=0; i < results.length; i++) {
                  results[i] = "Failed";
              }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index 7e763e2,e9690eb..4a74b64
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@@ -53,7 -53,8 +53,9 @@@ import javax.ejb.Local
  import javax.naming.ConfigurationException;
  import javax.xml.parsers.DocumentBuilderFactory;
  
 +import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
+ import com.cloud.agent.api.to.*;
+ import com.cloud.network.rules.FirewallRule;
  import org.apache.log4j.Logger;
  import org.apache.xmlrpc.XmlRpcException;
  import org.w3c.dom.Document;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXExternalFirewallElement.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/plugins/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiResponseHelper.java
index 61f906b,641f25b..d4ad82b
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@@ -2316,10 -2313,15 +2316,15 @@@ public class ApiResponseHelper implemen
  
          List<String> cidrs = ApiDBUtils.findFirewallSourceCidrs(fwRule.getId());
          response.setCidrList(StringUtils.join(cidrs, ","));
 -        
 +
+         if (fwRule.getTrafficType() == FirewallRule.TrafficType.Ingress) {
 -            IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId());
 -            response.setPublicIpAddressId(ip.getId());
 -            response.setPublicIpAddress(ip.getAddress().addr());
 +        IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId());
 +        response.setPublicIpAddressId(ip.getId());
 +        response.setPublicIpAddress(ip.getAddress().addr());
+         } else if (fwRule.getTrafficType() == FirewallRule.TrafficType.Egress) {
+             response.setPublicIpAddress(null);
+             response.setNetworkId(fwRule.getNetworkId());
+         }
  
          FirewallRule.State state = fwRule.getState();
          String stateToSet = state.toString();

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/api/ApiServlet.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/network/NetworkManager.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/network/NetworkManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/NetworkManagerImpl.java
index e2b6f32,0a4851f..0235bf1
--- a/server/src/com/cloud/network/NetworkManagerImpl.java
+++ b/server/src/com/cloud/network/NetworkManagerImpl.java
@@@ -2279,47 -2278,52 +2279,52 @@@ public class NetworkManagerImpl extend
      @Override
      public boolean applyRules(List<? extends FirewallRule> rules, FirewallRule.Purpose purpose,
              NetworkRuleApplier applier, boolean continueOnError) throws ResourceUnavailableException {
 -    	if (rules == null || rules.size() == 0) {
 -    		s_logger.debug("There are no rules to forward to the network elements");
 -    		return true;
 -    	}
 +        if (rules == null || rules.size() == 0) {
 +            s_logger.debug("There are no rules to forward to the network elements");
 +            return true;
 +        }
  
 -    	boolean success = true;
 -    	Network network = _networksDao.findById(rules.get(0).getNetworkId());
 +        boolean success = true;
 +        Network network = _networksDao.findById(rules.get(0).getNetworkId());
+         FirewallRuleVO.TrafficType trafficType = rules.get(0).getTrafficType();
+          List<PublicIp> publicIps = new ArrayList<PublicIp>();
  
+         if (! (rules.get(0).getPurpose() == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress)) {
 -            // get the list of public ip's owned by the network
 -            List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null);
 -            if (userIps != null && !userIps.isEmpty()) {
 -                for (IPAddressVO userIp : userIps) {
 -    			PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(userIp.getMacAddress()));
 -    			publicIps.add(publicIp);
 -	                }
 -             }
 -
 -    	// rules can not programmed unless IP is associated with network service provider, so run IP assoication for
 -    	// the network so as to ensure IP is associated before applying rules (in add state)
 -    	applyIpAssociations(network, false, continueOnError, publicIps);
 +        // get the list of public ip's owned by the network
 +        List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null);
-         List<PublicIp> publicIps = new ArrayList<PublicIp>();
 +        if (userIps != null && !userIps.isEmpty()) {
 +            for (IPAddressVO userIp : userIps) {
 +                PublicIp publicIp = new PublicIp(userIp, _vlanDao.findById(userIp.getVlanId()), NetUtils.createSequenceBasedMacAddress(userIp.getMacAddress()));
 +                publicIps.add(publicIp);
 +            }
 +        }
 +
 +        // rules can not programmed unless IP is associated with network service provider, so run IP assoication for
 +        // the network so as to ensure IP is associated before applying rules (in add state)
 +        applyIpAssociations(network, false, continueOnError, publicIps);
+ 	}
 -    	
 -    	try {
 -    		applier.applyRules(network, purpose, rules);
 -    	} catch (ResourceUnavailableException e) {
 -    		if (!continueOnError) {
 -    			throw e;
 -    		}
 -    		s_logger.warn("Problems with applying " + purpose + " rules but pushing on", e);
 -    		success = false;
 -    	}
 -    	
 +
 +        try {
 +            applier.applyRules(network, purpose, rules);
 +        } catch (ResourceUnavailableException e) {
 +            if (!continueOnError) {
 +                throw e;
 +            }
 +            s_logger.warn("Problems with applying " + purpose + " rules but pushing on", e);
 +            success = false;
 +        }
 +
+         if (! (rules.get(0).getPurpose() == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress) ) {
 -            // if all the rules configured on public IP are revoked then dis-associate IP with network service provider
 -            applyIpAssociations(network, true, continueOnError, publicIps);
 +        // if all the rules configured on public IP are revoked then dis-associate IP with network service provider
 +        applyIpAssociations(network, true, continueOnError, publicIps);
+         }
  
 -    	return success;
 +        return success;
      }
 -        
 -    
  
 -   
 +
 +
 +
  
      public class NetworkGarbageCollector implements Runnable {
  
@@@ -3355,42 -3396,42 +3398,42 @@@
          }
          return nic;
      }
 -    
 +
      @Override
-     public NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfileImpl<VMInstanceVO> vmProfile, boolean prepare)
+     public NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfile<? extends VMInstanceVO> vmProfile, boolean prepare)
 -            throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
 +            throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, 
              ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
 -                
 -                VirtualMachine vm = vmProfile.getVirtualMachine();
 -                DataCenter dc = _configMgr.getZone(network.getDataCenterId());
 -                Host host = _hostDao.findById(vm.getHostId()); 
 -                DeployDestination dest = new DeployDestination(dc, null, null, host);
 -                
 -                NicProfile nic = getNicProfileForVm(network, requested, vm);
 -                
 +
 +        VirtualMachine vm = vmProfile.getVirtualMachine();
-         NetworkVO networkVO = _networksDao.findById(network.getId());
 +        DataCenter dc = _configMgr.getZone(network.getDataCenterId());
 +        Host host = _hostDao.findById(vm.getHostId()); 
 +        DeployDestination dest = new DeployDestination(dc, null, null, host);
 +
 +        NicProfile nic = getNicProfileForVm(network, requested, vm);
 +
-         //1) allocate nic (if needed)
-         if (nic == null) {
+                 //1) allocate nic (if needed) Always allocate if it is a user vm
+                 if (nic == null || (vmProfile.getType() == VirtualMachine.Type.User)) {
 -                    int deviceId = _nicDao.countNics(vm.getId());
 -                    
 -                    nic = allocateNic(requested, network, false, 
 -                            deviceId, vmProfile).first();
 -                    
 -                    if (nic == null) {
 -                        throw new CloudRuntimeException("Failed to allocate nic for vm " + vm + " in network " + network);
 -                    }
 -                    
 -                    s_logger.debug("Nic is allocated successfully for vm " + vm + " in network " + network); 
 -                }
 -                
 -                //2) prepare nic
 -                if (prepare) {
 -                    NetworkVO networkVO = _networksDao.findById(network.getId());
 -                    nic = prepareNic(vmProfile, dest, context, nic.getId(), networkVO);
 -                    s_logger.debug("Nic is prepared successfully for vm " + vm + " in network " + network);
 -                }
 -                
 -                return nic;
 +            int deviceId = _nicDao.countNics(vm.getId());
 +
 +            nic = allocateNic(requested, network, false, 
 +                    deviceId, vmProfile).first();
 +
 +            if (nic == null) {
 +                throw new CloudRuntimeException("Failed to allocate nic for vm " + vm + " in network " + network);
              }
 +
 +            s_logger.debug("Nic is allocated successfully for vm " + vm + " in network " + network); 
 +        }
 +
 +        //2) prepare nic
 +        if (prepare) {
++                    NetworkVO networkVO = _networksDao.findById(network.getId());
 +            nic = prepareNic(vmProfile, dest, context, nic.getId(), networkVO);
 +            s_logger.debug("Nic is prepared successfully for vm " + vm + " in network " + network);
 +        }
 +
 +        return nic;
 +    }
      @Override
      public List<NicProfile> getNicProfiles(VirtualMachine vm) {
          List<NicVO> nics = _nicDao.listByVmId(vm.getId());

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/network/NetworkModelImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/network/dao/FirewallRulesDao.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/dao/FirewallRulesDao.java
index c461fd6,b5b7f99..0bbaa93
--- a/server/src/com/cloud/network/dao/FirewallRulesDao.java
+++ b/server/src/com/cloud/network/dao/FirewallRulesDao.java
@@@ -57,8 -56,7 +57,9 @@@ public interface FirewallRulesDao exten
      long countRulesByIpId(long sourceIpId);
      
      List<FirewallRuleVO> listByNetworkPurposeTrafficTypeAndNotRevoked(long networkId, FirewallRule.Purpose purpose, FirewallRule.TrafficType trafficType);
+     List<FirewallRuleVO> listByNetworkPurposeTrafficType(long networkId, FirewallRule.Purpose purpose, FirewallRule.TrafficType trafficType);
 -
 +    
      List<FirewallRuleVO> listByIpAndPurposeWithState(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state);
 +        
 +    void loadSourceCidrs(FirewallRuleVO rule);
  }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/network/element/CloudZonesNetworkElement.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/network/element/VirtualRouterElement.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/firewall/FirewallManagerImpl.java
index eba66fc,d4958f3..7bce18c
--- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
+++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
@@@ -29,8 -28,13 +29,14 @@@ import javax.naming.ConfigurationExcept
  
  import org.apache.cloudstack.api.command.user.firewall.ListFirewallRulesCmd;
  import org.apache.log4j.Logger;
 +import org.springframework.stereotype.Component;
  
+ import com.mysql.jdbc.ConnectionPropertiesImpl;
+ import org.apache.log4j.Logger;
+ 
+ import org.apache.cloudstack.api.BaseListCmd;
+ import org.apache.cloudstack.api.command.user.firewall.ListEgressFirewallRulesCmd;
+ import org.apache.cloudstack.api.command.user.firewall.ListFirewallRulesCmd;
  import com.cloud.configuration.Config;
  import com.cloud.configuration.dao.ConfigurationDao;
  import com.cloud.domain.dao.DomainDao;
@@@ -42,10 -46,13 +48,11 @@@ import com.cloud.event.dao.UsageEventDa
  import com.cloud.exception.InvalidParameterValueException;
  import com.cloud.exception.NetworkRuleConflictException;
  import com.cloud.exception.ResourceUnavailableException;
 -import com.cloud.network.IPAddressVO;
  import com.cloud.network.IpAddress;
  import com.cloud.network.Network;
 -import com.cloud.network.NetworkVO;
  import com.cloud.network.Network.Capability;
  import com.cloud.network.Network.Service;
+ import com.cloud.network.Networks.TrafficType;
  import com.cloud.network.NetworkManager;
  import com.cloud.network.NetworkModel;
  import com.cloud.network.NetworkRuleApplier;
@@@ -147,36 -174,44 +154,44 @@@ public class FirewallManagerImpl extend
      }
  
      @Override
-     public FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException {
+     public FirewallRule createEgressFirewallRule(FirewallRule rule) throws NetworkRuleConflictException {
          Account caller = UserContext.current().getCaller();
 -
 +        
-         if (rule.getSourceCidrList() == null && (rule.getPurpose() == Purpose.Firewall || rule.getPurpose() == Purpose.NetworkACL)) {
-             _firewallDao.loadSourceCidrs((FirewallRuleVO)rule);
-         }
- 
-         return createFirewallRule(rule.getSourceIpAddressId(), caller, rule.getXid(), rule.getSourcePortStart(), 
+         return createFirewallRule(null, caller, rule.getXid(), rule.getSourcePortStart(), 
                  rule.getSourcePortEnd(), rule.getProtocol(), rule.getSourceCidrList(), rule.getIcmpCode(),
-                 rule.getIcmpType(), null, rule.getType(), rule.getNetworkId());
+                 rule.getIcmpType(), null, rule.getType(), rule.getNetworkId(), rule.getTrafficType());
+     }
+ 
+     public FirewallRule createIngressFirewallRule(FirewallRule rule) throws NetworkRuleConflictException {
+          Account caller = UserContext.current().getCaller();
+         Long sourceIpAddressId = rule.getSourceIpAddressId();
+  
+         return createFirewallRule(sourceIpAddressId, caller, rule.getXid(), rule.getSourcePortStart(), 
+                  rule.getSourcePortEnd(), rule.getProtocol(), rule.getSourceCidrList(), rule.getIcmpCode(),
+                 rule.getIcmpType(), null, rule.getType(), rule.getNetworkId(), rule.getTrafficType());
 -     }
 +    }
  
      @DB
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_FIREWALL_OPEN, eventDescription = "creating firewall rule", create = true)
-     public FirewallRule createFirewallRule(long ipAddrId, Account caller, String xId, Integer portStart, 
+     public FirewallRule createFirewallRule(Long ipAddrId, Account caller, String xId, Integer portStart,
 -             Integer portEnd, String protocol, List<String> sourceCidrList, Integer icmpCode, Integer icmpType,
 +            Integer portEnd, String protocol, List<String> sourceCidrList, Integer icmpCode, Integer icmpType,
-             Long relatedRuleId, FirewallRule.FirewallRuleType type, long networkId) throws NetworkRuleConflictException {
+             Long relatedRuleId, FirewallRule.FirewallRuleType type, Long networkId, FirewallRule.TrafficType trafficType) throws NetworkRuleConflictException {
 - 
 +
-         IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
+         IPAddressVO ipAddress = null;
+         if (ipAddrId != null){
+             // this for ingress firewall rule, for egress id is null
+              ipAddress = _ipAddressDao.findById(ipAddrId);
 -           // Validate ip address
 -           if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) {
 +        // Validate ip address
 +        if (ipAddress == null && type == FirewallRule.FirewallRuleType.User) {
-             throw new InvalidParameterValueException("Unable to create firewall rule; ip id=" + ipAddrId + 
-                     " doesn't exist in the system");
+               throw new InvalidParameterValueException("Unable to create firewall rule; " +
+                     "couldn't locate IP address by id in the system");
 -           }
 -           _networkModel.checkIpForService(ipAddress, Service.Firewall, null);
          }
- 
 - 
 +        _networkModel.checkIpForService(ipAddress, Service.Firewall, null);  
++        }
 +
-         validateFirewallRule(caller, ipAddress, portStart, portEnd, protocol, Purpose.Firewall, type);
+         validateFirewallRule(caller, ipAddress, portStart, portEnd, protocol, Purpose.Firewall, type, networkId, trafficType);
 - 
 +
          // icmp code and icmp type can't be passed in for any other protocol rather than icmp
          if (!protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO) && (icmpCode != null || icmpType != null)) {
              throw new InvalidParameterValueException("Can specify icmpCode and icmpType for ICMP protocol only");
@@@ -243,7 -286,13 +266,13 @@@
          _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
  
          sb.and("id", sb.entity().getId(), Op.EQ);
+         sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ);
+         if (cmd instanceof ListEgressFirewallRulesCmd ) {
+             networkId =((ListEgressFirewallRulesCmd)cmd).getNetworkId();
+             sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
+         } else {
 -            sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
 +        sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
+         }
          sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
  
  
@@@ -288,10 -342,17 +322,17 @@@
  
      @Override
      public void detectRulesConflict(FirewallRule newRule) throws NetworkRuleConflictException {
- 
-         List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurposeAndNotRevoked(newRule.getSourceIpAddressId(), null);
+         List<FirewallRuleVO> rules;
+         if(newRule.getSourceIpAddressId() != null){
+              rules = _firewallDao.listByIpAndPurposeAndNotRevoked(newRule.getSourceIpAddressId(), null);
 -             assert (rules.size() >= 1) : "For network rules, we now always first persist the rule and then check for " +
 -             "network conflicts so we should at least have one rule at this point.";
 +        assert (rules.size() >= 1) : "For network rules, we now always first persist the rule and then check for " +
 +        "network conflicts so we should at least have one rule at this point.";
+         } else {
+             // fetches only firewall egress rules.
+             rules = _firewallDao.listByNetworkPurposeTrafficTypeAndNotRevoked(newRule.getNetworkId(), Purpose.Firewall, newRule.getTrafficType());
+             assert (rules.size() >= 1);
+         }
+ 
  
          for (FirewallRuleVO rule : rules) {
              if (rule.getId() == newRule.getId()) {
@@@ -399,38 -457,56 +440,56 @@@
              return;
          }
  
-         // Validate ip address
-         _accountMgr.checkAccess(caller, null, true, ipAddress);
- 
-         Long networkId = null;
- 
+         if (ipAddress!=null){
 -            if (ipAddress.getAssociatedWithNetworkId() == null) {
 +        if (ipAddress.getAssociatedWithNetworkId() == null) {
-             throw new InvalidParameterValueException("Unable to create firewall rule ; ip id=" + 
-                     ipAddress.getId() + " is not associated with any network");
+                 throw new InvalidParameterValueException("Unable to create firewall rule ; ip with specified id is not associated with any network");
 -            } else {
 -                networkId = ipAddress.getAssociatedWithNetworkId();
 -            }
 +        } else {
 +            networkId = ipAddress.getAssociatedWithNetworkId();
 +        }
  
+             // Validate ip address
+             _accountMgr.checkAccess(caller, null, true, ipAddress);
+ 
 -            Network network = _networkModel.getNetwork(networkId);
 -            assert network != null : "Can't create port forwarding rule as network associated with public ip address is null?";
 +        Network network = _networkModel.getNetwork(networkId);
 +        assert network != null : "Can't create port forwarding rule as network associated with public ip address is null?";
  
+             if (trafficType == FirewallRule.TrafficType.Egress) {
+                 _accountMgr.checkAccess(caller, null, true, network);
+             }
+ 
 -            // Verify that the network guru supports the protocol specified
 -            Map<Network.Capability, String> caps = null;
 +        // Verify that the network guru supports the protocol specified
 +        Map<Network.Capability, String> caps = null;
  
 -            if (purpose == Purpose.LoadBalancing) {
 -                if (!_elbEnabled) {
 -                    caps = _networkModel.getNetworkServiceCapabilities(network.getId(), Service.Lb);
 -                }
 -            } else if (purpose == Purpose.PortForwarding) {
 -                caps = _networkModel.getNetworkServiceCapabilities(network.getId(), Service.PortForwarding);
 +        if (purpose == Purpose.LoadBalancing) {
 +            if (!_elbEnabled) {
 +                caps = _networkModel.getNetworkServiceCapabilities(network.getId(), Service.Lb);
 +            }
 +        } else if (purpose == Purpose.PortForwarding) {
 +            caps = _networkModel.getNetworkServiceCapabilities(network.getId(), Service.PortForwarding);
+             }else if (purpose == Purpose.Firewall){
+                 caps = _networkModel.getNetworkServiceCapabilities(network.getId(),Service.Firewall);
 -            }
 +        }
  
 -            if (caps != null) {
 +        if (caps != null) {
-             String supportedProtocols = caps.get(Capability.SupportedProtocols).toLowerCase();
+                 String supportedProtocols;
+                 String supportedTrafficTypes = null;
+                 if (purpose == FirewallRule.Purpose.Firewall) {
+                     supportedTrafficTypes = caps.get(Capability.SupportedTrafficDirection).toLowerCase();
+                 }
+ 
+                 if (purpose == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress) {
+                     supportedProtocols = caps.get(Capability.SupportedEgressProtocols).toLowerCase();
+                 } else {
+                     supportedProtocols = caps.get(Capability.SupportedProtocols).toLowerCase();
+                 }
+ 
 -                if (!supportedProtocols.contains(proto.toLowerCase())) {
 -                    throw new InvalidParameterValueException("Protocol " + proto + " is not supported in zone " + network.getDataCenterId());
 -                } else if (proto.equalsIgnoreCase(NetUtils.ICMP_PROTO) && purpose != Purpose.Firewall) {
 -                    throw new InvalidParameterValueException("Protocol " + proto + " is currently supported only for rules with purpose " + Purpose.Firewall);
 +            if (!supportedProtocols.contains(proto.toLowerCase())) {
 +                throw new InvalidParameterValueException("Protocol " + proto + " is not supported in zone " + network.getDataCenterId());
 +            } else if (proto.equalsIgnoreCase(NetUtils.ICMP_PROTO) && purpose != Purpose.Firewall) {
 +                throw new InvalidParameterValueException("Protocol " + proto + " is currently supported only for rules with purpose " + Purpose.Firewall);
+                 } else if (purpose == Purpose.Firewall && !supportedTrafficTypes.contains(trafficType.toString().toLowerCase())) {
+                     throw new InvalidParameterValueException("Traffic Type " + trafficType + " is currently supported by Firewall in network " + networkId);
+                 }
              }
          }
      }
@@@ -576,10 -658,19 +641,19 @@@
          revokeRule(rule, caller, userId, false);
  
          boolean success = false;
+         Long networkId = rule.getNetworkId();
  
          if (apply) {
+             // ingress firewall rule
+             if (rule.getSourceIpAddressId() != null){ 
+                 //feteches ingress firewall, ingress firewall rules associated with the ip
 -                List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(rule.getSourceIpAddressId(), Purpose.Firewall);
 -                return applyFirewallRules(rules, false, caller);
 +            List<FirewallRuleVO> rules = _firewallDao.listByIpAndPurpose(rule.getSourceIpAddressId(), Purpose.Firewall);
 +            return applyFirewallRules(rules, false, caller);
+                 //egress firewall rule
+             } else if ( networkId != null){
+                 List<FirewallRuleVO> rules = _firewallDao.listByNetworkPurposeTrafficType(rule.getNetworkId(), Purpose.Firewall, FirewallRule.TrafficType.Egress);
+                 return applyFirewallRules(rules, false, caller);
+             }
          } else {
              success = true;
          }
@@@ -781,11 -872,8 +855,11 @@@
          List<FirewallRuleVO> systemRules = _firewallDao.listSystemRules();
          for (FirewallRuleVO rule : systemRules) {
              try {
 +                if (rule.getSourceCidrList() == null && (rule.getPurpose() == Purpose.Firewall || rule.getPurpose() == Purpose.NetworkACL)) {
 +                    _firewallDao.loadSourceCidrs(rule);
 +                } 
                  this.createFirewallRule(ip.getId(), acct, rule.getXid(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(),
-                         rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), rule.getRelated(), FirewallRuleType.System, rule.getNetworkId());
+                         rule.getSourceCidrList(), rule.getIcmpCode(), rule.getIcmpType(), rule.getRelated(), FirewallRuleType.System, rule.getNetworkId(), rule.getTrafficType());
              } catch (Exception e) {
                  s_logger.debug("Failed to add system wide firewall rule, due to:" + e.toString());
              }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/1b2b369e/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
----------------------------------------------------------------------