1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
// Copyright 2020 The Exonum Team
//
// Licensed 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.

//! Information schema for the runtime dispatcher.

use exonum_crypto::Hash;
use exonum_derive::*;
use exonum_merkledb::{
    access::{Access, AccessExt, AsReadonly},
    Fork, KeySetIndex, MapIndex, ProofMapIndex,
};
use exonum_proto::ProtobufConvert;

use crate::{
    proto::schema::{
        self, details::ModifiedInstanceInfo_MigrationTransition as PbMigrationTransition,
    },
    runtime::{
        migrations::{InstanceMigration, MigrationStatus},
        ArtifactId, ArtifactState, ArtifactStatus, CoreError, ExecutionError, ExecutionFail,
        InstanceId, InstanceQuery, InstanceSpec, InstanceState, InstanceStatus,
    },
};

const ARTIFACTS: &str = "dispatcher_artifacts";
const PENDING_ARTIFACTS: &str = "dispatcher_pending_artifacts";
const INSTANCES: &str = "dispatcher_instances";
const PENDING_INSTANCES: &str = "dispatcher_pending_instances";
const LOCAL_MIGRATION_RESULTS: &str = "dispatcher_local_migration_results";
const INSTANCE_IDS: &str = "dispatcher_instance_ids";

#[derive(Debug)]
pub(super) enum ArtifactAction {
    Deploy(Vec<u8>),
    Unload,
}

/// Information about a modified service instance.
#[derive(Debug, ProtobufConvert, BinaryValue)]
#[protobuf_convert(source = "schema::details::ModifiedInstanceInfo")]
pub(super) struct ModifiedInstanceInfo {
    #[protobuf_convert(with = "MigrationTransition")]
    pub migration_transition: Option<MigrationTransition>,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum MigrationTransition {
    Start,
    Commit,
    Rollback,
}

impl MigrationTransition {
    #[allow(clippy::wrong_self_convention, clippy::trivially_copy_pass_by_ref)]
    fn to_pb(value: &Option<Self>) -> PbMigrationTransition {
        use PbMigrationTransition::*;
        match value {
            None => NONE,
            Some(Self::Start) => START,
            Some(Self::Commit) => COMMIT,
            Some(Self::Rollback) => ROLLBACK,
        }
    }

    fn from_pb(pb: PbMigrationTransition) -> anyhow::Result<Option<Self>> {
        use PbMigrationTransition::*;
        Ok(match pb {
            NONE => None,
            START => Some(Self::Start),
            COMMIT => Some(Self::Commit),
            ROLLBACK => Some(Self::Rollback),
        })
    }
}

#[derive(Debug, Clone, Copy)]
enum MigrationOutcome {
    Rollback,
    Commit(Hash),
}

impl MigrationOutcome {
    fn as_verb(self) -> &'static str {
        match self {
            Self::Rollback => "rollback",
            Self::Commit(_) => "commit",
        }
    }
}

impl From<MigrationOutcome> for MigrationTransition {
    fn from(value: MigrationOutcome) -> Self {
        match value {
            MigrationOutcome::Rollback => Self::Rollback,
            MigrationOutcome::Commit(_) => Self::Commit,
        }
    }
}

/// Schema of the dispatcher, used to store information about pending artifacts / service
/// instances, and to reload artifacts / instances on node restart.
// TODO: Add information about implemented interfaces [ECR-3747]
#[derive(Debug)]
pub struct Schema<T: Access> {
    access: T,
}

impl<T: Access> Schema<T> {
    /// Constructs information schema for the given `access`.
    pub(crate) fn new(access: T) -> Self {
        Self { access }
    }

    /// Returns an artifacts registry indexed by the artifact name.
    pub(crate) fn artifacts(&self) -> ProofMapIndex<T::Base, ArtifactId, ArtifactState> {
        self.access.get_proof_map(ARTIFACTS)
    }

    /// Returns a service instances registry indexed by the instance name.
    pub(crate) fn instances(&self) -> ProofMapIndex<T::Base, str, InstanceState> {
        self.access.get_proof_map(INSTANCES)
    }

    /// Returns a lookup table to map instance ID with the instance name.
    fn instance_ids(&self) -> MapIndex<T::Base, InstanceId, String> {
        self.access.get_map(INSTANCE_IDS)
    }

