summaryrefslogtreecommitdiffstats
path: root/configserver/src/main/java/com/yahoo/vespa/config/server/deploy/Deployment.java
blob: b04b00b8223ead35f10f9c37998ca5b834045df2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.deploy;

import com.yahoo.component.Version;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.provision.HostFilter;
import com.yahoo.config.provision.Provisioner;
import com.yahoo.log.LogLevel;
import com.yahoo.path.Path;
import com.yahoo.transaction.NestedTransaction;
import com.yahoo.transaction.Transaction;
import com.yahoo.vespa.config.server.tenant.ActivateLock;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.config.server.TimeoutBudget;
import com.yahoo.vespa.config.server.http.InternalServerException;
import com.yahoo.vespa.config.server.session.LocalSession;
import com.yahoo.vespa.config.server.session.LocalSessionRepo;
import com.yahoo.vespa.config.server.session.PrepareParams;
import com.yahoo.vespa.config.server.session.Session;
import com.yahoo.vespa.config.server.session.SilentDeployLogger;

import java.time.Clock;
import java.time.Duration;
import java.util.Optional;
import java.util.logging.Logger;

/**
 * The process of deploying an application.
 * Deployments are created by a {@link ApplicationRepository}.
 * Instances of this are not multithread safe.
 *
 * @author lulf
 * @author bratseth
 */
public class Deployment implements com.yahoo.config.provision.Deployment {

    private static final Logger log = Logger.getLogger(Deployment.class.getName());

    /** The session containing the application instance to activate */
    private final LocalSession session;
    private final LocalSessionRepo localSessionRepo;
    /** The path to the tenant, or null if not available (only used during prepare) */
    private final Path tenantPath;
    private final Optional<Provisioner> hostProvisioner;
    private final ActivateLock activateLock;
    private final Duration timeout;
    private final Clock clock;
    private final DeployLogger logger = new SilentDeployLogger();
    
    /** The Vespa version this application should run on */
    private final Version version;

    private boolean prepared = false;
    
    /** Whether this model should be validated (only takes effect if prepared=false) */
    private boolean validate;

    private boolean ignoreLockFailure = false;
    private boolean ignoreSessionStaleFailure = false;

    private Deployment(LocalSession session, LocalSessionRepo localSessionRepo, Path tenantPath,
                       Optional<Provisioner> hostProvisioner, ActivateLock activateLock,
                       Duration timeout, Clock clock, boolean prepared, boolean validate, Version version) {
        this.session = session;
        this.localSessionRepo = localSessionRepo;
        this.tenantPath = tenantPath;
        this.hostProvisioner = hostProvisioner;
        this.activateLock = activateLock;
        this.timeout = timeout;
        this.clock = clock;
        this.prepared = prepared;
        this.validate = validate;
        this.version = version;
    }

    public static Deployment unprepared(LocalSession session, LocalSessionRepo localSessionRepo, Path tenantPath,
                                        Optional<Provisioner> hostProvisioner, ActivateLock activateLock,
                                        Duration timeout, Clock clock, boolean validate, Version version) {
        return new Deployment(session, localSessionRepo, tenantPath, hostProvisioner, activateLock,
                              timeout, clock, false, validate, version);
    }

    public static Deployment prepared(LocalSession session, LocalSessionRepo localSessionRepo,
                                      Optional<Provisioner> hostProvisioner, ActivateLock activateLock,
                                      Duration timeout, Clock clock) {
        return new Deployment(session, localSessionRepo, null, hostProvisioner, activateLock,
                              timeout, clock, true, true, session.getVespaVersion());
    }

    public Deployment setIgnoreLockFailure(boolean ignoreLockFailure) {
        this.ignoreLockFailure = ignoreLockFailure;
        return this;
    }

    public Deployment setIgnoreSessionStaleFailure(boolean ignoreSessionStaleFailure) {
        this.ignoreSessionStaleFailure = ignoreSessionStaleFailure;
        return this;
    }

    /** Prepares this. This does nothing if this is already prepared */
    @Override
    public void prepare() {
        if (prepared) return;
        TimeoutBudget timeoutBudget = new TimeoutBudget(clock, timeout);

        session.prepare(logger,
                        new PrepareParams.Builder().applicationId(session.getApplicationId())
                                                   .timeoutBudget(timeoutBudget)
                                                   .ignoreValidationErrors( ! validate)
                                                   .vespaVersion(version.toString())
                                                   .build(),
                        Optional.empty(),
                        tenantPath);
        this.prepared = true;
    }

