Index: trunk/Nebulous-Server/lib/Nebulous/Server.pm
===================================================================
--- trunk/Nebulous-Server/lib/Nebulous/Server.pm	(revision 39926)
+++ trunk/Nebulous-Server/lib/Nebulous/Server.pm	(revision 41172)
@@ -13,7 +13,15 @@
 use base qw( Class::Accessor::Fast );
 
+use Carp;
+
 use Cache::Memcached;
 use DBI;
+
+## for gentoo:
 use Digest::SHA1 qw( sha1_hex );
+
+## for ubuntu:
+# use Digest::SHA qw( sha1_hex );
+
 use Fcntl ':mode';
 use File::Basename qw( basename dirname fileparse );
@@ -77,6 +85,6 @@
         Cache::Memcached->new({
 	    servers => $config->memcached_servers,
-       })
-    );
+			      })
+	);
 #    $self->cache->set("foo", "bar") or die "set failed";
 #    $self->cache->get("foo") or die "get failed";
@@ -215,4 +223,6 @@
 }
 
+my $get_storage_volume_calls = 0;
+
 sub create_object
 {
@@ -252,6 +262,5 @@
     # the key's volume can't be validiated on input for this method so we have
     # to check it after parsing the key
-    if (defined $vol_name
-        and not $self->_is_valid_volume_name($key, $key->volume)) {
+    if (defined $vol_name and not $self->_is_valid_volume_name($key, $key->volume)) {
         unless ($key->hard_volume) {
             $log->warn( "$vol_name is not a known volume name" );
@@ -262,4 +271,6 @@
     }
         
+    $get_storage_volume_calls = 0;
+
     my ($vol_id, $vol_host, $vol_path, $vol_xattr)
         = $self->_get_storage_volume($key, $vol_name, $key->hard_volume);
@@ -273,5 +284,7 @@
                 # create storage_object
                 my $query = $db->prepare_cached( $sql->new_object ); 
-                $query->execute('NULL', $key->path, basename($key->path), $parent_id);
+# bad syntax    $query->execute('NULL', $key->path, basename($key->path), $parent_id);
+                $query->execute(0, $key->path, basename($key->path), $parent_id);
+                $query->finish;
             }
 
@@ -292,4 +305,5 @@
                 my $query = $db->prepare_cached( $sql->new_object_attr ); 
                 $query->execute($so_id);
+                $query->finish;
             }
 
@@ -300,4 +314,5 @@
                 my $query = $db->prepare_cached( $sql->new_object_instance );
                 $query->execute($vol_id);
+                $query->finish;
             }
 
@@ -327,4 +342,5 @@
                 # vol_id, uri, ins_id
                 $query->execute($vol_id, "$uri", $ins_id);
+                $query->finish;
             }
 
@@ -421,4 +437,5 @@
                     }
                     $query->finish;
+		    $db->commit;
                 }
 
@@ -441,4 +458,6 @@
                     my $query = $db->prepare_cached($sql->new_directory);
                     $query->execute($dir, $parent_id);
+                    $query->finish;
+		    $db->commit;
                 }
 
@@ -452,9 +471,8 @@
                     ($parent_id) = $query->fetchrow_array;
                     $query->finish;
+		    $db->commit;
                 }
                 die("failed to get LAST_INSERT_ID()")
                     unless $parent_id;
-
-                $db->commit;
             }
         };
@@ -712,11 +730,4 @@
         {
             type        => SCALAR|UNDEF,
-#            callbacks   => {
-#                # check that the volume name requested is valid
-#                'is valid volume name' => sub {
-#                    return 1 if not defined $_[0];
-#                    $self->_is_valid_volume_name($_[0])
-#                },
-#            },
             optional    => 1,
         },
@@ -726,15 +737,20 @@
 
     # if a volume name is explicity specified then we should make the
-    # replication onto that volume (even if there is alread an instance on that
+    # replication onto that volume (even if there is already an instance on that
     # volume) if at all possible and throw an error if we can not.
+
     # if a volume name IS NOT specified then we should make the replication
     # onto any (hopefully the best) volume that DOES NOT already have an
