Search in sources :

Example 56 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class SimpleCertificateAuthority method signCertificate.

private static Certificate signCertificate(X500Name signer, PrivateKey signerPrivateKey, X500Name subject, SubjectPublicKeyInfo subjectPublicKeyInfo) throws OpsException {
    try {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(SIGNATURE_ALGORITHM);
        AlgorithmIdentifier digestAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        long days = 3650;
        long now = System.currentTimeMillis();
        Date notBefore = new Date(now - ONE_DAY);
        Date notAfter = new Date(notBefore.getTime() + (days * ONE_DAY));
        BigInteger serialNumber;
        synchronized (SimpleCertificateAuthority.class) {
            long nextSerialNumber = System.currentTimeMillis();
            serialNumber = BigInteger.valueOf(nextSerialNumber);
        }
        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(signer, serialNumber, notBefore, notAfter, subject, subjectPublicKeyInfo);
        // {
        // boolean isCritical = false;
        // certificateBuilder.addExtension(X509Extensions.SubjectKeyIdentifier, isCritical,
        // csr.getSubjectPublicKeyInfo());
        // }
        AsymmetricKeyParameter caPrivateKeyParameters = PrivateKeyFactory.createKey(signerPrivateKey.getEncoded());
        ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digestAlgId).build(caPrivateKeyParameters);
        X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
        Certificate certificate = certificateHolder.toASN1Structure();
        return certificate;
    } catch (OperatorCreationException e) {
        throw new OpsException("Error signing certificate", e);
    } catch (IOException e) {
        throw new OpsException("Error signing certificate", e);
    }
}
Also used : OpsException(org.platformlayer.ops.OpsException) ContentSigner(org.bouncycastle.operator.ContentSigner) IOException(java.io.IOException) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) Date(java.util.Date) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 57 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class PlatformLayerTestContext method waitForJobComplete.

public JobData waitForJobComplete(JobData job, TimeSpan timeout) throws OpsException, IOException {
    TypedPlatformLayerClient client = getTypedClient();
    PlatformLayerKey jobKey = job.key;
    long startedAt = System.currentTimeMillis();
    while (true) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new IllegalStateException("Interrupted", e);
        }
        if (timeout != null && timeout.hasTimedOut(startedAt)) {
            throw new OpsException("Timeout waiting for job completion");
        }
        // TODO: We really need a "get job status" function
        JobData found = null;
        for (JobData candidate : client.listJobs().getJobs()) {
            if (jobKey.equals(candidate.getJobKey())) {
                found = candidate;
            }
        }
        if (found == null) {
            // Assume completed?
            throw new IllegalStateException("Job not found in job list");
        }
        JobExecutionList executions = client.listJobExecutions(job.getJobKey().getItemIdString());
        JobExecutionData foundExecution = null;
        for (JobExecutionData candidate : executions) {
            if (jobKey.equals(candidate.getJobKey())) {
                foundExecution = candidate;
            }
        }
        if (foundExecution == null) {
            throw new IllegalStateException("Execution not found in execution list");
        }
        JobState state = foundExecution.getState();
        switch(state) {
            case FAILED:
            case SUCCESS:
                System.out.println("Job completed; state=" + state);
                return found;
            case RUNNING:
                System.out.println("Continuing to wait for " + job.key + "; state=" + state);
                break;
            default:
                throw new IllegalStateException("Unexpected state: " + state + " for " + job.key);
        }
    }
}
Also used : TypedPlatformLayerClient(org.platformlayer.TypedPlatformLayerClient) OpsException(org.platformlayer.ops.OpsException) JobExecutionData(org.platformlayer.jobs.model.JobExecutionData) JobState(org.platformlayer.jobs.model.JobState) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) JobData(org.platformlayer.jobs.model.JobData) JobExecutionList(org.platformlayer.jobs.model.JobExecutionList)

Example 58 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class PkiServiceImpl method signCsr.

