def _CheckCallsForCreateInstanceWithContainer(self, disk,
                                               container_manifest):
     m = self.messages
     metadata = m.Metadata(items=[
         m.Metadata.ItemsValueListEntry(key='gce-container-declaration',
                                        value=containers_utils.DumpYaml(
                                            container_manifest)),
         m.Metadata.ItemsValueListEntry(key='google-logging-enabled',
                                        value='true')
     ])
     self.CheckRequests(
         self.zone_get_request,
         self.cos_images_list_request,
         [(self.compute.instances, 'Insert',
           m.ComputeInstancesInsertRequest(
               instance=m.Instance(
                   canIpForward=False,
                   disks=[self.default_attached_disk, disk],
                   labels=self.default_labels,
                   machineType=self.default_machine_type,
                   metadata=metadata,
                   name='instance-1',
                   networkInterfaces=[self.default_network_interface],
                   scheduling=m.Scheduling(automaticRestart=True),
                   serviceAccounts=[self.default_service_account],
                   tags=self.default_tags),
               project='my-project',
               zone='central2-a',
           ))],
     )
 def _GetInstanceWithStatus(self, status):
   return self.messages.Instance(
       status=status,
       metadata=self.messages.Metadata(items=[
           self.messages.Metadata.ItemsValueListEntry(
               key='gce-container-declaration',
               value=containers_utils.DumpYaml(
                   self.default_container_manifest))
       ]))
 def _GetMetadataRequestWithMetadata(self, metadata):
   return self.messages.ComputeInstancesSetMetadataRequest(
       project=self.Project(),
       zone='central2-a',
       instance='instance-1',
       metadata=self.messages.Metadata(items=[
           self.messages.Metadata.ItemsValueListEntry(
               key='gce-container-declaration',
               value=containers_utils.DumpYaml(metadata))
       ]))
 def _GetInstanceWithManifest(self, manifest=None, disks=None):
   disks = disks or []
   manifest = manifest or {}
   return self.messages.Instance(
       status=self.messages.Instance.StatusValueValuesEnum.RUNNING,
       disks=disks,
       metadata=self.messages.Metadata(items=[
           self.messages.Metadata.ItemsValueListEntry(
               key='gce-container-declaration',
               value=containers_utils.DumpYaml(
                   manifest))
       ]))
 def testDumpYamlHasDisclaimer(self):
     self.assertTrue('# DISCLAIMER' in containers_utils.DumpYaml({}))
  def testNoContainerCommandAndArgs(self):
    messages = self.messages
    with self.Client() as client:
      client.instances.Get.Expect(
          messages.ComputeInstancesGetRequest(
              project=self.Project(), zone='central2-a', instance='instance-1'),
          messages.Instance(metadata=messages.Metadata(items=[
              messages.Metadata.ItemsValueListEntry(
                  key='gce-container-declaration',
                  value=containers_utils.DumpYaml({
                      'spec': {
                          'containers': [{
                              'name': 'instance-1',
                              'image': 'gcr.io/my-docker/test-image',
                              'securityContext': {
                                  'privileged': True
                              },
                          }],
                      }
                  }))
          ])))

      client.instances.SetMetadata.Expect(
          messages.ComputeInstancesSetMetadataRequest(
              project=self.Project(),
              zone='central2-a',
              instance='instance-1',
              metadata=messages.Metadata(items=[
                  messages.Metadata.ItemsValueListEntry(
                      key='gce-container-declaration',
                      value=containers_utils.DumpYaml({
                          'spec': {
                              'containers': [{
                                  'name': 'instance-1',
                                  'image': 'gcr.io/my-docker/test-image',
                                  'securityContext': {
                                      'privileged': True
                                  },
                                  'volumeMounts': [],
                              }],
                              'volumes': []
                          }
                      }))
              ])),
          self._GetOperationMessage(
              self._GetOperationRef('operation-X', 'central2-a'),
              messages.Operation.StatusValueValuesEnum.PENDING))

      client.zoneOperations.Wait.Expect(
          self.messages.ComputeZoneOperationsWaitRequest(
              operation='operation-X',
              zone='central2-a',
              project=self.Project()),
          self._GetOperationMessage(
              self._GetOperationRef('operation-X', 'central2-a'),
              self.messages.Operation.StatusValueValuesEnum.DONE,
              self._GetInstanceRef('instance-1', 'central2-a')))

      client.instances.Get.Expect(
          self.messages.ComputeInstancesGetRequest(
              instance='instance-1', project='fake-project', zone='central2-a'),
          self.messages.Instance(name='instance-1'))

      self._ExpectStop(client)
      self._ExpectStart(client)

      self.Run("""
          compute instances update-container instance-1
            --zone central2-a
            --clear-container-command
            --clear-container-args
          """)
    self.AssertOutputEquals('')
    self.AssertErrContains('Updating specification of container [instance-1]')
    self.AssertErrContains('Stopping instance [instance-1]')
    self.AssertErrContains('Starting instance [instance-1]')
 def _GetMetadataRequest(self):
   return self.messages.ComputeInstancesSetMetadataRequest(
       project=self.Project(),
       zone='central2-a',
       instance='instance-1',
       metadata=self.messages.Metadata(items=[
           self.messages.Metadata.ItemsValueListEntry(
               key='gce-container-declaration',
               value=containers_utils.DumpYaml({
                   'spec': {
                       'containers': [{
                           'name':
                               'instance-1',
                           'image':
                               'container-image',
                           'command': ['container-command'],
                           'args': ['container-arg'],
                           'stdin':
                               True,
                           'tty':
                               False,
                           'securityContext': {
                               'privileged': True
                           },
                           'env': [{
                               'name': 'key1',
                               'value': 'val2'
                           }],
                           'volumeMounts': [{
                               'mountPath': 'mount1',
                               'name': 'host-path-0',
                               'readOnly': True
                           }, {
                               'mountPath': 'mount2',
                               'name': 'host-path-1',
                               'readOnly': False
                           }, {
                               'mountPath': 'tmpfs2',
                               'name': 'tmpfs-2'
                           }]
                       }],
                       'restartPolicy':
                           'Always',
                       'volumes': [{
                           'name': 'tmpfs-0',
                           'hostPath': {
                               'path': 'host-path',
                           },
                       }, {
                           'name': 'tmpfs-1',
                           'emptyDir': {
                               'medium': 'Memory',
                           },
                       }, {
                           'name': 'host-path-0',
                           'hostPath': {
                               'path': 'host1',
                           },
                       }, {
                           'name': 'host-path-1',
                           'hostPath': {
                               'path': 'host2',
                           },
                       }, {
                           'name': 'tmpfs-2',
                           'emptyDir': {
                               'medium': 'Memory',
                           },
                       }],
                   }
               }))
       ]))
 def SetUp(self):
     self.SelectApi(self.api_version)
     m = self.messages
     self.cos_image_name = 'cos-dev-63-8872-76-0'
     self.cos_image_path = ('projects/cos-cloud/global/images/'
                            'cos-dev-63-8872-76-0')
     self.make_requests.side_effect = iter(
         [[
             m.Zone(name='central2-a'),
             m.Zone(name='central2-b'),
             m.Zone(name='central2-c')
         ],
          [
              m.Image(name=self.cos_image_name,
                      selfLink=self.cos_image_path,
                      creationTimestamp='2016-06-06T18:52:15.455-07:00')
          ], []])
     self.cos_images_list_request = [
         (self.compute.images, 'List',
          self.messages.ComputeImagesListRequest(project='cos-cloud')),
     ]
     self.default_attached_disk = m.AttachedDisk(
         autoDelete=True,
         boot=True,
         initializeParams=m.AttachedDiskInitializeParams(
             sourceImage=self.cos_image_path),
         licenses=[],
         mode=m.AttachedDisk.ModeValueValuesEnum.READ_WRITE,
         type=m.AttachedDisk.TypeValueValuesEnum.PERSISTENT)
     self.default_machine_type = (
         '{0}/projects/my-project/zones/central2-a/'
         'machineTypes/n1-standard-1'.format(self.compute_uri))
     self.default_container_manifest = {
         'spec': {
             'containers': [{
                 'name': 'instance-1',
                 'image': 'gcr.io/my-docker/test-image',
                 'securityContext': {
                     'privileged': False
                 },
                 'stdin': False,
                 'tty': False,
                 'volumeMounts': []
             }],
             'restartPolicy':
             'Always',
             'volumes': []
         }
     }
     self.default_labels = m.Instance.LabelsValue(additionalProperties=[
         m.Instance.LabelsValue.AdditionalProperty(
             key='container-vm', value='cos-dev-63-8872-76-0')
     ])
     self.default_metadata = m.Metadata(items=[
         m.Metadata.ItemsValueListEntry(
             key='gce-container-declaration',
             value=containers_utils.DumpYaml(
                 self.default_container_manifest)),
         m.Metadata.ItemsValueListEntry(key='google-logging-enabled',
                                        value='true')
     ])
     self.default_tags = None
     self.default_network_interface = m.NetworkInterface(
         accessConfigs=[
             m.AccessConfig(
                 name='external-nat',
                 type=m.AccessConfig.TypeValueValuesEnum.ONE_TO_ONE_NAT)
         ],
         network=('{0}/projects/my-project/global/networks/default'.format(
             self.compute_uri)))
     self.default_service_account = m.ServiceAccount(
         email='default',
         scopes=[
             'https://www.googleapis.com/auth/devstorage.read_only',
             'https://www.googleapis.com/auth/logging.write',
             'https://www.googleapis.com/auth/monitoring.write',
             'https://www.googleapis.com/auth/pubsub',
             'https://www.googleapis.com/auth/service.management.readonly',
             'https://www.googleapis.com/auth/servicecontrol',
             'https://www.googleapis.com/auth/trace.append'
         ])