-    # instance on it.  If all avilable volume already have an instance on them
+    # instance on it.  If all available volumes already have an instance on them
     # then we should throw an error 
+
     # volume names implied as part of the key are *IGNORED* as the source and
     # *SHOULD NOT* be used as the destination either
 
     eval {
-        $key = parse_neb_key($key);
+	# EAM 2019.10.31 : if I supply dest_vol_name here, then
+	# $key->volume will point at that volume and the section below
+	# will correctly be testing the validity of dest_vol_name
+        $key = parse_neb_key($key, $dest_vol_name);
     };
     $log->logdie("$@") if $@;
@@ -742,8 +758,14 @@
     my $db  = $self->db($key);
 
+    ## Old comment:
     # puke if the source volume is bogus, we may want to actually use this as
     # the instance to be copied later
-    if (defined $key->volume
-        and not $self->_is_valid_volume_name($key, $key->volume)) {
+
+    # EAM 2019.10.31 : in the past, the key-implied volume was
+    # supplied here, which was inconsistent since above it says the
+    # key-implied volume is ignored. By supplying $dest_vol_name to
+    # parse_neb_key above, the key->volume now refers to the
+    # dest_volume
+    if (defined $key->volume and not $self->_is_valid_volume_name($key, $key->volume)) {
         unless ($key->hard_volume) {
             $log->warn($key->volume . " not a known volume name");
@@ -752,19 +774,26 @@
         }
     }
-    # puke if the source volume is bogus, we may want to actually use this as
-    # the instance to be copied later
-    if (defined $dest_vol_name
-        and not $self->_is_valid_volume_name($key, $dest_vol_name)) {
-           $log->logdie($key->volume . " is not a valid volume name");
-    }
-        
+
+    # puke if the destination volume is bogus
+    ## XXX if I supply dest_vol_name to parse_neb_key above, this section below is redundant with the above
+    ## if (defined $dest_vol_name
+    ##     and not $self->_is_valid_volume_name($key, $dest_vol_name)) {
+    ##        $log->logdie($key->volume . " is not a valid volume name");
+    ## }
+
+    $get_storage_volume_calls = 0;
+
     my ($vol_id, $vol_host, $vol_path, $vol_xattr);
     if (defined $dest_vol_name) {
+	# if we supplied dest_vol_name, then the call to parse_neb_key above
+	# will have set $key->volume to that value and hard_volume to match
         ($vol_id, $vol_host, $vol_path, $vol_xattr)
-            = $self->_get_storage_volume($key, $dest_vol_name);
+            = $self->_get_storage_volume($key, $key->volume, $key->hard_volume);
     } else {
         ($vol_id, $vol_host, $vol_path, $vol_xattr)
             = $self->_get_replication_volume($key);
     }
+
+    # print "selected target: $vol_id, $vol_host\n";
 
     my $uri;
@@ -784,4 +813,5 @@
                 $so_id = $query->fetchrow_hashref->{ 'so_id' };
                 $query->finish;
+		$db->commit;
             }
 
@@ -800,4 +830,5 @@
                 # time LAST_INSERT_ID() is invoked
                 $query->finish;
+		$db->commit;
             }
 
@@ -841,6 +872,6 @@
     eval {
         my $mode = $self->getxattr_object("$key", 'user.mode');
-        if (defined $mode) {
-            $self->chmod_object("$key", $mode);
+        if (defined $mode && $mode ne "") {
+	    $self->chmod_object("$key", $mode);
         }
     };
@@ -852,5 +883,4 @@
 
     $log->debug("leaving");
-
     return "$uri";
 }
@@ -1323,4 +1353,5 @@
             die( "xattr $key:$name does not exist" );
         }
+
         # if we go more then one row bad something very bad has happened.
         unless ($rows == 1) {
@@ -1335,7 +1366,10 @@
         $value = $row->{ 'value' };
     };
+    $db->commit;
+
     if ($@) {
         if ($@ =~ /user\..*? does not exist/) {
             # do not log xattr does not exist messages
+	    # NOTE: the client is using the reported message to interpret the errors
             die $@;
         }
@@ -1386,4 +1420,5 @@
     };
     $log->logdie("database error: $@") if $@;
+    $db->commit;
 
     $log->debug("leaving");