    /// Returns a pending artifacts queue used to notify the runtime about artifacts
    /// to be deployed.
    fn pending_artifacts(&self) -> KeySetIndex<T::Base, ArtifactId> {
        self.access.get_key_set(PENDING_ARTIFACTS)
    }

    /// Returns a pending instances queue used to notify the runtime about service instances
    /// to be updated.
    fn modified_instances(&self) -> MapIndex<T::Base, str, ModifiedInstanceInfo> {
        self.access.get_map(PENDING_INSTANCES)
    }

    pub(crate) fn local_migration_results(&self) -> MapIndex<T::Base, str, MigrationStatus> {
        self.access.get_map(LOCAL_MIGRATION_RESULTS)
    }

    /// Returns the information about a service instance by its identifier.
    pub fn get_instance<'q>(&self, query: impl Into<InstanceQuery<'q>>) -> Option<InstanceState> {
        let instances = self.instances();
        match query.into() {
            // TODO It makes sense to indexing by identifiers primary. [ECR-3880]
            InstanceQuery::Id(id) => self
                .instance_ids()
                .get(&id)
                .and_then(|instance_name| instances.get(&instance_name)),

            InstanceQuery::Name(instance_name) => instances.get(instance_name),
        }
    }

    /// Returns information about an artifact by its identifier.
    pub fn get_artifact(&self, name: &ArtifactId) -> Option<ArtifactState> {
        self.artifacts().get(name)
    }

    /// Returns result of a locally completed migration for the specified service instance.
    ///
    /// This result is set once the migration script associated with the service instance completes
    /// and is cleared after the migration is flushed or rolled back.
    pub fn local_migration_result(&self, instance_name: &str) -> Option<MigrationStatus> {
        self.local_migration_results().get(instance_name)
    }

    /// Checks if the provided artifact can currently be unloaded. Returns an error if the unloading
    /// is impossible.
    pub fn check_unloading_artifact(&self, artifact: &ArtifactId) -> Result<(), ExecutionError> {
        self.do_check_unloading_artifact(artifact).map(drop)
    }

    fn do_check_unloading_artifact(
        &self,
        artifact: &ArtifactId,
    ) -> Result<ArtifactState, ExecutionError> {
        let state = self.artifacts().get(artifact).ok_or_else(|| {
            let msg = format!(
                "Requested to unload artifact `{}`, which is not deployed",
                artifact
            );
            CoreError::ArtifactNotDeployed.with_description(msg)
        })?;

        if state.status != ArtifactStatus::Active {
            let msg = format!(
                "Requested to unload artifact `{}`, which has non-active status: {}",
                artifact, state.status
            );
            return Err(CoreError::ArtifactNotDeployed.with_description(msg));
        }

        // Check that the artifact has no dependent services. A service is dependent on
        // the artifact if it references it as the current artifact, or its migration target.
        for instance in self.instances().values() {
            if instance.associated_artifact() == Some(artifact) {
                let msg = format!(
                    "Cannot unload artifact `{}`: service `{}` references it \
                     as the current artifact",
                    artifact,
                    instance.spec.as_descriptor()
                );
                return Err(CoreError::CannotUnloadArtifact.with_description(msg));
            }

            let status = instance
                .pending_status
                .as_ref()
                .or_else(|| instance.status.as_ref());
            if let Some(InstanceStatus::Migrating(migration)) = status {
                if migration.target == *artifact {
                    let msg = format!(
                        "Cannot unload artifact `{}`: service `{}` references it \
                         as the data migration target",
                        artifact,
                        instance.spec.as_descriptor()
                    );
                    return Err(CoreError::CannotUnloadArtifact.with_description(msg));
                }
            }
        }

        Ok(state)
    }
}

// `AsReadonly` specialization to ensure that we won't leak mutable schema access.
impl<T: AsReadonly> Schema<T> {
    /// Readonly set of artifacts.
    pub fn service_artifacts(&self) -> ProofMapIndex<T::Readonly, ArtifactId, ArtifactState> {
        self.access.as_readonly().get_proof_map(ARTIFACTS)
    }

    /// Readonly set of service instances.
    pub fn service_instances(&self) -> ProofMapIndex<T::Readonly, str, InstanceState> {
        self.access.as_readonly().get_proof_map(INSTANCES)
    }
}