@Override
public List<X509Certificate> signCsr(ProjectEntity project, String csr) throws OpsException {
    CertificateAndKey projectPki;
    try {
        projectPki = repository.getProjectPki(project);
    } catch (RepositoryException e) {
        throw new OpsException("Error getting project PKI info", e);
    }
    SimpleCertificateAuthority ca = new SimpleCertificateAuthority();
    ca.caCertificate = projectPki.getCertificateChain();
    ca.caPrivateKey = projectPki.getPrivateKey();
    X509Certificate certificate = ca.signCsr(csr);
    List<X509Certificate> chain = Lists.newArrayList();
    chain.add(certificate);
    for (X509Certificate cert : projectPki.getCertificateChain()) {
        chain.add(cert);
    }
    return chain;
}
Also used : OpsException(org.platformlayer.ops.OpsException) SimpleCertificateAuthority(org.platformlayer.crypto.SimpleCertificateAuthority) RepositoryException(org.platformlayer.RepositoryException) CertificateAndKey(com.fathomdb.crypto.CertificateAndKey) X509Certificate(java.security.cert.X509Certificate)

Example 59 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class OperationWorker method doOperation.

Object doOperation() throws OpsException {
    final Action action = activeJob.getAction();
    final PlatformLayerKey targetItemKey = activeJob.getTargetItemKey();
    RenameThread rename = new RenameThread(action.getClass().getSimpleName() + " " + targetItemKey);
    try {
        OpsContextBuilder opsContextBuilder = opsSystem.getInjector().getInstance(OpsContextBuilder.class);
        final ProjectAuthorization project = activeJob.getProjectAuthorization();
        final OpsContext opsContext = opsContextBuilder.buildOpsContext(activeJob);
        final ServiceType serviceType = activeJob.getServiceType();
        final ServiceProvider serviceProvider = opsSystem.getServiceProvider(serviceType);
        try {
            return OpsContext.runInContext(opsContext, new CheckedCallable<Object, Exception>() {

                @Override
                public Object call() throws Exception {
                    log.info("Starting job");
                    activeJob.setState(JobState.RUNNING);
                    ItemBase item;
                    ManagedItemRepository repository = opsSystem.getManagedItemRepository();
                    try {
                        boolean fetchTags = true;
                        item = repository.getManagedItem(targetItemKey, fetchTags, SecretProvider.from(project));
                    } catch (RepositoryException e) {
                        throw new OpsException("Error reading item from repository", e);
                    }
                    if (item == null) {
                        throw new WebApplicationException(404);
                    }
                    List<Object> scopeItems = Lists.newArrayList();
                    addActionScopeItems(action, item, scopeItems);
                    Object controller = serviceProvider.getController(item);
                    scopeItems.add(item);
                    scopeItems.add(action);
                    BindingScope scope = BindingScope.push(scopeItems);
                    opsContext.recurseOperation(scope, controller);
                    // TODO: Should we run a verify operation before -> ACTIVE??
                    // (we need to fix the states as well)
                    ManagedItemState newState = finishAction(action, scope);
                    if (newState != null) {
                        repository.changeState(targetItemKey, newState);
                        item.state = newState;
                    }
                    log.info("Job finished with SUCCESS");
                    activeJob.setState(JobState.SUCCESS);
                    return null;
                }

                private ManagedItemState finishAction(Action action, BindingScope scope) throws OpsException {
                    ManagedItemState newState = null;
                    if (action instanceof ConfigureAction) {
                        newState = ManagedItemState.ACTIVE;
                    }
                    if (action instanceof ValidateAction) {
                    // TODO: Change state to healthy??
                    }
                    if (action instanceof DeleteAction) {
                        newState = ManagedItemState.DELETED;
                    }
                    if (action instanceof BackupAction) {
                        BackupContext backupContext = scope.getInstance(BackupContext.class);
                        backupContext.writeDescriptor();
                    }
                    return newState;
                }

                private void addActionScopeItems(Action action, ItemBase item, List<Object> scopeItems) throws OpsException {
                    if (action instanceof BackupAction) {
                        // TODO: Don't hard-code this
                        BackupHelpers backupHelpers = opsSystem.getInjector().getInstance(BackupHelpers.class);
                        BackupContext backupContext = backupHelpers.createBackupContext(item);
                        scopeItems.add(backupContext);
                    }
                }
            });
        } catch (Throwable e) {
            log.warn("Error running operation", e);
            log.warn("Job finished with FAILED");
            // boolean isDone = false; // We will retry
            activeJob.setState(JobState.FAILED);
            TimeSpan retry = null;
            HasRetryInfo retryInfo = ExceptionHelpers.findRetryInfo(e);
            if (retryInfo != null) {
                retry = retryInfo.getRetry();
            }
            if (retry == null) {
                // TODO: Eventually give up??
                retry = ApplicationMode.isDevelopment() ? TimeSpan.ONE_MINUTE : TimeSpan.FIVE_MINUTES;
            }
            // TODO: State transition??
            // managedItem.setState(ManagedItemState.ACTIVE, true);
            log.warn("Scheduling retry in " + retry);
            activeJob.enqueueRetry(retry);
            return null;
        } finally {
            try {
                activeJob.recordJobEnd();
            } catch (OpsException e) {
                log.error("Error recording job in registry", e);
            }
        }
    } finally {
        IoUtils.safeClose(rename);
    }
}
Also used : ValidateAction(org.platformlayer.core.model.ValidateAction) ConfigureAction(org.platformlayer.core.model.ConfigureAction) DeleteAction(org.platformlayer.core.model.DeleteAction) BackupAction(org.platformlayer.core.model.BackupAction) Action(org.platformlayer.core.model.Action) OpsException(org.platformlayer.ops.OpsException) WebApplicationException(javax.ws.rs.WebApplicationException) BackupHelpers(org.platformlayer.ops.backups.BackupHelpers) ManagedItemRepository(org.platformlayer.xaas.repository.ManagedItemRepository) OpsContext(org.platformlayer.ops.OpsContext) TimeSpan(com.fathomdb.TimeSpan) BackupAction(org.platformlayer.core.model.BackupAction) ServiceType(org.platformlayer.ids.ServiceType) BackupContext(org.platformlayer.ops.backups.BackupContext) HasRetryInfo(org.platformlayer.exceptions.HasRetryInfo) List(java.util.List) BindingScope(org.platformlayer.ops.BindingScope) ConfigureAction(org.platformlayer.core.model.ConfigureAction) ItemBase(org.platformlayer.core.model.ItemBase) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) RepositoryException(org.platformlayer.RepositoryException) RepositoryException(org.platformlayer.RepositoryException) OpsException(org.platformlayer.ops.OpsException) WebApplicationException(javax.ws.rs.WebApplicationException) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) ProjectAuthorization(org.platformlayer.model.ProjectAuthorization) DeleteAction(org.platformlayer.core.model.DeleteAction) ValidateAction(org.platformlayer.core.model.ValidateAction) ManagedItemState(org.platformlayer.core.model.ManagedItemState)