@@ -1442,5 +1477,4 @@
                 die( "affected row count is $rows instead of 1" );
             }
-
             $db->commit;
             $log->debug("commit");
@@ -1545,6 +1579,5 @@
 	$work_dir = $pattern;
 	$file_pattern = '%';
-    }
-    else {
+    } else {
 	my $dir_plain = dirname($pattern);
 	if ($dir_plain eq 'neb:') {
@@ -1575,4 +1608,5 @@
         my $query = $db->prepare_cached( $sql->find_dir_by_parent_id . " AND dirname LIKE ? ");
         $query->execute( $dir_id, $file_pattern );
+	$db->commit;
 
         while ( my $row = $query->fetchrow_hashref ) {
@@ -1595,4 +1629,5 @@
         my $query = $db->prepare_cached( $sql->find_object_by_dir_id . " AND ext_id_basename LIKE ? ");
         $query->execute( $dir_id , $file_pattern);
+	$db->commit;
 
         while ( my $row = $query->fetchrow_hashref ) {
@@ -1624,5 +1659,4 @@
     my $sql = $self->sql;
     my $db  = $self->_db_for_index($index);
-
 
     # first check to see if the key is an exact match
@@ -1645,4 +1679,5 @@
         $log->logdie("database error: $@");
     }
+    $db->commit;
 
     if (scalar @keys) {
@@ -1678,4 +1713,5 @@
     };
     $log->logdie("database error: $@") if $@;
+    $db->commit;
 
     # find files under dir
@@ -1692,4 +1728,5 @@
     };
     $log->logdie("database error: $@") if $@;
+    $db->commit;
 
     $log->debug( "leaving" );
@@ -1753,4 +1790,5 @@
 }
 
+# sub find_instances
 sub find_instances_old
 {
@@ -1769,11 +1807,4 @@
         {
             type        => SCALAR|UNDEF,
-#            callbacks   => {
-#                # check that the volume name requested is valid
-#                'is valid volume name' => sub {
-#                    return 1 if not defined $_[0];
-#                    $self->_is_valid_volume_name($_[0])
-#                },
-#            },
             optional    => 1,
         },
@@ -1787,8 +1818,6 @@
     my $sql = $self->sql;
 
-#    unless ($key) {
-#        $log->warn("key was undefined after validate_pos(), trying again...");
-#        return $self->find_instances(@_);
-#    }
+    # default value for find_invalid is false
+    if (not defined $find_invalid) { $find_invalid = 0; }
 
     # vol_name overrides the key implied volume
@@ -1828,5 +1857,6 @@
 	    my $rows;
             # ext_id, available
-	    if (defined($find_invalid)) {
+	    if (defined($find_invalid) and $find_invalid) {
+		# XXX returns instances which are NOT available
 		$rows = $query->execute($key->path, 0);
 	    }
@@ -1865,5 +1895,5 @@
 }
 
-#sub find_instances_by_proximity
+# sub find_instances_by_proximity
 sub find_instances
 {
@@ -1882,11 +1912,4 @@
         {
             type        => SCALAR|UNDEF,
-#            callbacks   => {
-#                # check that the volume name requested is valid
-#                'is valid volume name' => sub {
-#                    return 1 if not defined $_[0];
-#                    $self->_is_valid_volume_name($_[0])
-#                },
-#            },
             optional    => 1,
         },
@@ -1897,11 +1920,11 @@
         }, 
     );
-
     my $sql = $self->sql;
 
-#    unless ($key) {
-#        $log->warn("key was undefined after validate_pos(), trying again...");
-#        return $self->find_instances(@_);
-#    }
+    if (not defined $find_invalid) { $find_invalid = 0; }
+
+    if ($find_invalid eq "find them all") {
+	$log->logdie("old neb-cull --one_only, neb-rm --invalid both disabled by new Server.pm");
+    }
 
     # vol_name overrides the key implied volume
@@ -1932,6 +1955,4 @@
 	    }
 	}
-
-
     }
 
@@ -1972,17 +1993,25 @@
             # ext_id, name, available
 	    # host_vol_id host_cab_id host_site_id ext_id available