impl Schema<&Fork> {
    /// Adds artifact specification to the set of the pending artifacts.
    pub(super) fn add_pending_artifact(
        &mut self,
        artifact: &ArtifactId,
        deploy_spec: Vec<u8>,
    ) -> Result<(), ExecutionError> {
        // Check that the artifact is absent among the deployed artifacts.
        if self.artifacts().contains(artifact) {
            let msg = format!("Cannot deploy artifact `{}` twice", artifact);
            return Err(CoreError::ArtifactAlreadyDeployed.with_description(msg));
        }
        // Add artifact to registry with pending status.
        self.artifacts().put(
            artifact,
            ArtifactState::new(deploy_spec, ArtifactStatus::Deploying),
        );
        // Add artifact to pending artifacts queue.
        self.pending_artifacts().insert(artifact);
        Ok(())
    }

    /// Adds artifact specification to the set of the active artifacts.
    pub(super) fn add_active_artifact(
        &mut self,
        artifact: &ArtifactId,
        deploy_spec: Vec<u8>,
    ) -> Result<(), ExecutionError> {
        // Check that the artifact is absent among the deployed artifacts.
        if self.artifacts().contains(artifact) {
            let msg = format!("Cannot deploy artifact `{}` twice", artifact);
            return Err(CoreError::ArtifactAlreadyDeployed.with_description(msg));
        }

        self.artifacts().put(
            artifact,
            ArtifactState::new(deploy_spec, ArtifactStatus::Active),
        );
        Ok(())
    }

    /// Unloads the provided artifact.
    pub(super) fn unload_artifact(&mut self, artifact: &ArtifactId) -> Result<(), ExecutionError> {
        let mut state = self.do_check_unloading_artifact(artifact)?;
        state.status = ArtifactStatus::Unloading;
        self.artifacts().put(artifact, state);
        self.pending_artifacts().insert(artifact);
        Ok(())
    }

    /// Checks preconditions for migration initiation.
    pub(super) fn check_migration_initiation(
        &self,
        new_artifact: &ArtifactId,
        old_service: &str,
    ) -> Result<InstanceState, ExecutionError> {
        // The service should exist.
        let instance_state = self.instances().get(old_service).ok_or_else(|| {
            let msg = format!(
                "Cannot initiate migration for non-existing service `{}`",
                old_service
            );
            CoreError::IncorrectInstanceId.with_description(msg)
        })?;

        // The service should be stopped or frozen. Note that this also checks that
        // the service is not being currently migrated.
        if instance_state.status != Some(InstanceStatus::Stopped)
            && instance_state.status != Some(InstanceStatus::Frozen)
        {
            let msg = format!(
                "Data migration cannot be initiated for service `{}` because is not stopped \
                 or frozen",
                instance_state.spec.as_descriptor()
            );
            return Err(CoreError::InvalidServiceTransition.with_description(msg));
        }

        // There should be no pending status for the service.
        if let Some(pending_status) = instance_state.pending_status {
            let msg = format!(
                "Cannot initiate migration for service `{}` because it has \
                 another state transition in progress ({})",
                old_service, pending_status
            );
            return Err(CoreError::ServicePending.with_description(msg));
        }

        // The new artifact should exist.
        let artifact_state = self.artifacts().get(new_artifact).ok_or_else(|| {
            let msg = format!(
                "The target artifact `{}` for data migration of service `{}` is not deployed",
                new_artifact,
                instance_state.spec.as_descriptor()
            );
            CoreError::UnknownArtifactId.with_description(msg)
        })?;
        // The new artifact should be deployed.
        if artifact_state.status != ArtifactStatus::Active {
            let msg = format!(
                "The target artifact `{}` for data migration of service `{}` is not active",
                new_artifact,
                instance_state.spec.as_descriptor()
            );
            return Err(CoreError::ArtifactNotDeployed.with_description(msg));
        }

        // The new artifact should refer a newer version of the service artifact.
        if !new_artifact.is_upgrade_of(&instance_state.spec.artifact) {
            let msg = format!(
                "The target artifact `{}` for data migration of service `{}` is not an upgrade \
                 of its current artifact `{}`",
                new_artifact,
                instance_state.spec.as_descriptor(),
                instance_state.spec.artifact
            );
            return Err(CoreError::CannotUpgradeService.with_description(msg));
        }

        Ok(instance_state)
    }

