private Long getAccountId(HealthcheckInstanceType type, long instanceId) { if (type == HealthcheckInstanceType.INSTANCE) { Instance instance = objectManager.loadResource(Instance.class, instanceId); if (instance != null) { return instance.getAccountId(); } } return null; } }
public AgentInstanceBuilderImpl(AgentInstanceFactoryImpl factory, Instance instance, Set<String> roles) { this(factory); this.accountId = instance.getAccountId(); this.zoneId = instance.getZoneId(); String uriPrefix = "event"; Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS); Object prefix = labels.get(SystemLabels.LABEL_AGENT_URI_PREFIX); if (prefix != null) { uriPrefix = prefix.toString(); } this.uri = uriPrefix + ":///instanceId=" + instance.getId(); this.resourceAccountId = instance.getAccountId(); this.requestedRoles = roles; }
protected boolean k8sRequired(Instance instance) { Account account = objectManager.loadResource(Account.class, instance.getAccountId()); String orch = DataAccessor.fieldString(account, AccountConstants.FIELD_ORCHESTRATION); return AccountConstants.ORC_KUBERNETES_DISPLAY.equals(orch); }
protected Service getService(final Instance instance, final String name, final String projectName) { Service service = composeDao.getComposeServiceByName(instance.getAccountId(), name, projectName); if (service != null) { return service; } return lockManager.lock(new ComposeServiceLock(instance.getAccountId(), name), new LockCallback<Service>() { @Override public Service doWithLock() { Service service = composeDao.getComposeServiceByName(instance.getAccountId(), name, projectName); if (service != null) { return service; } return createService(instance); } }); }
@Override public Service doWithLock() { Service service = composeDao.getComposeServiceByName(instance.getAccountId(), name, projectName); if (service != null) { return service; } return createService(instance); } });
private void createLabels(Instance instance) { @SuppressWarnings("unchecked") Map<String, String> labels = DataAccessor.fields(instance).withKey(InstanceConstants.FIELD_LABELS).as(Map.class); if (labels == null) { return; } for (Map.Entry<String, String> labelEntry : labels.entrySet()) { String labelKey = labelEntry.getKey(); String labelValue = labelEntry.getValue(); labelsService.createContainerLabel(instance.getAccountId(), instance.getId(), labelKey, labelValue); } }
@Override public AgentInstanceBuilder withInstance(Instance instance) { withAccountId(instance.getAccountId()); withZoneId(instance.getZoneId()); return this; }
protected Set<Long> createNicsFromIds(Instance instance, List<Nic> nics, Map<String, Object> data, List<Long> networkIds) { Set<Long> nicIds = new TreeSet<Long>(); int deviceId = 0; if (networkIds != null) { for (int i = 0; i < networkIds.size(); i++) { Number createId = networkIds.get(i); if (createId == null) { deviceId++; continue; } Nic newNic = null; for (Nic nic : nics) { if (nic.getNetworkId() == createId.longValue()) { newNic = nic; break; } } if (newNic == null) { newNic = objectManager.create(Nic.class, NIC.ACCOUNT_ID, instance.getAccountId(), NIC.NETWORK_ID, createId, NIC.INSTANCE_ID, instance .getId(), NIC.DEVICE_NUMBER, deviceId); } deviceId++; processManager.executeStandardProcess(StandardProcess.CREATE, newNic, data); nicIds.add(newNic.getId()); } } return nicIds; }
@SuppressWarnings("unchecked") void processLabels(Instance instance) { Map<String, String> labels = CollectionUtils.toMap(CollectionUtils.getNestedValue(instance.getData(), FIELD_DOCKER_INSPECT, "Config", "Labels")); for (Map.Entry<String, String>label : labels.entrySet()) { labelsService.createContainerLabel(instance.getAccountId(), instance.getId(), label.getKey(), label.getValue()); } Map<String, Object> inspect = (Map<String, Object>)instance.getData().get(FIELD_DOCKER_INSPECT); if (inspect == null) { return; } transformer.setLabels(instance, inspect); objectManager.persist(instance); }
@Override public Mount doWithLock() { Map<Object, Object> criteria = new HashMap<Object, Object>(); criteria.put(MOUNT.VOLUME_ID, volume.getId()); criteria.put(MOUNT.INSTANCE_ID, instance.getId()); criteria.put(MOUNT.PATH, path); criteria.put(MOUNT.REMOVED, null); criteria.put(MOUNT.STATE, new Condition(ConditionType.NE, CommonStatesConstants.INACTIVE)); Mount mount = objectManager.findAny(Mount.class, criteria); if (mount != null) { if (!mount.getPath().equalsIgnoreCase(permissions)) objectManager.setFields(mount, MOUNT.PERMISSIONS, permissions); return mount; } return objectManager.create(Mount.class, MOUNT.ACCOUNT_ID, instance.getAccountId(), MOUNT.INSTANCE_ID, instance.getId(), MOUNT.VOLUME_ID, volume.getId(), MOUNT.PATH, path, MOUNT.PERMISSIONS, permissions); } });
private String checkContainerNetwork(String inspectNetMode, Instance instance, Map<String, Object> data) { if (!StringUtils.startsWith(inspectNetMode, NetworkConstants.NETWORK_MODE_CONTAINER)) return null; String[] parts = StringUtils.split(inspectNetMode, ":", 2); String targetContainer = null; if (parts.length == 2) { targetContainer = parts[1]; Instance netFromInstance = instanceDao.getInstanceByUuidOrExternalId(instance.getAccountId(), targetContainer, targetContainer); if (netFromInstance == null) { Event inspectEvent = newInspectEvent(targetContainer, targetContainer); Object inspectObj = callAgentForInspect(data, inspectEvent); Map<String, Object> inspect = CollectionUtils.toMap(inspectObj); String uuid = getRancherUuidLabel(inspect, null); String externalId = inspect.get("Id") != null ? inspect.get("Id").toString() : null; netFromInstance = instanceDao.getInstanceByUuidOrExternalId(instance.getAccountId(), uuid, externalId); } if (netFromInstance != null) { DataAccessor.fields(instance).withKey(FIELD_NETWORK_CONTAINER_ID).set(netFromInstance.getId()); return NetworkConstants.NETWORK_MODE_CONTAINER; } } log.warn("Problem configuring container networking for container [externalId: {}]. Could not find target container: [{}].", instance.getExternalId(), targetContainer); return NetworkConstants.NETWORK_MODE_NONE; }
protected Volume getRoot(Instance instance, List<Volume> volumes) { if (instance.getImageId() == null) { return null; } for (Volume volume : volumes) { if (volume.getDeviceNumber() != null && volume.getDeviceNumber().intValue() == 0) { return volume; } } return objectManager.create(Volume.class, VOLUME.ACCOUNT_ID, instance.getAccountId(), VOLUME.INSTANCE_ID, instance.getId(), VOLUME.IMAGE_ID, instance .getImageId(), VOLUME.DEVICE_NUMBER, 0, VOLUME.ATTACHED_STATE, CommonStatesConstants.ACTIVE); }
private void callExternalSchedulerToRemovePorts(Instance instance, List<Port> removedPorts) { List<Long> agentIds = getAgentResource(instance.getAccountId(), Arrays.asList(instance)); for (Long agentId : agentIds) { EventVO<Map<String, Object>> schedulerEvent = buildEventForPort(SCHEDULER_RELEASE_EVENT, InstanceConstants.PROCESS_DEALLOCATE, Arrays.asList(instance), agentId, removedPorts); if (schedulerEvent != null) { Map<String, Object> reqData = CollectionUtils .toMap(schedulerEvent.getData().get(SCHEDULER_REQUEST_DATA_NAME)); reqData.put(HOST_ID, getHostUuid(instance)); RemoteAgent agent = agentLocator.lookupAgent(agentId); Event eventResult = callScheduler("Error reserving resources: %s", schedulerEvent, agent); if (eventResult.getData() == null) { return; } } } }
protected void setSecrets(Instance instance, Map<Object, Object> data) { List<SecretReference> secrets = DataAccessor.fieldObjectList(instance, InstanceConstants.FIELD_SECRETS, SecretReference.class, jsonMapper); if (secrets == null || secrets.isEmpty()) { return; } StorageDriver driver = storageDriverDao.findSecretsDriver(instance.getAccountId()); if (driver == null) { return; } String token = tokenService.generateToken(CollectionUtils.asMap("uuid", instance.getUuid()), new Date(System.currentTimeMillis() + 31556926000L)); try { Volume vol = storageDriverDao.createSecretsVolume(instance, driver, token); create(vol, null); } catch (ProcessCancelException e) { // ignore } }
@Override protected Object getAgentResource(ProcessState state, ProcessInstance process, Object dataResource) { Instance instance = getInstance(state); if (!isPod(instance)) { return false; } Long accountId = instance.getAccountId(); List<Long> agentIds = agentInstanceDao.getAgentProvider(SystemLabels.LABEL_AGENT_SERVICE_LABELS_PROVIDER, accountId); Long agentId = agentIds.size() == 0 ? null : agentIds.get(0); if ((instance instanceof Instance) && (agentIds.contains(instance.getAgentId()) || instance.getSystem())) { return null; } if (agentId == null) { if (k8sRequired(instance)) { throw new ExecutionException("Failed to find labels provider", instance); } else { return null; } } return agentId; }
@Override protected void postProcessEvent(EventVO<?> event, Event reply, ProcessState state, ProcessInstance process, Object eventResource, Object dataResource, Object agentResource) { Map<String, String> labels = CollectionUtils.toMap(CollectionUtils.getNestedValue(reply.getData(), "instance", "+data", "+fields", "+labels")); if (labels.size() == 0) { labels = CollectionUtils.toMap(CollectionUtils.getNestedValue(reply.getData(), "instanceHostMap", "instance", "+data", "+fields", "+labels")); } else { CollectionUtils.setNestedValue(CollectionUtils.toMap(reply.getData()), labels, "instanceHostMap", "instance", "+data", "+fields", "+labels"); } Instance instance = getInstance(state); if (labels.size() == 0) { throw new ExecutionException("Failed to find labels for POD", instance); } for (Map.Entry<String, String>label : labels.entrySet()) { labelsService.createContainerLabel(instance.getAccountId(), instance.getId(), label.getKey(), label.getValue()); } } }
@Override public Volume doWithLock() { Volume volume = dockerDao.createDockerVolumeInPool(instance.getAccountId(), dVol.getName(), dVol.getUri(), dVol.getExternalId(), dVol.getDriver(), storagePool, dVol.isBindMount(), instance.getNativeContainer()); return volume; } });
@Override public HandlerResult handle(ProcessState state, ProcessInstance process) { Instance instance = (Instance)state.getResource(); if (!Boolean.TRUE.equals(instance.getSystem())) { return null; } List<Long> agentIds = agentInstanceDao.getAgentProviderIgnoreHealth(SystemLabels.LABEL_AGENT_SERVICE_IPSEC, instance.getAccountId()); for (long agentId : agentIds) { ConfigUpdateRequest request = ConfigUpdateRequest.forResource(Agent.class, agentId); ConfigUpdateItem item = request.addItem("psk"); item.setApply(true); item.setIncrement(false); statusManager.updateConfig(request); } return null; }
@Override public HandlerResult handle(ProcessState state, ProcessInstance process) { Instance instance = (Instance)state.getResource(); if (!InstanceConstants.CONTAINER_LIKE.contains(instance.getKind())) { return null; } Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS); Account account = objectManager.loadResource(Account.class, instance.getAccountId()); Map<Object, Object> data = new HashMap<>(); setAgentVolumes(instance, labels, data); setName(instance, labels, data); setDns(instance, labels, data); setLogConfig(instance, data); setSecrets(instance, data); setSystemLabel(instance, labels); setEnvironmentLabel(labels, account); if (!data.isEmpty()) { return new HandlerResult(data); } return null; }
@Override public HandlerResult handle(ProcessState state, ProcessInstance process) { final Instance instance = (Instance) state.getResource(); List<Service> services = objectManager.find(Service.class, SERVICE.ACCOUNT_ID, instance.getAccountId(), SERVICE.REMOVED, null, SERVICE.SELECTOR_CONTAINER, new Condition(ConditionType.NOTNULL)); for (final Service service : services) { if (sdService.isSelectorContainerMatch(service.getSelectorContainer(), instance)) { lockManager.lock(new ServiceInstanceLock(service, instance), new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { ServiceExposeMap exposeMap = exposeMapDao.createServiceInstanceMap(service, instance, false); if (exposeMap.getState().equalsIgnoreCase(CommonStatesConstants.REQUESTED)) { objectProcessManager.scheduleStandardProcessAsync(StandardProcess.CREATE, exposeMap, null); } } }); } } return null; }