-            my $rows = $query->execute($h_vol_id, $h_cab_id, $h_site_id, $key->path, 1);
+
+	    my $rows;
+	    if (defined($find_invalid) and $find_invalid) {
+		# returns instances which are NOT available (volume not available)
+		$rows = $query->execute($h_vol_id, $h_cab_id, $h_site_id, $key->path, 0);
+	    } else {
+		$rows = $query->execute($h_vol_id, $h_cab_id, $h_site_id, $key->path, 1);
+	    }		
             unless ($rows > 0) {
                 $query->finish;
-                die("no instances on storage volume or volume is not avaiable for key: $key volume: $vol_name");
+                die("no instances on storage volume or volume is not available for key: $key volume: $vol_name");
             }
         } else {
             $query = $db->prepare_cached( $sql->get_object_instances );
+            # ext_id, available
+
 	    my $rows;
-            # ext_id, available
-	    if (defined($find_invalid)) {
+	    if (defined($find_invalid) and $find_invalid) {
+		# returns instances which are NOT available (volume not available)
 		$rows = $query->execute($key->path, 0);
-	    }
-	    else {
+	    } else {
 		$rows = $query->execute($key->path, 1);
 	    }
@@ -1992,8 +2021,13 @@
             }
         }
+	$db->commit;
+	## if we do not call commit here, the transaction stays
+	## open blocking some operations below. 
 
         while (my $row = $query->fetchrow_hashref) {
             my $instance = $row->{ 'uri' };
             push @locations, $instance if $instance;
+
+	    # Carp::carp ("instance 2: $row->{ 'uri' }, $row->{ 'vol_id' }, $row->{ 'cab_id' }, $row->{ 'vol_idx' }\n");
         }
     };
@@ -2003,5 +2037,5 @@
         if (defined $vol_name and not defined $key->hard_volume) {
             $log->debug("retrying with 'any' volume");
-            return $self->find_instances($key->path, 'any');
+            return $self->find_instances($key->path, 'any', $find_invalid);
         }
         $log->logdie("database error: $@");
@@ -2018,4 +2052,8 @@
 }
 
+# this method returns instances on the specified volume
+# or a list of all available instances
+# it does NOT choose instances based on proximity
+# and it does NOT return invalid instances
 sub find_instances_for_cull
 {
@@ -2061,4 +2099,8 @@
     my $db  = $self->db($key);
 
+    ## XXX this method is missing the alias deference section (see find_instances)
+    ## if aliases are intended to be compute nodes in the same cabinet / site as
+    ## the storage nodes, then this is not needed.
+
     # the key's volume can't be validiated on input for this method so we have
     # to check it after parsing the key
@@ -2082,5 +2124,5 @@
             unless ($rows > 0) {
                 $query->finish;
-                die("no instances on storage volume or volume is not avaiable for key: $key volume: $vol_name");
+                die("no instances on storage volume or volume is not available for key: $key volume: $vol_name");
             }
         } else {
@@ -2105,10 +2147,13 @@
         $db->rollback;
         # handle soft volumes
-        if (defined $vol_name and not defined $key->hard_volume) {
+	# we need to call find_intances_for_cull here so the returned structure 
+	# is the same (find_instances just returns an array of strings)
+        if (defined $vol_name and not defined $key->hard_volume and ($vol_name ne "any")) {
             $log->debug("retrying with 'any' volume");
-            return $self->find_instances($key->path, 'any');
+            return $self->find_instances_for_cull($key->path, 'any');
         }
         $log->logdie("database error: $@");
     }
+    $db->commit;
 
     # XXX remove this?
@@ -2222,5 +2267,4 @@
                 }
             }
-
             $db->commit;
             $log->debug("commit");
@@ -2282,4 +2326,5 @@
         $stat = $query->fetchrow_arrayref;
         $query->finish;
+	$db->commit;
     };
     $log->logdie("database error: $@") if $@;
@@ -2318,4 +2363,5 @@
     };
     $log->logdie("database error: $@") if $@;
+    $db->commit;
 
     $log->logdie("no mounted volumes found") unless (scalar @$stats);
@@ -2415,5 +2461,9 @@
     my ($key, $name, $hard_volume) = @_;
     