    /// Marks the start of data migration for a service. This method does not perform
    /// consistency checks assuming that this call is preceded by `check_migration_initiation`.
    pub(super) fn add_pending_migration(
        &mut self,
        instance_state: InstanceState,
        migration: InstanceMigration,
    ) {
        let pending_status = InstanceStatus::migrating(migration);
        self.add_pending_status(
            instance_state,
            pending_status,
            Some(MigrationTransition::Start),
        )
        .expect("BUG: Cannot add pending service status during migration initialization");
        // Since we've checked in `check_migration_initiation` that the service
        // has no pending status, we assume that it will be added successfully here.
    }

    /// Fast-forwards data migration by bumping the recorded service version.
    /// The entire migration workflow is skipped in this case; the service transitions to
    /// the `Stopped` status and no pending status is added.
    /// The runtime will be notified about the service state when the block is accepted.
    pub(super) fn fast_forward_migration(
        &mut self,
        mut instance_state: InstanceState,
        new_artifact: ArtifactId,
    ) {
        debug_assert!(*instance_state.data_version() <= new_artifact.version);
        instance_state.status = Some(InstanceStatus::Stopped);
        instance_state.data_version = None;
        instance_state.spec.artifact = new_artifact;
        let instance_name = instance_state.spec.name.clone();
        self.instances().put(&instance_name, instance_state);

        let modified_info = ModifiedInstanceInfo {
            migration_transition: None,
        };
        self.modified_instances().put(&instance_name, modified_info);
    }

    fn add_pending_status(
        &mut self,
        mut instance_state: InstanceState,
        pending_status: InstanceStatus,
        migration_transition: Option<MigrationTransition>,
    ) -> Result<(), CoreError> {
        if instance_state.pending_status.is_some() {
            return Err(CoreError::ServicePending);
        }
        instance_state.pending_status = Some(pending_status);
        let instance_name = instance_state.spec.name.clone();
        let modified_info = ModifiedInstanceInfo {
            migration_transition,
        };
        self.instances().put(&instance_name, instance_state);
        self.modified_instances().put(&instance_name, modified_info);
        Ok(())
    }

    fn resolve_ongoing_migration(
        &mut self,
        instance_name: &str,
        outcome: MigrationOutcome,
    ) -> Result<(), ExecutionError> {
        let instance_state = self.instances().get(instance_name).ok_or_else(|| {
            let msg = format!(
                "Cannot {} migration for unknown service `{}`",
                outcome.as_verb(),
                instance_name
            );
            CoreError::IncorrectInstanceId.with_description(msg)
        })?;

        let migration = match instance_state.status {
            Some(InstanceStatus::Migrating(ref migration)) if !migration.is_completed() => {
                migration
            }
            _ => {
                let msg = format!(
                    "Cannot {} migration for service `{}` because it has \
                     no ongoing migration",
                    outcome.as_verb(),
                    instance_state.spec.as_descriptor()
                );
                return Err(CoreError::NoMigration.with_description(msg));
            }
        };

        let new_status = match outcome {
            MigrationOutcome::Rollback => InstanceStatus::Stopped,
            MigrationOutcome::Commit(hash) => {
                let mut migration = migration.to_owned();
                migration.completed_hash = Some(hash);
                InstanceStatus::Migrating(migration)
            }
        };

        self.add_pending_status(instance_state, new_status, Some(outcome.into()))?;
        Ok(())
    }

    /// Saves migration rollback to the database. Returns an error if the rollback breaks
    /// invariants imposed by the migration workflow.
    pub(super) fn add_migration_rollback(
        &mut self,
        instance_name: &str,
    ) -> Result<(), ExecutionError> {
        self.resolve_ongoing_migration(instance_name, MigrationOutcome::Rollback)?;
        self.local_migration_results().remove(instance_name);
        Ok(())
    }

    /// Saves migration commit to the database. Returns an error if the commit breaks
    /// invariants imposed by the migration workflow. Note that an error is *not* returned
    /// if the local migration result contradicts the commit (this is only checked on block commit).
    pub(super) fn add_migration_commit(
        &mut self,
        instance_name: &str,
        hash: Hash,
    ) -> Result<(), ExecutionError> {
        self.resolve_ongoing_migration(instance_name, MigrationOutcome::Commit(hash))
    }