Example 60 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class OpsContextBuilder method buildOpsContext.

public OpsContext buildOpsContext(ActiveJobExecution activeJob) throws OpsException {
    ServiceType serviceType = activeJob.getServiceType();
    ProjectAuthorization projectAuthz = activeJob.getProjectAuthorization();
    List<ProjectAuthorization> projects = Lists.newArrayList();
    // .getProject();
    ProjectAuthorization runAsProject = projectAuthz;
    projects.add(runAsProject);
    MultitenantConfiguration multitenant = opsSystem.getMultitenantConfiguration();
    if (multitenant != null) {
        ProjectAuthorization masterProject = multitenant.getMasterProject();
        if (runAsProject.getName().equals(masterProject.getName())) {
            // We're in the master project
            multitenant = null;
        } else {
            runAsProject = masterProject;
            projects.add(runAsProject);
        }
    }
    TypedPlatformLayerClient defaultClient = buildClient(runAsProject);
    FederationConfiguration federationMapConfig = FederatedPlatformLayerClient.buildFederationConfiguration(defaultClient);
    FederationMap federationMap = new FederationMap(httpStrategy, mapper, federationMapConfig);
    if (multitenant != null) {
        // .getProject();
        ProjectAuthorization localProject = projectAuthz;
        TypedPlatformLayerClient localClient = buildClient(localProject);
        FederationKey host = FederationKey.LOCAL;
        ProjectId project = localClient.getProject();
        FederationMapping mapKey = new FederationMapping(host, project);
        federationMap.addMapping(mapKey, localClient);
        for (PlatformLayerKey mappedService : multitenant.getMappedItems()) {
            FederationMap.Rule rule = new FederationMap.Rule();
            rule.mappedItems = mappedService;
            rule.targetKey = mapKey;
            federationMap.addRule(rule);
        }
    }
    ProjectId runAsProjectId = new ProjectId(runAsProject.getName());
    PlatformLayerClient platformLayerClient;
    if (federationMap.isEmpty()) {
        platformLayerClient = defaultClient;
    } else {
        federationMap.addDefault(defaultClient);
        platformLayerClient = FederatedPlatformLayerClient.build(runAsProjectId, federationMap);
    }
    ServiceConfiguration serviceConfiguration = new ServiceConfiguration(runAsProjectId, serviceType);
    ServiceAuthorization serviceAuthorization;
    try {
        serviceAuthorization = serviceAuthorizationService.findServiceAuthorization(serviceType, runAsProjectId);
        // }
        if (serviceAuthorization == null) {
            serviceAuthorization = new ServiceAuthorization();
            serviceAuthorization.serviceType = serviceConfiguration.getServiceType().getKey();
        }
    } catch (RepositoryException e) {
        throw new OpsException("Error reading from repository", e);
    }
    // OpsConfig opsConfig = OpsConfig.build(serviceAuthorization);
    // UserInfo userInfo = new SimpleUserInfo(auth, opsConfig);
    OpsContext opsContext = new OpsContext(opsSystem, activeJob, serviceConfiguration, platformLayerClient, projects);
    return opsContext;
}
Also used : TypedPlatformLayerClient(org.platformlayer.TypedPlatformLayerClient) OpsException(org.platformlayer.ops.OpsException) ProjectId(org.platformlayer.ids.ProjectId) FederationMap(org.platformlayer.federation.FederationMap) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) RepositoryException(org.platformlayer.RepositoryException) OpsContext(org.platformlayer.ops.OpsContext) MultitenantConfiguration(org.platformlayer.ops.MultitenantConfiguration) FederationKey(org.platformlayer.ids.FederationKey) ServiceAuthorization(org.platformlayer.xaas.model.ServiceAuthorization) DirectPlatformLayerClient(org.platformlayer.ops.DirectPlatformLayerClient) FederatedPlatformLayerClient(org.platformlayer.federation.FederatedPlatformLayerClient) PlatformLayerClient(org.platformlayer.PlatformLayerClient) TypedPlatformLayerClient(org.platformlayer.TypedPlatformLayerClient) FederationConfiguration(org.platformlayer.federation.model.FederationConfiguration) ServiceConfiguration(org.platformlayer.ops.ServiceConfiguration) ServiceType(org.platformlayer.ids.ServiceType) ProjectAuthorization(org.platformlayer.model.ProjectAuthorization) FederationMapping(org.platformlayer.federation.FederationMapping)

Aggregations

OpsException (org.platformlayer.ops.OpsException)142 IOException (java.io.IOException)39 File (java.io.File)19 ItemBase (org.platformlayer.core.model.ItemBase)19 RepositoryException (org.platformlayer.RepositoryException)18 PlatformLayerKey (org.platformlayer.core.model.PlatformLayerKey)17 Handler (org.platformlayer.ops.Handler)17 Tag (org.platformlayer.core.model.Tag)16 Command (org.platformlayer.ops.Command)16 Machine (org.platformlayer.ops.Machine)13 TagChanges (org.platformlayer.core.model.TagChanges)11 OpsTarget (org.platformlayer.ops.OpsTarget)11 TimeoutException (java.util.concurrent.TimeoutException)10 OpenstackException (org.openstack.client.OpenstackException)10 OpsContext (org.platformlayer.ops.OpsContext)10 X509Certificate (java.security.cert.X509Certificate)9 InetAddress (java.net.InetAddress)8 ProjectId (org.platformlayer.ids.ProjectId)8 ProcessExecution (org.platformlayer.ops.process.ProcessExecution)8 List (java.util.List)7