-#    $log->warn("_g_s_v: key:>$key< name:>$name< hard_vol:>$hard_volume<");
+    # track the number of calls to this function and
+    # give up after 10 attempts
+    $get_storage_volume_calls ++;
+
+#   $log->warn("_g_s_v: key:>$key< name:>$name< hard_vol:>$hard_volume<");
     my $sql = $self->sql;
     my $db  = $self->db($key);
@@ -2427,7 +2477,8 @@
             # %free, name, avaiable, allocate
             $rows = $query->execute($max_used_space, $name, 1, 1);
-            # XXX destinguish between non-existant and unavailable
+            # XXX distinguish between non-existant and unavailable
             unless ($rows > 0) {
                 $query->finish;
+		$db->commit;
 
                 # if a volume name was specified, and is soft, and we failed to
@@ -2442,4 +2493,5 @@
             if ($rows > 1) {
                 $query->finish;
+		$db->commit;
                 die("affected row count is $rows instead of 1");
             }
@@ -2449,8 +2501,12 @@
             $rows = $query->execute($max_used_space, 1, 1, $topfew_count);
 #	    $log->warn("Storage_volume: $rows $topfew_count");
-            # there has to be atleast one storage volume
+            # there has to be at least one storage volume
             unless ($rows > 0) {
                 $query->finish;
-                die("no storage volume is available for key: $key volume: $name hard_volume: $hard_volume");
+		$db->commit;
+		# prevent failure in the die due to undefined variables
+		my $hard_volume_str = defined $hard_volume ? $hard_volume : "undefined";
+		my $name_str = defined $name ? $name : "undefined";
+                die("no storage volume is available for key: $key volume: $name_str hard_volume: $hard_volume_str");
             }
         }
@@ -2465,5 +2521,9 @@
             $log->error($@);
             $log->debug("retrying...");
-            return $self->_get_storage_volume(@_);
+	    if ($get_storage_volume_calls < 10) {
+		return $self->_get_storage_volume(@_);
+	    }
+	    # else
+	    $log->logdie("no available storage volume: $@");
         } 
         # else
@@ -2502,5 +2562,5 @@
 	unless ($rows > 0) {
 	    $query->finish;
-	    die("Requested key $key does not exist");
+	    die("Requested key $key does not exist (or cabinet is undefined)");
 	}
 	if ($rows == 1) {
@@ -2513,16 +2573,18 @@
 	    }
 	    $query->finish;
-	}
-	else {
+	} else {
+	    # if instances are spread across multiple cabinets, allow the next instance to go anywhere
+	    # NOTE: this does not prevent the new instance from going to the same volume as one of the existing instances
 	    $forbidden_cabinet = 0;
 	    $forbidden_site    = 0;
 	    $query->finish;
 	}
-	    
+	$db->commit;
 
         $query = $db->prepare_cached( $sql->get_replication_volume_for_ext_id );
-        # ext_id, %free, avaiable, allocate
+        # ext_id, %free, available, allocate
+
         $rows = $query->execute($key->path, $max_used_space, 1, 1, $forbidden_cabinet, $forbidden_site, $topfew_count);
-        # XXX destinguish between non-existant and unaviable
+        # XXX distinguish between non-existant and unavailable
         unless ($rows > 0) {
             $query->finish;
@@ -2544,4 +2606,5 @@
         ($vol_id, $vol_host, $vol_path, $xattr, $free) = $query->fetchrow_array;
         $query->finish;
+	$db->commit;
     };
     $log->logdie("database error: $@") if $@;
@@ -2590,4 +2653,6 @@
         ($ext_id) = $query->fetchrow_array;
         $query->finish;
+        $db->commit;
+	## if we do not call commit here, the transaction stays open blocking some operations below
     };
     if ($@) {
@@ -2612,5 +2677,6 @@
 }
 
-
+# in the past, _is_valid_volume_name returned 'undef'.  
+# now it either returns 1 (success) or 0 (failure)
 sub _is_valid_volume_name
 {
@@ -2650,4 +2716,5 @@
         ($vol_id, $vol_path, $free) = $query->fetchrow_array;
         $query->finish;
+        $db->commit;
     };
     $log->logdie("database error: $@") if $@;