    /// Saves local migration result to the database.
    pub(super) fn add_local_migration_result(
        &mut self,
        instance_name: &str,
        result: MigrationStatus,
    ) {
        self.local_migration_results().put(instance_name, result);
    }

    /// Adds information about a pending service instance to the schema.
    pub(crate) fn initiate_adding_service(
        &mut self,
        spec: InstanceSpec,
    ) -> Result<(), ExecutionError> {
        let artifact_state = self.artifacts().get(&spec.artifact).ok_or_else(|| {
            let msg = format!(
                "Cannot instantiate service `{}` from unknown artifact `{}`",
                spec.as_descriptor(),
                spec.artifact
            );
            CoreError::ArtifactNotDeployed.with_description(msg)
        })?;

        if artifact_state.status != ArtifactStatus::Active {
            let msg = format!(
                "Cannot instantiate service `{}` from non-active artifact `{}` \
                 (artifact status: {})",
                spec.as_descriptor(),
                spec.artifact,
                artifact_state.status
            );
            return Err(CoreError::ArtifactNotDeployed.with_description(msg));
        }

        // Check that the instance name doesn't exist.
        if self.instances().contains(&spec.name) {
            let msg = format!("Service with name `{}` already exists", spec.name);
            return Err(CoreError::ServiceNameExists.with_description(msg));
        }
        // Check that the instance identifier doesn't exist.
        // TODO: revise dispatcher integrity checks [ECR-3743]
        let mut instance_ids = self.instance_ids();
        if instance_ids.contains(&spec.id) {
            let msg = format!("Service with numeric ID {} already exists", spec.id);
            return Err(CoreError::ServiceIdExists.with_description(msg));
        }
        instance_ids.put(&spec.id, spec.name.clone());

        let new_instance = InstanceState::from_raw_parts(spec, None, None, None);
        self.add_pending_status(new_instance, InstanceStatus::Active, None)
            .map_err(From::from)
    }

    /// Adds information about stopping service instance to the schema.
    pub(crate) fn initiate_simple_service_transition(
        &mut self,
        instance_id: InstanceId,
        new_status: InstanceStatus,
    ) -> Result<(), ExecutionError> {
        let verb = match new_status {
            InstanceStatus::Stopped => "stop",
            InstanceStatus::Frozen => "freeze",
            _ => unreachable!(),
        };

        let instance_name = self.instance_ids().get(&instance_id).ok_or_else(|| {
            let msg = format!("Cannot {} unknown service with ID {}", verb, instance_id);
            CoreError::IncorrectInstanceId.with_description(msg)
        })?;

        let state = self
            .instances()
            .get(&instance_name)
            .expect("BUG: Instance identifier exists but the corresponding instance is missing.");

        let check = match new_status {
            InstanceStatus::Stopped => InstanceStatus::can_be_stopped,
            InstanceStatus::Frozen => InstanceStatus::can_be_frozen,
            _ => unreachable!(),
        };

        let current_status = state.status.as_ref();
        if current_status.map_or(false, check) {
            self.add_pending_status(state, new_status, None)
                .map_err(From::from)
        } else {
            let current_status =
                current_status.map_or_else(|| "none".to_owned(), ToString::to_string);
            let msg = format!(
                "Cannot {} service `{}` because the transition is precluded by the current \
                 service status ({})",
                verb,
                state.spec.as_descriptor(),
                current_status
            );
            Err(CoreError::InvalidServiceTransition.with_description(msg))
        }
    }

    /// Adds information about resuming service instance to the schema.
    pub(crate) fn initiate_resuming_service(
        &mut self,
        instance_id: InstanceId,
    ) -> Result<(), ExecutionError> {
        let instance_name = self.instance_ids().get(&instance_id).ok_or_else(|| {
            let msg = format!("Cannot resume service with unknown ID {}", instance_id);
            CoreError::IncorrectInstanceId.with_description(msg)
        })?;

        let mut state = self
            .instances()
            .get(&instance_name)
            .expect("BUG: Instance identifier exists but the corresponding instance is missing.");

        if *state.data_version() != state.spec.artifact.version {
            let msg = format!(
                "Service `{}` has data version ({}) differing from its artifact version (`{}`) \
                 and thus cannot be resumed",
                state.spec.name,
                state.data_version(),
                state.spec.artifact
            );
            return Err(CoreError::CannotResumeService.with_description(msg));
        }

        let current_status = state.status.as_ref();
        if current_status.map_or(false, InstanceStatus::can_be_resumed) {
            state.data_version = None;
            self.add_pending_status(state, InstanceStatus::Active, None)
                .map_err(From::from)
        } else {
            let current_status =
                current_status.map_or_else(|| "none".to_owned(), ToString::to_string);
            let msg = format!(
                "Cannot resume service `{}` because the transition is precluded by the current \
                 service status ({})",
                state.spec.as_descriptor(),
                current_status
            );
            Err(CoreError::InvalidServiceTransition.with_description(msg))
        }
    }