    /** Activates this. If it is not already prepared, this will call prepare first. */
    @Override
    public void activate() {
        if (! prepared)
            prepare();

        TimeoutBudget timeoutBudget = new TimeoutBudget(clock, timeout);
        long sessionId = session.getSessionId();
        validateSessionStatus(session);
        try {
            log.log(LogLevel.DEBUG, "Trying to acquire lock " + activateLock + " for session " + sessionId);
            boolean acquired = activateLock.acquire(timeoutBudget, ignoreLockFailure);
            if ( ! acquired) {
                log.log(LogLevel.DEBUG, "Acquiring " + activateLock + " for session " + sessionId + " returned false");
            }

            log.log(LogLevel.DEBUG, "Lock acquired " + activateLock + " for session " + sessionId);
            NestedTransaction transaction = new NestedTransaction();
            transaction.add(deactivateCurrentActivateNew(localSessionRepo.getActiveSession(session.getApplicationId()), session, ignoreSessionStaleFailure));

            if (hostProvisioner.isPresent()) {
                hostProvisioner.get().activate(transaction, session.getApplicationId(), session.getProvisionInfo().getHosts());
            }
            transaction.commit();
            session.waitUntilActivated(timeoutBudget);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new InternalServerException("Error activating application", e);
        } finally {
            log.log(LogLevel.DEBUG, "Trying to release lock " + activateLock + " for session " + sessionId);
            activateLock.release();
            log.log(LogLevel.DEBUG, "Lock released " + activateLock + " for session " + sessionId);
        }
        log.log(LogLevel.INFO, session.logPre() + "Session " + sessionId + 
                               " activated successfully using " +
                               ( hostProvisioner.isPresent() ? hostProvisioner.get() : "no host provisioner" ) +
                               ". Config generation " + session.getMetaData().getGeneration());
    }

    /**
     * Request a restart of services of this application on hosts matching the filter.
     * This is sometimes needed after activation, but can also be requested without
     * doing prepare and activate in the same session.
     */
    public void restart(HostFilter filter) {
        hostProvisioner.get().restart(session.getApplicationId(), filter);
    }

    /** Exposes the session of this for testing only */
    public LocalSession session() { return session; }
    
    private long validateSessionStatus(LocalSession localSession) {
        long sessionId = localSession.getSessionId();
        if (Session.Status.NEW.equals(localSession.getStatus())) {
            throw new IllegalStateException(localSession.logPre() + "Session " + sessionId + " is not prepared");
        } else if (Session.Status.ACTIVATE.equals(localSession.getStatus())) {
            throw new IllegalStateException(localSession.logPre() + "Session " + sessionId + " is already active");
        }
        return sessionId;
    }

    private Transaction deactivateCurrentActivateNew(LocalSession currentActiveSession, LocalSession session, boolean ignoreStaleSessionFailure) {
        Transaction transaction = session.createActivateTransaction();
        if (isValidSession(currentActiveSession)) {
            checkIfActiveHasChanged(session, currentActiveSession, ignoreStaleSessionFailure);
            checkIfActiveIsNewerThanSessionToBeActivated(session.getSessionId(), currentActiveSession.getSessionId());
            transaction.add(currentActiveSession.createDeactivateTransaction().operations());
        }
        return transaction;
    }

    private boolean isValidSession(LocalSession session) {
        return session != null;
    }

    private void checkIfActiveHasChanged(LocalSession session, LocalSession currentActiveSession, boolean ignoreStaleSessionFailure) {
        long activeSessionAtCreate = session.getActiveSessionAtCreate();
        log.log(LogLevel.DEBUG, currentActiveSession.logPre() + "active session id at create time=" + activeSessionAtCreate);
        if (activeSessionAtCreate == 0) return; // No active session at create

        long sessionId = session.getSessionId();
        long currentActiveSessionSessionId = currentActiveSession.getSessionId();
        log.log(LogLevel.DEBUG, currentActiveSession.logPre() + "sessionId=" + sessionId + 
                                ", current active session=" + currentActiveSessionSessionId);
        if (currentActiveSession.isNewerThan(activeSessionAtCreate) &&
                currentActiveSessionSessionId != sessionId) {
            String errMsg = currentActiveSession.logPre()+"Cannot activate session " +
                            sessionId + " because the currently active session (" +
                            currentActiveSessionSessionId + ") has changed since session " + sessionId +
                            " was created (was " + activeSessionAtCreate + " at creation time)";
            if (ignoreStaleSessionFailure) {
                log.warning(errMsg + " (Continuing because of force.)");
            } else {
                throw new IllegalStateException(errMsg);
            }
        }
    }

    // As of now, config generation is based on session id, and config generation must be an monotonically
    // increasing number
    private void checkIfActiveIsNewerThanSessionToBeActivated(long sessionId, long currentActiveSessionId) {
        if (sessionId < currentActiveSessionId) {
            throw new IllegalArgumentException("It is not possible to activate session " + sessionId +
                                               ", because it is older than current active session (" + 
                                               currentActiveSessionId + ")");
        }
    }

}