Update the logic for creating the container name for toolbox.

Starting from COS-97, COS started using containerd for creating the
toolbox container. For creating the container name, we use a combination
of username+container_image+container_image_tag. In containerd, there is
a validation that the container name should not exceed 76 characters.
However, it is possible that when the project name where the container
is hosted is long, then the container name created can exceed 76
characters.

Instead of using username+container_image+container_image_tag, we can
use username+container_image_256_hash_prefix.

BUG=b/236409342
TEST=locally ran the script to see that toolbox runs fine when using
long username/project_name/container_image_tag.
RELEASE_NOTE=Fixed the bug in toolbox where long project name/container
image tag can fail to run the toolbox container.

Change-Id: Ife3e696559cca6e18a8744e6ba47f3a8a2a67963
diff --git a/toolbox b/toolbox
index 14c90b5..46fe4e5 100755
--- a/toolbox
+++ b/toolbox
@@ -47,7 +47,7 @@
 machinename=$(echo "${USER}-${TOOLBOX_DOCKER_IMAGE}-${TOOLBOX_DOCKER_TAG}" | sed -r 's/[^a-zA-Z0-9_.-]/_/g')
 machinepath="${TOOLBOX_DIRECTORY}/${machinename}"
 osrelease="${machinepath}/etc/os-release"
-if [ ! -f ${osrelease} ] || systemctl is-failed -q ${machinename} ; then
+if [ ! -f ${osrelease} ] ; then
 	sudo mkdir -p "${machinepath}"
 	sudo mkdir -p "${TOOLBOX_TEMP_DIR}"
 	sudo chown ${USER}: "${machinepath}"
@@ -70,11 +70,15 @@
 		fi
 		sudo ctr image pull "${user_flags[@]}" "${TOOLBOX_DOCKER_IMAGE}:${TOOLBOX_DOCKER_TAG}"
 	fi
-	sudo ctr containers create "${TOOLBOX_DOCKER_IMAGE}:${TOOLBOX_DOCKER_TAG}" ${machinename} /bin/true
-	sudo ctr snapshot mounts "${TOOLBOX_TEMP_DIR}" ${machinename} | xargs sudo
+	# The below command is finding the short SHA256 prefix of the container
+	# image.
+	container256hash=$(sudo ctr image ls | grep "${TOOLBOX_DOCKER_IMAGE}:${TOOLBOX_DOCKER_TAG}" | awk '{ print $3 }' | cut -d':' -f2 | cut -c-12)
+	containername=$(echo "${USER}-${container256hash}" | sed -r 's/[^a-zA-Z0-9_.-]/_/g')
+	sudo ctr containers create "${TOOLBOX_DOCKER_IMAGE}:${TOOLBOX_DOCKER_TAG}" ${containername} /bin/true
+	sudo ctr snapshot mounts "${TOOLBOX_TEMP_DIR}" ${containername} | xargs sudo
 	sudo rsync -a "${TOOLBOX_TEMP_DIR}/" "${machinepath}"
 	sudo umount "${TOOLBOX_TEMP_DIR}"
-	sudo ctr container rm ${machinename}
+	sudo ctr container rm ${containername}
 	sudo rm -rf "${TOOLBOX_TEMP_DIR}"
 	sudo touch ${osrelease}
 fi