    /// Makes pending artifacts and instances active.
    pub(super) fn activate_pending(&mut self) {
        // Activate pending artifacts.
        let mut artifacts = self.artifacts();
        for artifact in &self.pending_artifacts() {
            let mut state = artifacts
                .get(&artifact)
                .expect("Artifact marked as pending is not saved in `artifacts`");

            match state.status {
                ArtifactStatus::Deploying => {
                    state.status = ArtifactStatus::Active;
                    artifacts.put(&artifact, state);
                }
                ArtifactStatus::Unloading => {
                    artifacts.remove(&artifact);
                }
                _ => { /* should be unreachable */ }
            }
        }

        // Commit new statuses for pending instances.
        let mut instances = self.instances();
        for instance in self.modified_instances().keys() {
            let mut state = instances
                .get(&instance)
                .expect("BUG: Instance marked as modified is not saved in `instances`");
            if state.pending_status.is_some() {
                state.commit_pending_status();
                instances.put(&instance, state);
            }
        }
    }

    /// Takes pending artifacts from queue.
    pub(super) fn take_pending_artifacts(&mut self) -> Vec<(ArtifactId, ArtifactAction)> {
        let mut index = self.pending_artifacts();
        let artifacts = self.artifacts();
        let pending_artifacts = index
            .iter()
            .map(|artifact| {
                let action = if let Some(state) = artifacts.get(&artifact) {
                    debug_assert_eq!(state.status, ArtifactStatus::Active);
                    ArtifactAction::Deploy(state.deploy_spec)
                } else {
                    ArtifactAction::Unload
                };
                (artifact, action)
            })
            .collect();
        index.clear();
        pending_artifacts
    }

    /// Takes modified service instances from queue. This method should be called
    /// after new service statuses are committed (e.g., in `commit_block`).
    pub(super) fn take_modified_instances(&mut self) -> Vec<(InstanceState, ModifiedInstanceInfo)> {
        let mut modified_instances = self.modified_instances();
        let instances = self.instances();

        let output = modified_instances
            .iter()
            .map(|(instance_name, info)| {
                let state = instances
                    .get(&instance_name)
                    .expect("BUG: Instance marked as modified is not saved in `instances`");
                (state, info)
            })
            .collect();
        modified_instances.clear();

        output
    }

    /// Marks a service migration as completed. This sets the service status from `Migrating`
    /// to `Stopped`, bumps its artifact version and removes the local migration result.
    pub(super) fn complete_migration(&mut self, instance_name: &str) -> Result<(), ExecutionError> {
        let mut instance_state = self.instances().get(instance_name).ok_or_else(|| {
            let msg = format!(
                "Cannot complete migration for unknown service `{}`",
                instance_name
            );
            CoreError::IncorrectInstanceId.with_description(msg)
        })?;

        let end_version = match instance_state.status {
            Some(InstanceStatus::Migrating(ref migration)) if migration.is_completed() => {
                migration.end_version.clone()
            }
            _ => {
                let msg = format!(
                    "Cannot complete migration for service `{}` because it has no migration \
                     with committed outcome",
                    instance_name
                );
                return Err(CoreError::NoMigration.with_description(msg));
            }
        };

        self.local_migration_results().remove(instance_name);
        debug_assert!(*instance_state.data_version() < end_version);
        instance_state.data_version = Some(end_version);
        self.add_pending_status(instance_state, InstanceStatus::Stopped, None)
            .map_err(From::from)
    }
}

/// Removes local migration result for specified service.
#[doc(hidden)]
pub fn remove_local_migration_result(fork: &Fork, service_name: &str) {
    Schema::new(fork)
        .local_migration_results()
        .remove(service_name);
}